Choosing an Embedding Model

Matt George

Fractional CTO · Founder of Injuria.ai

•11 min read•

An embedding model is a foundational component for modern AI applications. It translates complex, high-dimensional data like text, images, or audio into a compact numerical representation called a vector. The model's goal is to arrange these vectors in a high-dimensional space such that semantically similar items are positioned close to one another. This capability is the engine behind effective semantic search, retrieval-augmented generation (RAG), recommendation systems, and data clustering. Selecting the right embedding model is a critical architectural decision that directly impacts system performance, cost, and the quality of the end-user experience. The choice determines how well a RAG system finds relevant context for a large language model, how accurate a search function is, and how useful a product recommendation becomes.

How an Embedding Model Works

At its core, a text embedding model is a function that maps a variable-length string of text to a fixed-length numerical vector. While various architectures exist, the vast majority of modern, high-performance models are based on the Transformer architecture. The process of turning text into a vector involves several distinct steps.

Step 1: Tokenization

The first step is tokenization[1], where the input text is broken down into smaller units called tokens. This process is more sophisticated than simply splitting by spaces or punctuation. Modern models use subword tokenization algorithms, such as Byte-Pair Encoding (BPE)[2] or WordPiece[3]. These methods create a vocabulary of frequently occurring character sequences, allowing them to represent any word, including rare, misspelled, or out-of-vocabulary terms, as a sequence of known subword units. For example, the word "embedding" might be tokenized into em, bed, and ding. This approach provides a robust way to handle the vastness of natural language.

Step 2: Input Representation

Once tokenized, the sequence of tokens is converted into a sequence of numerical vectors. In a standard Transformer model[4], the initial vector for each token is typically a sum of three separate embeddings:

  1. Token Embeddings: A learned vector from a lookup table that corresponds to the specific token ID from the vocabulary.
  2. Positional Embeddings: A vector that encodes the position of the token within the sequence. Since the core Transformer architecture processes all tokens in parallel, this information is essential for the model to understand word order.
  3. Segment Embeddings: Used for tasks that involve sentence pairs (like question answering), these embeddings help the model distinguish between the first and second text inputs.

Step 3: Encoder Layers

The sequence of initial vectors is then processed by a stack of identical encoder layers. Each encoder layer contains two primary sub-components. The first is a self-attention mechanism. This is the defining feature of the Transformer. It allows the model to weigh the importance of every other token in the sequence when computing the representation for a single token. For instance, in the sentence "He deposited money in the bank," the self-attention mechanism learns to associate "bank" strongly with "money" and "deposited," generating a contextually specific representation for a financial institution. The second sub-component is a position-wise feed-forward neural network, which applies a nonlinear transformation to each token's representation. These layers are stacked, allowing the model to build progressively more complex and abstract representations of the text.

Step 4: Pooling

After passing through the final encoder layer, the model has produced a sequence of context-aware vectors, one for each input token. To create a single vector that represents the entire input text (a "sentence embedding"), these token vectors must be aggregated. This step is known as pooling. Common strategies include:

  • Mean Pooling: Calculate the element-wise average of all the output token vectors. This simple method is a surprisingly effective and common default, as it incorporates information from the entire sequence.
  • CLS Pooling: Many models are pre-trained with a special [CLS] token at the beginning of the input. The output vector corresponding to this [CLS] token is sometimes used as the aggregate sentence representation. However, this method is only effective if the model has been specifically fine-tuned to use the [CLS] token for this purpose.

Step 5: Normalization

As a final step, the resulting pooled vector is often normalized to have a unit length of 1 using L2 normalization[5]. This is a critical optimization for downstream search tasks. When all vectors in a collection are normalized, the cosine similarity[6] between any two vectors, a measure of the angle between them, can be calculated with a simple dot product. The dot product is computationally much faster than a full cosine similarity calculation, enabling efficient, large-scale similarity searches in vector databases.

A Brief History and Context

The concept of representing words as vectors is not new. Early breakthroughs like Word2Vec[7] (Google, 2013) and GloVe[8] (Stanford, 2014) produced powerful static embeddings. These models assigned a single, fixed vector to each word in their vocabulary. Their main limitation was a lack of context; the word "bank" had the same vector representation in "river bank" as it did in "investment bank."

The 2017 publication of the Transformer architecture marked a paradigm shift toward contextual embeddings. Models like BERT[9] (Google, 2018) used the Transformer's self-attention mechanism to generate word representations that changed based on the surrounding text. This dramatically improved performance on a wide range of NLP tasks.

However, a crucial refinement was necessary for semantic search. In 2019, the paper on Sentence-BERT (SBERT)[10] demonstrated that the raw outputs from a standard BERT model were not suitable for similarity comparison. The authors showed that BERT needed to be fine-tuned using a siamese network structure on sentence-pair datasets. This process explicitly trained the model to map semantically similar sentences to nearby points in the vector space. Nearly all modern text embedding models are based on this principle, starting with a powerful pre-trained transformer and fine-tuning it for the specific task of generating sentence-level embeddings.

