Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

Embeddings: what are vector representations and how do they work?

A documentation search should find subscription cancellation instructions even if the user asks how to terminate a membership. Embeddings make it possible to compare representations rather than words alone. Their usefulness depends on the model, task and indexing strategy. This guide explains how they are produced, compared and deployed.

AI
Published Written by Reading time 9 min read
On this page Contents: quick navigation between sections

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?

MetricExample valuePreferred direction
Cosine similarity0.597614Higher
Dot product5Higher
Euclidean distance3Lower

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

Theoretical raw coordinate payload for one million dense vectors (GB, excluding overhead)
DimensionsFP32FP16INT8
3841.5360.7680.384
7683.0721.5360.768
15366.1443.0721.536
307212.2886.1443.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]

Embeddings enable computational comparison of data. Choose them by retrieval quality on representative tasks, not dimension count alone. Maintain model-index compatibility, select the appropriate metric, measure outcomes and protect both source data and vectors.

Tools for this topic

AI Embeddings Semantic Search Vector Similarity RAG Vector Databases Information Retrieval Cosine Similarity MTEB Sentence Transformers

Frequently asked questions

Is an embedding a token?

No. A token is an input unit; an embedding is a numerical representation of a token or another object, such as a document.

Do more dimensions mean better quality?

No. Dimension affects storage and computation, but quality depends on training and the task.

Can embeddings from different models be compared?

Only if their spaces are intentionally aligned and compatibility is verified; matching dimensions are insufficient.

Does RAG require a vector database?

No. Lexical search, hybrid search and other data sources can also be used.

Can an embedding be converted back to text?

There is no general lossless decoder, but inversion attacks may recover information and sometimes text under specific conditions.

Does cosine similarity of 0.9 mean 90% relevance?

No. It is a geometric score requiring calibration for the data and task.

Can embedding quantization change retrieval results?

Yes. It can change distances and rankings. Evaluate compressed vectors on representative queries and distinguish compression losses from ANN index losses.

Sources and references

  1. Google for Developers, Embedding space and static embeddings↩1↩2
  2. PyTorch, Embedding layer↩
  3. Reimers and Gurevych, Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks (EMNLP-IJCNLP 2019)↩1↩2↩3
  4. Sentence Transformers, Semantic Search↩1↩2↩3↩4↩5↩6
  5. intfloat, Multilingual-E5-base model card↩1↩2
  6. Wang et al., Text Embeddings by Weakly-Supervised Contrastive Pre-training↩
  7. FAISS, MetricType and distances↩1↩2↩3
  8. OpenAI, Vector embeddings↩1↩2
  9. Sentence Transformers, Retrieve & Re-Rank↩1↩2↩3↩4↩5
  10. Santhanam et al., ColBERTv2: Effective and Efficient Retrieval via Lightweight Late Interaction (NAACL 2022)↩
  11. Kusupati et al., Matryoshka Representation Learning (NeurIPS 2022)↩
  12. MTEB, Available Benchmarks↩1↩2
  13. Poświata, Dadas and Perełkiewicz, PL-MTEB: Polish Massive Text Embedding Benchmark (Findings of ACL 2026)↩
  14. Morris et al., Text Embeddings Reveal (Almost) As Much As Text (EMNLP 2023)↩1↩2
  15. Seputis et al., Rethinking the Privacy of Text Embeddings: A Reproducibility Study of "Text Embeddings Reveal (Almost) As Much As Text" (2025)↩1↩2
  16. Elastic, Reciprocal rank fusion↩
  17. Sentence Transformers, Embedding Quantization↩
  18. FAISS, Guidelines to choose an index↩1↩2
  19. Muennighoff et al., MTEB: Massive Text Embedding Benchmark (EACL 2023)↩
  20. MMTEB: Massive Multilingual Text Embedding Benchmark (ICLR 2025)↩
  21. Frank and Afli, The Harder Text Embedding Benchmark (HTEB): Beyond One-dimensional Static Robustness (EMNLP 2026)↩
  22. Sentence Transformers, Input Formats↩
  23. ir-measures, Measures↩1↩2

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning