What Are Embeddings?
Embeddings are dense vector representations of data (text, images, audio) that capture semantic meaning in a continuous, high-dimensional space. Similar concepts are mapped to nearby points, enabling machines to understand relationships, perform similarity searches, and support downstream ML tasks.
In the context of LLMs, text embeddings convert words, sentences, or documents into fixed-size vectors (typically 384 to 4096 dimensions) that encode semantic content. These vectors are the foundation for Retrieval-Augmented Generation (RAG), semantic search, clustering, and classification.
How Text Embeddings Work
The Embedding Process
- Tokenization: Split text into tokens (words, subwords, or characters)
- Token Embedding: Map each token to a learned vector
- Contextual Encoding: Pass through transformer layers to capture context
- Pooling: Aggregate token embeddings into a single vector (mean, CLS, max)
- Normalization: L2-normalize for cosine similarity comparisons
# Example using OpenAI embeddings
from openai import OpenAI
client = OpenAI()
response = client.embeddings.create(
model="text-embedding-3-small",
input="Machine learning is transforming industries"
)
embedding = response.data[0].embedding
print(f"Dimensions: {len(embedding)}") # 1536
print(f"First 5 values: {embedding[:5]}")
# [0.023, -0.045, 0.012, 0.078, -0.034]
Similarity Metrics
Once you have embeddings, you need a way to measure how similar two vectors are. The choice of metric affects retrieval quality and performance.
Cosine Similarity
Measures the angle between vectors. Range: [-1, 1]. Most common for text embeddings.
cos(A,B) = A·B / (|A||B|)
Euclidean Distance
Measures straight-line distance. Smaller = more similar. Good for dense clusters.
d(A,B) = √Σ(Aᵢ-Bᵢ)²
Dot Product
Raw similarity score. Fastest but affected by vector magnitude.
A·B = Σ(Aᵢ × Bᵢ)
💡 Best Practice: For normalized embeddings (L2 norm = 1), cosine similarity equals dot product. Most embedding models normalize outputs, so dot product is faster with identical results.
Popular Embedding Models
| Model | Provider | Dimensions | Max Tokens | Notes |
|---|---|---|---|---|
| text-embedding-3-large | OpenAI | 3072 | 8191 | Best quality, variable dimensions |
| text-embedding-3-small | OpenAI | 1536 | 8191 | Cost-effective, good balance |
| voyage-3 | Voyage AI | 1024 | 32000 | Long context, excellent for RAG |
| embed-v3 | Cohere | 1024 | 512 | Multilingual, input type support |
| bge-large-en-v1.5 | BAAI (Open) | 1024 | 512 | Open-source, MTEB top performer |
| e5-large-v2 | Microsoft (Open) | 1024 | 512 | Open-source, versatile |
| nomic-embed-text-v1.5 | Nomic (Open) | 768 | 8192 | Long context, fully open weights |
| all-MiniLM-L6-v2 | Sentence Transformers | 384 | 256 | Tiny, fast, good for prototyping |
How to Choose an Embedding Model
Consider Quality
- Check MTEB benchmark scores for your use case
- Test on your actual data—benchmarks don't tell everything
- Higher dimensions often (not always) = better quality
Consider Context Length
- Match model context to your chunk size
- Long-context models for documents, short for queries
- Truncation silently drops important content
Consider Cost
- API costs for embedding millions of documents
- Storage costs scale with dimensions × document count
- Open-source models eliminate per-token costs
Consider Latency
- API calls add network latency
- Smaller models are faster for self-hosted inference
- Batch embedding is more efficient than single requests
Vector Databases
To search embeddings efficiently at scale, you need a vector database with Approximate Nearest Neighbor (ANN) indexing. Key options:
| Database | Type | Best For |
|---|---|---|
| Pinecone | Managed SaaS | Production workloads, zero ops |
| Weaviate | Open Source / Cloud | Hybrid search, GraphQL API |
| Qdrant | Open Source / Cloud | Advanced filtering, Rust performance |
| Milvus | Open Source | Billion-scale, GPU acceleration |
| Chroma | Open Source | Local development, simple API |
| pgvector | PostgreSQL Extension | Existing Postgres infrastructure |
| FAISS | Library (Meta) | Low-level control, research |
# Example: Storing and searching with Chroma
import chromadb
from chromadb.utils import embedding_functions
# Initialize
client = chromadb.Client()
ef = embedding_functions.OpenAIEmbeddingFunction(
model_name="text-embedding-3-small"
)
# Create collection
collection = client.create_collection(
name="documents",
embedding_function=ef
)
# Add documents (automatically embedded)
collection.add(
documents=["Machine learning basics", "Deep learning fundamentals"],
ids=["doc1", "doc2"]
)
# Query (automatically embedded and searched)
results = collection.query(
query_texts=["What is neural network?"],
n_results=2
)
ANN Indexing Algorithms
Exact nearest neighbor search is O(n)—too slow for large datasets. Approximate algorithms trade accuracy for speed:
HNSW
Hierarchical Navigable Small World. Graph-based, excellent recall, higher memory usage. Default for most vector DBs.
IVF (Inverted File)
Clusters vectors into buckets. Faster build time, lower memory, slightly lower recall. Good for very large datasets.
PQ (Product Quantization)
Compresses vectors into compact codes. Massive memory reduction, some quality loss. Often combined with IVF.
ScaNN
Google's optimized implementation. Learned quantization, excellent speed-accuracy tradeoff.
Common Use Cases
Semantic Search
Find documents by meaning, not keywords. "How to fix login issues" matches "Authentication troubleshooting guide".
RAG (Retrieval-Augmented Generation)
Retrieve relevant context to ground LLM responses in factual data. The backbone of enterprise AI assistants.
Duplicate Detection
Identify near-duplicate content, support tickets, or documents even when wording differs.
Recommendation Systems
"Users who liked X also liked Y"—based on content similarity rather than collaborative filtering.
Classification & Clustering
Use embeddings as features for classifiers, or cluster documents to discover topics and patterns.
Best Practices
- Use the same model for queries and documents: Different models produce incompatible embedding spaces.
- Normalize your embeddings: Most modern models do this automatically, but verify for your specific model.
- Chunk intelligently: Split long documents into meaningful segments (paragraphs, sections) before embedding.
- Consider asymmetric embeddings: Some models have separate modes for short queries vs. long documents (e.g., Cohere input_type).
- Batch your API calls: Embedding APIs support batching—use it for better throughput and lower costs.
- Monitor embedding drift: If your model or data changes, re-embed your corpus to maintain consistency.
- Store metadata: Always store original text and metadata alongside vectors for context in retrieval results.
Related Topics
- Retrieval-Augmented Generation (RAG)
- Chunking Strategies
- Transformers Architecture
- Semantic Search
- 🔧 RAG Visualizer Tool — Interactive visualization of embeddings and retrieval
Test Your Knowledge
Score 8/10 or higher to pass
You need to be logged in to take this quiz.
Login to Continue