A Concrete Example

You can generate embeddings and perform similarity searches with just a few lines of Python using open-source libraries like sentence-transformers. This example uses the popular and lightweight all-MiniLM-L6-v2 model.

from sentence_transformers import SentenceTransformer, util

# 1. Load a pre-trained model
# This model maps sentences & paragraphs to a 384-dimensional dense vector space.
model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')

# A corpus of documents to search through
corpus = [
 'The International Space Station is a modular space station in low Earth orbit.',
 'A financial institution that accepts deposits and channels them into lending activities.',
 'The Amazon River is the largest river by discharge volume of water in the world.',
 'Artificial intelligence is intelligence demonstrated by machines.',
]

# 2. Generate embeddings for the corpus
corpus_embeddings = model.encode(corpus, convert_to_tensor=True)

# The user's query
query = 'What is a bank?'

# 3. Generate an embedding for the query
query_embedding = model.encode(query, convert_to_tensor=True)

# 4. Compute cosine similarity between the query and all corpus documents
# The result is a tensor of scores.
cosine_scores = util.cos_sim(query_embedding, corpus_embeddings)

# 5. Find the most similar document
best_match_index = cosine_scores.argmax()

print(f"Query: {query}")
print(f"Best match from corpus: '{corpus[best_match_index]}' (Score: {cosine_scores[0][best_match_index]:.4f})")

# Expected output:
# Query: What is a bank?
# Best match from corpus: 'A financial institution that accepts deposits and channels them into lending activities.' (Score: 0.7583)

This example demonstrates the end-to-end flow: loading a model, encoding a collection of texts into a matrix of vectors, encoding a query, and using cosine similarity to find the most relevant entry in the collection.

The Decision Framework: Tradeoffs and Costs

Choosing an embedding model requires balancing performance, cost, and operational complexity. There is no single "best" model for all use cases.

Performance vs. Cost

The primary tradeoff is between the quality of the embeddings and the cost to generate and store them. Several factors are at play:

  • Embedding Dimension: This is the length of the vector produced by the model. Common dimensions are 384, 768, and 1024, with some models exceeding 4000. Higher dimensions can capture more semantic nuance but come with direct costs. Storage requirements in a vector database[11] scale linearly with dimensionality. Search and retrieval algorithms (like Approximate Nearest Neighbor search) can also become slower and less accurate as dimensionality increases, a phenomenon known as the curse of dimensionality.
  • Model Size: Larger models with more parameters tend to produce higher-quality embeddings but are slower and more expensive to run. Inference latency (the time to generate one embedding) and throughput (embeddings per second) are critical metrics. A model that is too slow can become a bottleneck in real-time applications.
  • Context Length: This is the maximum number of tokens the model can process in a single input. Older models were often limited to 512 tokens. The maximum sequence length for BAAI's bge-large-en-v1.5[12] is 512 tokens, and the model will only process the first 512 tokens of a longer input. While powerful, processing longer sequences requires significantly more computation and memory.

To evaluate performance objectively, use a benchmark. The Massive Text Embedding Benchmark (MTEB)[13] is the industry standard, and the public Hugging Face MTEB Leaderboard[14] is an essential resource for comparing the performance of hundreds of open-source models across tasks like retrieval, clustering, and classification.

Open Source vs. Proprietary APIs

Another major decision is whether to self-host an open-source model or use a managed API from a provider.

  • Open-Source Models: Models available on platforms like Hugging Face (e.g., BGE, GTE, E5 models) offer maximum control. You can run them on your own infrastructure (on-premise or in the cloud), ensuring data privacy and avoiding per-call costs. This path also allows for fine-tuning the model on your proprietary data for superior domain-specific performance. The downside is the operational burden. You are responsible for provisioning GPUs, managing inference servers, ensuring high availability, and scaling the system.

  • Proprietary APIs: Services like OpenAI's Embedding API[15], Cohere's Embed API[16], and Google's Text Embedding API[17] offer simplicity. They are fully managed, highly scalable, and often provide state-of-the-art performance with minimal setup. The tradeoffs are cost (typically priced per token), data privacy (you are sending your data to a third party), and vendor lock-in. If you build your system around a specific provider's embeddings, migrating to another model later can be a significant undertaking.

Domain Specificity

A model trained on a general corpus of web text may not understand the specialized vocabulary of domains like law, finance, or medicine. If your application operates in a niche area, a general-purpose model's performance may be disappointing. In this case, you should consider finding a model already fine-tuned on a similar domain or undertaking a fine-tuning project yourself. Fine-tuning can produce dramatic performance gains but requires a high-quality labeled dataset (e.g., pairs of queries and relevant documents) and machine learning expertise.

Failure Modes to Anticipate

