An embedding is a learned, dense, continuous vector representation that maps discrete symbolic entities—such as subword tokens, sentences, code snippets, or multimodal images—into a continuous low-dimensional geometric manifold $\mathbb{R}^d$ where spatial proximity reflects semantic, syntactic, or functional similarity. In contrast to sparse, orthogonal representations (such as one-hot encodings or BM25 bag-of-words vectors where orthogonal axes treat every token as completely equidistant and devoid of intrinsic relationship), dense embeddings pack semantic relationships into continuous geometric coordinates. Within an embedding manifold, algebraic operations correspond to semantic transformations (the canonical linguistic analogy $\vec{v}_{\text{king}} - \vec{v}_{\text{man}} + \vec{v}_{\text{woman}} \approx \vec{v}_{\text{queen}}$), and geometric distance metrics—predominantly cosine similarity and inner product—quantify conceptual alignment. In modern artificial intelligence systems, embeddings serve two distinct architectural roles: internal token embeddings ($W_{\text{embed}} \in \mathbb{R}^{|V| \times d_{\text{model}}}$) that initialize neural representations inside transformer blocks, and pooled sentence/document embeddings (produced by bi-encoders like BGE, E5, and OpenAI text-embedding-3) that power vector databases, semantic search, and Retrieval-Augmented Generation (RAG). At an engineering level, the sentence embedding and vector retrieval pipeline operates across structured mathematical stages:
A few principles are essential for understanding how embeddings are trained, how Matryoshka Representation Learning compresses memory footprints, and why bi-encoders differ fundamentally from cross-encoders in RAG architectures:
The contrastive learning framework, InfoNCE loss, and sequence pooling. Modern sentence and document embedding models (such as BGE-M3, E5-v2, and GTE) are trained via *contrastive learning* over massive batches of paired positive passages $(q_i, p_i^+)$ and negative passages $p_{i,j}^-$. Rather than predicting masked tokens, the model's objective is to pull semantically related query-document pairs close together on the unit hypersphere while repelling irrelevant documents. Training is governed by the symmetric *InfoNCE loss* (Information Noise-Contrastive Estimation) parameterized by temperature hyperparameter $\tau$:
The denominator leverages *in-batch negatives* (all other positive documents $p_j^+$ in a batch of size $B$ serve as negative distractors for query $q_i$) alongside mined *hard negatives* (passages with high lexical overlap but irrelevant semantic answers). To produce a single sequence vector $\mathbf{v} \in \mathbb{R}^d$ from the final transformer hidden state matrix $\mathbf{H} \in \mathbb{R}^{T \times d}$, modern architectures evaluate three primary pooling strategies:
1. *Mean Pooling:* Computes the element-wise average across all unmasked token vectors:
Mean pooling captures the aggregate semantic gist of an entire passage and serves as the default standard for SBERT, E5, and BGE models.
2. *[CLS] Token Pooling:* Extracts the final hidden state of the first sequence token $\mathbf{h}_{\text{[CLS]}}$, which attends across all positions via bidirectional self-attention.
3. *Last-Token Pooling:* In decoder-only embedding models (such as Mistral-Embed and LLM2Vec), pooling extracts the hidden state of the final token $\mathbf{h}_T$, preserving causal autoregressive context accumulation. The geometric structure of a continuous semantic embedding manifold is illustrated below:
Bi-encoders vs. Cross-encoders and Matryoshka Representation Learning (MRL). In production retrieval architectures, machine learning engineers navigate a fundamental trade-off between retrieval speed and contextual scoring precision:
1. *Bi-Encoder Architecture (Fast k-NN Retrieval):* A bi-encoder processes the query $\mathbf{q}$ and candidate documents $\mathbf{d}$ independently through separate forward passes (or the same Siamese network). Because document embeddings are calculated offline and indexed into approximate nearest neighbor (ANN) vector databases (such as Milvus, Qdrant, or FAISS), querying 10 million passages requires only a single query forward pass followed by sub-millisecond dot-product matrix multiplication ($\mathcal{O}(d)$ per item). However, because the query and document tokens cannot attend to each other via self-attention, fine-grained cross-token interactions are lost.
2. *Cross-Encoder Architecture (High-Precision Reranking):* A cross-encoder concatenates the query and document into a single sequence `[CLS] query [SEP] document [EOS]` and passes it through all transformer self-attention layers. Every query token directly computes attention scores against every document token ($\mathcal{O}((L_q + L_d)^2)$ complexity). While dramatically more accurate, running a cross-encoder across millions of candidate documents is computationally impossible at scale. Production RAG pipelines therefore employ a *two-stage retrieval funnel*: a fast bi-encoder retrieves the top-100 candidates, which are subsequently reranked by a cross-encoder to surface the top-5 passages to the LLM.
3. *Matryoshka Representation Learning (MRL):* Pioneered by Kusupati et al. (NeurIPS, 2022) and implemented in OpenAI `text-embedding-3`, MRL trains embeddings such that the most critical semantic information is compressed into the first $k$ dimensions (e.g., $d \in \{64, 128, 256, 512, 1536\}$). By truncating a 1536-dimensional vector to 256 dimensions, engineers reduce vector storage and network transfer overhead by $6\times$ while retaining over 98% of downstream retrieval accuracy. The execution structure of the two-stage retrieval cascade is illustrated below:
Comparative embedding models, dimensionalities, and retrieval characteristics. Production AI applications deploy specialized embedding architectures calibrated to latency constraints, memory budgets, and domain specialization:
| Model Family / Architecture | Vector Dimension ($d$) | Context Window | Pooling Strategy | Quantization Support | Primary Production Utility |
|---|---|---|---|---|---|
| OpenAI `text-embedding-3-large` | $256 - 3072$ (MRL) | $8192$ tokens | Proprietary pooled | Native dimension slicing & int8 | General-purpose enterprise RAG with flexible dimension truncation |
| BAAI `bge-m3` | $1024$ | $8192$ tokens | Dense, Lexical, & Multi-Vector | int8 / uint8 SQ | Multi-lingual hybrid search (dense semantic + sparse lexical ColBERT) |
| Microsoft `e5-mistral-7b-instruct` | $4096$ | $32768$ tokens | Last-token pooling | 4-bit / 8-bit weight | Frontier retrieval accuracy on complex multi-paragraph technical texts |
| Sentence-BERT `all-MiniLM-L6-v2` | $384$ | $512$ tokens | Mean pooling | int8 / binary | Ultra-fast edge device embedding and high-throughput real-time clustering |
| Cohere `embed-v3` | $1024$ | $512$ tokens | Multi-stage contrastive | Native binary / int8 modes | Enterprise search featuring search-optimized compression modes |
Read embeddings through a *geometric-semantic-manifold* lens rather than an *opaque-vector-lookup* lens: an embedding is not merely an arbitrary list of floating-point numbers, but a coordinate position within a continuous semantic topology shaped by contrastive loss. By mastering the geometric properties of unit-norm hyperspheres, the efficiency of Matryoshka dimension truncation, and the two-stage synergy between bi-encoders and cross-encoders, machine learning engineers build scalable, sub-millisecond retrieval backbones that power accurate, grounded generative artificial intelligence.