~7m10:03
Скрытый слой

Эмбеддинги на пальцах: рисуем 3D-карту смыслов

Nov 1, 2026

Read: ~7m · You save: 3 min

Embeddings on Your Fingers: Drawing a 3D Map of Meanings

How does search understand that « fix a tap » and « eliminating a mixer leak » mean the same thing? Embeddings, meaning maps and cosine similarity explained simply.

A search query "How to fix a faucet?" may return an article about repairing a mixer tap leak as the first link. The query and the text share not a single word. The reason is that language models work not with letters but with vectors that encode meaning. Such vectors are called embeddings. They underlie search, recommendations, and chatbots that work with documents.

From Text to Numbers

A computer works only with numbers, so text is first split into tokens. A token is a word or part of a word. Each token is assigned a number in a vocabulary. For example, the word "кошка" (cat, feminine) might correspond to the number 18342, and the word "кот" (tomcat) to the number 51907.

The number does not reflect meaning. In numerical order, "кошка" and "кот" are far apart, while the neighbor of "кошки" might turn out to be "кошелёк" (wallet). Adding and comparing such numbers makes no sense.

An alternative is the one-hot representation. Each word corresponds to a string of zeros as long as the entire vocabulary, with a one in the position of that word. The drawback is obvious: any two words are equally far from each other. "Кошка" is no more similar to "кота" than it is to "холодильник" (refrigerator).

What is needed is a representation that is short, dense, and places semantically close words near each other. Such a representation is precisely the embedding. The term comes from the English embedding, which literally means "insertion" or "embedding". Words are, as it were, embedded into a space.

Semantic Space

Imagine a map where each word has coordinates. One axis shows how alive an object is. Another shows how large it is. A mouse, a cat, a dog, and an elephant are located on the right, by size. A teapot and a truck are on the left.

In this system, "cat" is described by two numbers: 0.9 and 0.2. They can be shown as a point or as an arrow from the center of the coordinates. The arrow is called a vector, which is why embeddings are also called vectors.

Two axes are not enough. "Tiger" and "cat" almost coincide on such a map. Adding a third axis ("domestic" or "wild") separates them. Each new axis adds a number and a distinction that the model can take into account.

Real models use hundreds or thousands of axes. Embedding dimensions are 768, 1024, or more than 3,000 numbers. Such a space cannot be drawn, but the mathematics in it is the same as the mathematics of a flat map.

It is important to note that in a real model, the axes do not have names like "alive" or "large." The model decides on its own how to distribute meaning across the numbers. One property is usually spread across many axes at the same time. What matters is the position of the point as a whole, not any single number.

How to Measure Similarity

The distance between points often does not reflect closeness in meaning. The length of a vector depends on factors unrelated to the word's meaning, for example, the frequency of the word in the training data. A vector can become longer while its direction remains unchanged.

Therefore, similarity is measured by the angle between vectors, more precisely by the cosine of the angle:

  • vectors pointing in the same direction: the cosine equals 1;
  • vectors are perpendicular: the cosine equals 0, meaning there is no shared sense;
  • vectors point in opposite directions: the cosine equals −1.

Cosine similarity is calculated by multiplying the corresponding coordinates of the vectors, adding up the results, and dividing by the product of the vectors' lengths.

For the words "cat" and "kitten," the value will be high; for "cat" and "dog," it will be lower; for "cat" and "refrigerator," it will be low.

A non-obvious detail: in real models, even unrelated texts often yield a value not of 0, but, for example, 0.3. Therefore, you evaluate not the absolute value but the relative one: which pair is closer and which is farther.

Key point: an embedding is a point in the space of meanings. Similarity is the angle between points when viewed from the center.

How the Model Places the Dots

No one assigns word coordinates by hand. The method rests on an idea put forward by the linguist John Rupert Firth in 1957: a word can be understood by the company it keeps.

Consider sentences with a blank. "Tea," "coffee," and "cocoa" all fit the gap. Words with similar surroundings usually have close meanings, so their points should be located near each other.

In 2013, Google developed the Word2Vec model, which made embeddings widely known. The training process works as follows:

  1. Each word is assigned a random point.
  2. The model goes through a large body of text and learns to predict which words appear next to each other.
  3. Each error slightly shifts the points: neighbors move closer together, random pairs move apart.
  4. After billions of such shifts, the random cloud turns into a structured map.

As a result, drinks group with drinks, animals with animals, and cities with cities. The model was never given a definition of the concept "drink." It identified this group from the way people write texts.

Later, a property emerged that surprised even the authors of the method: directions in the space begin to correspond to relationships between words. If you take the vector "king," subtract "man," and add "woman," the nearest word, excluding the original ones, will be "queen." The pairs "country" and "capital" work in the same way. In modern models this arithmetic is performed less precisely, but the principle holds.

Embedding Table

The first step of any language model is the embedding table. It has a row for each token in the vocabulary. The model receives a token's number and retrieves the corresponding row. This is how a word turns into a vector.

For example, Llama 3 with 8 billion parameters has a vocabulary of 128 thousand tokens, and each embedding consists of 4096 numbers. A single table contains more than half a billion numbers, all of which are determined during training.

The table has a limitation. The word "key" has one row, that is, one point, for all of its meanings: "door key," "treble clef," "spring key" (a spring of water).

Layers of the model help resolve the ambiguity. Each layer adds information from neighboring words to the word's vector. "Key" next to "door" shifts toward locks, next to "violin" toward musical notes, and next to "water" toward springs. Such vectors are called contextual embeddings.

At the final stage, the model computes the probabilities of the next word based on the last vector. Thus, any response from a neural network begins with vectors and ends with them.

From Word to Text

Search requires more than a single word: phrases and documents need to be compared. The model outputs a vector for each token, so a single vector for the entire text must be obtained. There are two main approaches:

  • Mean pooling: the average of the vectors of all tokens is calculated.
  • Special token: a special token is added to the beginning of the text, and the model learns to gather the meaning of the whole phrase into it.

This process is called pooling.

A regular language model is not trained to create vectors for search. For this purpose, separate embedding models are used, which are fine-tuned on millions of pairs. A question and its correct answer are pulled toward each other, while random pairs are pushed apart. This method is called contrastive learning.

After such training, the phrases "how to fix a faucet" and "elimination of a mixer leak" end up close to each other. This explains the search result from the beginning of the article.

Application Areas

Semantic search. Documents are converted into vectors in advance and stored in a database. The query is also converted into a vector, after which the system finds the nearest vectors. Such storage systems are called vector databases.

Document chatbots (RAG). Documents are split into fragments, which are converted into vectors. When a question is asked, the system finds the nearest fragments and passes them to a language model. The model forms its answer based on the retrieved text, not only on data obtained during training.

Recommendations and clustering. Systems identify similar products and movies, and group thousands of reviews by topic without manual labeling. In all cases, one operation is performed: searching for the nearest vectors.

Multilingual models. In such models, the words "кошка", cat, and Katze land at almost the same point in the space. The meaning is the same, while the languages differ.

Multimodal models. Models such as CLIP place texts and images in the same space. A photo of a cat ends up next to the text "фото кота." This principle underlies image search by description.

Practical Test

The test was run on the BGE-M3 model. It works well with Russian and was run locally via Ollama. The script performs three actions: it sends phrases to the model, receives vectors, and calculates the cosine similarity of each pair.

The set of phrases included two phrases about a faucet, two about cats, and one about the weather. Each phrase was represented by 1024 numbers.

Results:

  • The pairs "faucet" and "mixer tap" showed high similarity, even though they have no words in common.
  • "A cat on the windowsill" and "a kitten by the window" also showed high similarity.
  • The weather phrase had low similarity with all the other phrases.

