What are embeddings?
An embedding represents an object in a numerical space, typically as a vector with a fixed number of coordinates. A model maps text, images, audio or other objects to numbers so that the geometry is useful for a task. Unlike one-hot encoding, where each category has its own position, a dense representation can capture learned relationships between categories. Individual coordinates generally do not have a unique interpretable meaning. [1]
A token ID is an index, not a similarity measure. An embedding table, such as PyTorch's Embedding layer, assigns learned vectors to IDs; subsequent Transformer layers can produce context-dependent representations. A sentence vector intended for retrieval is a separate output, usually requiring suitable training. An arbitrary hidden state of a generative model is not automatically a good retrieval embedding. [2][3]
Beyond retrieval, embeddings can support ticket clustering, potential duplicate detection, classification and product recommendation. Define similarity separately for each task: a shared topic is not the same as a duplicate, and product proximity does not guarantee usefulness. [1][12]
How does a model produce a vector?
A typical text encoder tokenizes input, computes contextual token representations and aggregates them through pooling, such as averaging unmasked tokens or selecting a designated token, depending on the architecture. Projection and L2 normalization may follow. Reproduce the model card's procedure, including input limits, prefixes and padding masks. Truncating long text can discard evidence needed for retrieval. [3][4][5]
Contrastive training assigns higher similarity scores to positive pairs, such as a question and a relevant passage, than to negative pairs. The loss optimizes relative scores among examples, often including hard negatives that are topically close but irrelevant. Not all models use the same training recipe; sentence similarity and query-to-answer retrieval are different tasks. E5 and Sentence-BERT illustrate different approaches to representation learning. [3][6]
Symmetric sentence similarity differs from asymmetric retrieval of a longer answer passage for a short query. An encoder may use different instructions on each side; Sentence Transformers provides encode_query and encode_document for this purpose. Compatible spaces need not use identical encoders if the encoders are designed for joint comparison. Text and image vectors can likewise be compared only when the model provides a shared space. [4][22]
How is vector similarity measured?
| Metric | Example value | Preferred direction |
|---|---|---|
| Cosine similarity | 0.597614 | Higher |
| Dot product | 5 | Higher |
| Euclidean distance | 3 | Lower |
For vectors a and b of equal dimensionality, the dot product is Σ aᵢbᵢ, the L2 norm is √Σ aᵢ², and cosine similarity is (a·b)/(‖a‖₂‖b‖₂). For nonzero real vectors, cosine similarity ranges from −1 to 1; it is undefined for a zero vector. Euclidean distance is √Σ(aᵢ−bᵢ)². Choose the metric recommended for the model and supported by the index configuration. [7]
Synthetic example: a=(1,2,3), b=(2,0,1). The dot product is 5, the norms are √14 and √5, cosine similarity is 5/√70 ≈ 0.597614, and Euclidean distance is 3. After normalizing both nonzero vectors, dot product equals cosine similarity and squared L2 distance equals 2−2·cos(a,b). Their rankings are equivalent under exact arithmetic and appropriate sorting directions. A score of 0.8 is not an 80% relevance probability; calibrate thresholds for the model and data. [7][8]
Libraries may return transformed scores: FAISS METRIC_L2 returns squared Euclidean distance, which is 9 rather than 3 in this example. Cosine distance under the 1−cos convention ranges from 0 to 2. Dot product also depends on vector magnitude, so it has no fixed range for arbitrary vectors. Do not transfer thresholds between metrics, models or indexes without conversion or recalibration. [7]
Dense, sparse and multi-vector representations
A dense embedding commonly represents text as one vector with many nonzero coordinates. Sparse representations retain relatively few nonzero values, such as weighted vocabulary features, and may also be learned. BM25 is a lexical ranking method, not a synonym for all sparse embeddings. Hybrid search combines lexical and semantic signals, often by fusing rankings, to support paraphrases as well as product IDs, error codes and rare terms. [4][9]
A bi-encoder independently encodes queries and documents in a compatible space, allowing document vectors to be indexed in advance. A cross-encoder processes a pair jointly and is often used to rerank a small candidate set. Multi-vector models such as ColBERTv2 retain token representations and use late interaction, changing storage and retrieval costs. [9][10]
Reciprocal Rank Fusion (RRF) is a practical fusion method: a document's score is the sum of 1/(c+r), where r is its one-based rank in each list containing it and c is a positive configuration constant. A missing document contributes nothing from that list. RRF uses positions rather than directly adding incompatible BM25 and cosine scores, but does not guarantee a better ranking. Example: with c=60, document A at ranks 1 and 3 receives 1/61 + 1/63 ≈ 0.032266; document B only at rank 2 receives 1/62 ≈ 0.016129. These are ranking scores, not probabilities. [16]
Embeddings in semantic search and RAG
During ingestion, acquire documents, retain identifiers, versions and permissions, split text according to structure and encoder limits, generate vectors and store them with metadata. At query time use the compatible query encoder and appropriate prefix; multilingual-e5-base, for example, requires query: and passage: prefixes even for non-English texts. Retrieve candidates, enforce access filters and optionally rerank. [4][5][9]
Exhaustive exact search compares all eligible vectors; approximate nearest-neighbor search (ANN) reduces work at the cost of potentially missing neighbors. In RAG, the generator receives selected source passages, not merely similarity scores. A passage saying “do not cancel” may be close to one saying “cancel”; embeddings do not guarantee truth, date validity or permissions. Preserve source evidence and evaluate generation separately from retrieval. [4][9][18]
Chunking affects results independently of model selection: short passages may lose context, while long passages can dilute the signal or exceed encoder limits. Preserve headings, source identifiers and versions; deduplicate overlapping passages in the final context when needed. Tune chunk size and overlap empirically. Enforce access permissions before exposing retrieved content to the generator or user. [4][9]
Dimension, memory and space compatibility
| Dimensions | FP32 | FP16 | INT8 |
|---|---|---|---|
| 384 | 1.536 | 0.768 | 0.384 |
| 768 | 3.072 | 1.536 | 0.768 |
| 1536 | 6.144 | 3.072 | 1.536 |
| 3072 | 12.288 | 6.144 | 3.072 |
For N dense vectors with d dimensions and b bytes per coordinate, the raw payload is N·d·b. One million 768-dimensional FP32 vectors occupy 3,072,000,000 bytes, or 3.072 GB (about 2.86 GiB); ideal FP16 storage is half that. Indexes, IDs, text, metadata, replicas and quantization scales add overhead. Higher dimension does not guarantee quality. Matryoshka Representation Learning trains representations that remain useful at supported shorter dimensions; arbitrary truncation of any model's vectors is not justified. [8][11]
Two models with equal dimensionality may use entirely different coordinate systems. Store model identity and revision, tokenization settings, pooling, normalization, dimensionality and chunking version. Changing representation spaces generally requires re-embedding documents and switching indexes after evaluation. Do not mix old and new vectors unless compatibility is explicitly provided and verified.
Quantizing encoder weights and quantizing stored embeddings are separate operations. One million 768-dimensional INT8 vectors require a theoretical 768 MB of coordinate payload, excluding scales and other metadata. Scalar quantization may require calibrating ranges on representative data. Binary representations may be smaller still, but require a suitable metric or higher-precision rescoring. Evaluate the impact of compression rather than assuming rankings remain unchanged. [17]
How to select and evaluate an embedding model
Start with the task, languages, domain, input limit, license, costs, latency and data-processing requirements. Compare local and hosted models on the same corpus. MTEB and its multilingual extension MMTEB cover different tasks; PL-MTEB contains 30 tasks in five categories for Polish. A leaderboard score is not a substitute for application-specific evaluation or proof of superiority in every domain. [12][13][19][20]
Build representative queries with relevance judgments. Measure recall@k (the number of relevant documents in the top k divided by the total number of known relevant documents), precision@k, MRR and nDCG as appropriate to the labels. Define how to handle duplicates, incomplete judgments and queries with no relevant documents. Compare lexical, hybrid and reranked retrieval; separate encoder quality from approximate-index losses by comparing ANN against exact search. Test changes to dimensions, quantization and chunking on a separate held-out set. [23]
Example: if five documents are known to be relevant and three appear among the first four unique results, recall@4 is 3/5 = 60% and precision@4 is 3/4 = 75%. MRR averages the reciprocal rank of the first relevant result (zero if absent); nDCG accounts for graded relevance and position relative to an ideal ranking. [23]
Distinguish relevance-based recall@k from ANN agreement with exact search. If exact top 10 contains ten distinct IDs and ANN returns eight of them, ANN recall@10 is 80%; this is not 80% relevance to user needs. Use the same metric, corpus, filters and tie policy. Test short queries, negation, identifiers and languages separately. HTEB examines robustness to lexical and stylistic changes, length and language; a high static benchmark score does not guarantee robustness to such changes. [18][21]
Security and production deployment
Embeddings are neither encryption nor guaranteed anonymization. Research on text inversion from vectors has demonstrated information recovery under specific conditions; success depends on models and data. Minimize data, control access to vectors and documents, verify API-provider terms, encrypt storage and manage deletion across copies and indexes. [14][15]
Roll out changes gradually: version the model and configuration, build a new index alongside the old one, evaluate a representative set and switch traffic with a rollback option. Monitor latency, cost, relevance and the fraction of queries without useful results. When evidence is insufficient, the system should be able to return no match instead of forcing an answer. Similarity search does not replace authorization or fact checking.
The inversion reproducibility study found that effectiveness depends in part on input length. Quantization can mitigate particular attacks in a specific experiment, but it does not demonstrate anonymization or provide a formal privacy guarantee. It cannot replace access control. [14][15]
