Embedding: Basic Concepts
Summary
Embedding is a numerical vector representation of data (text, images, audio) that preserves the semantic closeness of objects. More details in the glossary.
Definition
Embedding is a mapping of an object (a word, a sentence, a document, an image) to a vector of fixed dimension in a multidimensional space. The vector is an array of floating-point numbers. The key property of embeddings is semantic closeness: objects with a similar meaning are located near each other in the vector space.
How embeddings are built
Embeddings are created by neural networks. A model is trained to predict the context of a word or to reconstruct the input data, and in the process of training its internal representations become vectors. For text, models such as Word2Vec and GloVe are used, as well as transformer encoders (BERT, T5).
| Type | Example | Dimension | Use |
|---|---|---|---|
| Word | word2vec | 100–300 | Finding synonyms, analogies |
| Sentence | sentence-transformers | 384–1024 | Semantic search, clustering |
| Document | OpenAI embeddings | 1536–3072 | RAG, classification |
| Multimodal | CLIP | 512–1024 | Image search |
Properties of the vector space
Embeddings have properties that can be used in practice:
- Cosine similarity — a measure of how close vectors are, computed as the cosine of the angle between them. The value ranges from -1 to 1, where 1 is the maximum similarity. More details in the glossary.
- Euclidean distance — the geometric distance between points. More details in the glossary.
- Vector arithmetic — the operations of addition and subtraction preserve semantic relationships. For example, vector('king') - vector('man') + vector('woman') ≈ vector('queen').
Use in LLMs
In LLMs embeddings are used at several levels:
- Input layer — tokens are converted into vectors before being fed to the transformer. More about tokenization.
- Positional encoding — information about the position of a token is added. More details in the glossary.
- Vector databases — for finding relevant fragments in RAG. More details in the article about vector databases.
from sentence_transformers import SentenceTransformer
model = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')
sentences = ['the cat is sitting by the window', 'the cat is sleeping on the windowsill', 'it is raining today']
embeddings = model.encode(sentences)
# The cosine similarity between the first and the second sentence will be high
# between the first and the third — low
Relation to other concepts
Embeddings are closely related to the weights of a model: the embedding matrix is part of the trainable parameters. The dimension of an embedding is a hyperparameter that affects quality and computational cost. More about parameters.
For searching by embeddings, vector indexes (HNSW, IVF) are used. More details in the glossary.