A search for "how do I fix a faucet?" returned the text about a mixer leak first and the text about the weather last. Thus, semantic search was implemented in less than thirty lines of code.

Ограничения эмбеддингов

Логика распознаётся плохо. Эмбеддинги хорошо определяют тему, но плохо различают смысловые противоположности. Фразы «Я люблю кошек» и «Я не люблю кошек» оказываются очень близко, так как слова почти совпадают и тема одна и та же. Для поиска такое поведение допустимо, для понимания смысла — нет.

Модели наследуют стереотипы. Эмбеддинги обучаются на текстах людей, которые содержат их стереотипы. В работе 2016 года на аналогии «мужчина относится к программисту, как женщина к…» Word2Vec ответил «домохозяйка».

Векторы разных моделей несовместимы. У каждой модели собственная карта пространства. При смене модели всю базу векторов требуется пересчитать.

Summary

An embedding is an address of meaning in a multidimensional space. The similarity of two objects is determined by the angle between their addresses. All language models begin with an embedding table, which maps tokens to vectors, and subsequent layers refine these vectors in light of context.

Introduction: Why Embeddings Are Needed

Search understands the meaning of a query even when there are no common words. For a neural network, words are not letters but vectors of numbers that encode meaning.

  • The query "How do I fix a faucet?" finds an article about fixing a mixer tap leak without any common words
  • For a neural network, the word cat is represented as a list of a thousand numbers
  • Similar words get similar numbers, and relationships turn into directions
  • The direction from man to woman roughly matches the direction from king to queen
  • Embeddings underlie language models, search, recommendations, and chatbots over documents

Tokens, Numbers, and Why Embeddings Are Needed

Text is first split into tokens, which are assigned numbers in a vocabulary. The number alone says nothing about meaning, and one-hot encoding makes all words equally distant from each other.

  • Text is split into tokens, which are words or parts of words
  • Each token is assigned a number in the vocabulary, for example cat 18342, cat (tomcat) 51907
  • The number does not reflect meaning: cat and tomcat are far apart, and a neighbor of cat may be wallet
  • One-hot: a string of zeros as long as the whole vocabulary with a one at the word's position
  • With one-hot, any two words are equally distant from each other; cat is no closer to tomcat than to refrigerator
  • Embedding (from English embedding, meaning insertion) is a short dense representation where words with similar meanings sit close together

Map of Meanings and Vectors

Meaning of words is conveniently represented as points on a map with coordinate axes. Each new axis adds a distinction, and real models use hundreds or thousands of axes.

  • Example of a two-dimensional map: an axis of "how alive" and an axis of "how large"
  • Mouse, cat, dog and elephant are placed on the right by size, kettle and truck on the left
  • A cat is described by two numbers, 0.9 and 0.2, and can be represented as a point or an arrow (vector)
  • Two axes are not enough: tiger and cat nearly coincide, adding a "domestic or wild" axis separates them
  • Dimensionality of real embeddings: 768, 1024, or more than 3000 numbers
  • In a real model the axes have no clear names, and a single property is usually spread across many axes
  • What matters is not an individual coordinate but the position of the point as a whole

Cosine Similarity

Similarity is measured not by distance but by the angle between vectors using cosine similarity, since vector length depends on how frequently a word appeared in training.

  • Distance between points often depends on how frequently a word appeared during training, so it does not reflect meaning
  • The cosine of the angle equals 1 for the same direction, 0 for a right angle, and minus 1 for opposite directions
  • Cosine similarity is computed by multiplying coordinates pairwise, summing them, and dividing by the vector lengths
  • For cat and kitten the value is high, for cat and dog it is lower, and for cat and refrigerator it is low
  • In real models, unrelated texts often give not zero but, for example, 0.3, so comparison matters more than the absolute number

How the Model Learns: Word2Vec and Word Context