Embedding models are powerful but not infallible. Technical leaders must be aware of their limitations.

  • Nuance and Negation: Models can struggle with subtle linguistic phenomena like sarcasm, humor, and negation. The sentence "This laptop is not good" might be embedded closer to "This laptop is good" than to "This laptop is bad," because they share many of the same tokens.
  • Factual Incorrectness: Embeddings capture semantic similarity, not factual correctness. A search for "side effects of aspirin" might retrieve a document that is well-written and semantically on-topic but contains dangerously incorrect medical advice. The embedding model's job is retrieval, not verification.
  • Inherent Bias: Models trained on vast internet datasets will learn and perpetuate the societal biases present in that data. These biases, related to gender, race, nationality, and other attributes, are encoded in the vector space and can lead to unfair or harmful application behavior if not carefully audited and mitigated.

Common Misconceptions Corrected

Misconception 1: "A higher embedding dimension is always better."
This is false. While a larger dimension provides more capacity, performance often plateaus or even degrades after a certain point. Meanwhile, storage and computation costs increase linearly. The optimal dimension is task-dependent, and a smaller, well-trained vector can often outperform a larger, less-optimized one.

Misconception 2: "You can use the output of any large language model as an embedding."
This is a common and costly mistake. As the Sentence-BERT paper showed, the raw hidden states of a generic language model like BERT or GPT are not optimized for similarity search. Models must be specifically fine-tuned on similarity tasks to produce useful sentence embeddings. Using a base model will lead to poor retrieval performance.

Misconception 3: "Embeddings capture true 'meaning'."
Embeddings capture complex statistical relationships learned from their training data. This serves as a powerful and effective proxy for meaning, but it is not equivalent to human understanding or reasoning. They model co-occurrence and contextual patterns, not truth, logic, or intent.

The State of Embeddings Today

The field is advancing rapidly, but the current landscape is centered on a few key trends. Transformer-based models fine-tuned with SBERT-like methods are the dominant architecture. The MTEB leaderboard serves as the de facto proving ground for new models, with fierce competition between academic labs and corporate research teams.

Among proprietary models, providers are differentiating with unique features. OpenAI's text-embedding-3 series, for example, was trained using Matryoshka Representation Learning (MRL)[18]. This technique allows developers to truncate the full-size embedding vector to a smaller dimension at inference time, providing a flexible tradeoff between performance and cost without needing to switch models. Cohere's embed-v3 models offer different input_type parameters optimized for different retrieval tasks, such as searching short queries versus classifying long documents.

Open-source models like bge-large-en-v1.5 and the E5 model family remain highly competitive, often outperforming proprietary alternatives on public benchmarks. The choice between open-source and proprietary is less about raw quality and more about the strategic decision of control versus convenience. As you choose a model, consider not just today's leaderboard but also your team's capabilities, your application's requirements, and the total cost of ownership for the path you select.

Sources (18)
  1. Wikipedia: Tokenization (lexical analysis)
  2. Wikipedia: Byte-pair encoding
  3. Hugging Face Docs: Tokenizer Summary (WordPiece)
  4. arXiv: Attention Is All You Need
  5. Wikipedia: Norm (mathematics) #Euclidean norm
  6. Wikipedia: Cosine similarity
  7. arXiv: Efficient Estimation of Word Representations in Vector Space (Word2Vec)
  8. Stanford NLP Group: GloVe: Global Vectors for Word Representation
  9. arXiv: BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding
  10. arXiv: Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks
  11. Wikipedia: Vector database
  12. Hugging Face Model Card: BAAI/bge-large-en-v1.5
  13. arXiv: MTEB: Massive Text Embedding Benchmark
  14. Hugging Face Spaces: Massive Text Embedding Benchmark (MTEB) Leaderboard
  15. OpenAI API Documentation: Embeddings
  16. Cohere Docs: Embed API
  17. Google Cloud Docs: Get text embeddings
  18. arXiv: Matryoshka Representation Learning

Recommended reading

Mixture of Experts, Explained12 min readMixture of Experts (MoE) is a neural network architecture that increases model capacity without a proportional rise in computation by conditionally activating only a fraction of its parameters, known as 'experts', for any given input.The History of Neural Networks16 min readFrom the perceptron to the backpropagation revival and the GPU-and-data moment that finally made deep learning work.Speculative Decoding: How LLMs Generate Faster12 min readSpeculative decoding accelerates large language model inference by using a smaller, faster model to draft text that a larger, more powerful model then verifies in parallel, significantly reducing generation latency without compromising output quality.Structured Data Extraction With LLMs: When It Beats Hand-Written Parsers12 min readLarge Language Models can extract structured data like JSON from unstructured text with surprising reliability, but the mechanism and tradeoffs determine when this approach is superior to traditional parsers.Context Windows: What They Cost and How to Use Them Well13 min readA context window is the measure of text an AI model can consider at once to process a request and generate a response. Understanding its technical mechanisms, costs, and failure modes is critical for making sound engineering decisions about when to use large contexts versus alternative architectures like RAG.How Attention Works in Large Language Models13 min readA technical explanation of the attention mechanism in LLMs, from its conceptual origins to the mathematical details of Scaled Dot-Product Attention and its practical implications for engineering leaders.