The model itself learns the position of words from their context, following the idea of linguist John Firth. This is how Word2Vec, created at Google in 2013, works.

  • Linguist John Firth's idea: a word can be known by its context
  • Words that appear in the same context usually have similar meanings and receive nearby points
  • Word2Vec was trained at Google in 2013
  • First, each word is given a random point, then the model guesses neighboring words in a huge text
  • Each error slightly shifts the points: neighbors are pulled together, random pairs drift apart
  • Over time the random cloud turns into a map: drinks with drinks, animals with animals, cities with cities
  • Directions begin to encode relationships: king minus man plus woman gives queen
  • In modern models the arithmetic works less cleanly, but the idea remains

Embedding Table and Context

The first step of any language model is an embedding table, but a static vector cannot distinguish a word's meanings across different contexts. The model's layers add context, producing contextual embeddings.

  • The embedding table contains one row for each token in the vocabulary
  • Llama 3 with 8 billion parameters has 128 thousand rows, each with 4096 numbers
  • A single table contains more than half a billion numbers, all of which are learned during training
  • The static table problem: the word 'key' has one row and one point for all meanings (door key, violin clef, spring key... )
  • Each layer mixes information from neighbors into the vector, and 'key' shifts toward locks, notes, or springs
  • Such vectors are called contextual embeddings
  • At the end, the model computes next-word probabilities from the last vector

Vectors for Whole Phrases and Contrastive Learning

To compare whole phrases and documents, one vector for the entire text is needed, obtained through pooling. For search, separate embedding models trained contrastively are used.

  • The model outputs a vector for each token, but search needs one vector for the entire text
  • Averaging the vectors of all tokens is the simplest approach
  • Alternative: add a special token at the beginning and train the model to gather the phrase's meaning into it; this is called pooling
  • A regular language model does not learn to make good vectors for search, so separate embedding models are needed
  • Models are further trained on millions of pairs: a question and its correct answer are pulled together, while random pairs are pushed apart
  • This training is called contrastive and brings "how to fix a tap" close to "eliminating a mixer leak"

Where Embeddings Are Used

Embeddings are used in semantic search, in RAG chatbots over documents, in recommendations and text clustering, and in multilingual and multimodal models.

  • Semantic search: documents are converted into vectors in advance and stored in a vector database, the query is also converted into a vector, and the nearest ones are searched for
  • RAG: documents are split into chunks, converted into vectors, the nearest chunks to the question are found and passed to a language model
  • Recommendations and clustering: similar products, movies, and reviews are grouped by topic without manual labeling
  • Multilingual models: "cat", "Katze", and "кошка" land at nearly the same point
  • Multimodal models, such as CLIP, place text and images in one space, so a photo of a cat ends up near the phrase "photo of a cat"

Practice: Semantic Search with BGE3

A demonstration of semantic search using the BGE3 model, which handles Russian well and runs locally via Ollama. The script is about thirty lines of code.

  • Model: BGE3, which understands Russian, runs locally via Ollama
  • The script sends phrases to the model, gets vectors, and computes the cosine similarity of each pair
  • Test phrases: two about a faucet, two about cats, and one about the weather
  • Each phrase is turned into 1024 numbers
  • On the similarity heatmap, the faucet and the mixer stand out even though they share no common words; a cat on the windowsill and a kitten by the window are also close; the weather is dim with all of them
  • The query "how to fix a faucet?" returns the text about a mixer leak first and the weather text last

Limitations of Embeddings

Embeddings capture the topic well but understand logic poorly, inherit stereotypes, and are incompatible between models, so when the model is changed the database must be recomputed.

  • The phrases "I love cats" and "I don't love cats" end up very close together, because the words and topic are almost identical
  • For search this is tolerable; for understanding meaning it is not
  • In a 2016 paper, Word2Vec answered the analogy "man is to programmer as woman is to ..." with "homemaker"
  • Embeddings learn from human texts together with their stereotypes
  • Vectors from different models are incompatible: each has its own map, so when the model changes the database must be fully recomputed