Embeddings: turning meaning into numbers
Computers do not know what words mean. They only work with numbers. An embedding turns words and sentences into numbers in a way that puts similar meanings close together. Click a word on the map below.
Short answer. An embedding turns a word or a sentence into a list of numbers (a vector). The vectors are trained so that similar meanings end up close together. So "find things with a similar meaning" becomes "find nearby vectors."
Scaled-down toy. The coordinates were placed by hand to explain the idea. Real embeddings have hundreds to thousands of dimensions, and a model sets them by training.
Position = ( , )
Click a word to connect it to its 5 closest words with blue lines and see their ranks. Press and drag to move it, and the ranks change right away. With a keyboard, use the "Word" box and the position boxes.
Definitions
The text below explains with pictures and a lab. These are the textbook definitions. V is the vocabulary size, d is the number of dimensions of the embedding, u and v are vectors of d real numbers, and ‖u‖ is the length of a vector.
- embedding
- A mapping that gives each item (a word, token, sentence and so on) one vector of d real numbers, or that vector itself. It is learned so that the vectors of items with similar meanings end up close together.
- embedding matrix
- A V × d matrix with one row for each token in the vocabulary (the text calls it the embedding table). For token number i, the row for i is the embedding of that token. Its values are learned together with the other weights of the model.
- one-hot vector
- A vector with V entries where only the entry for token i is 1 and every other entry is 0. Multiplying this vector, as a row, by the embedding matrix gives the row of E for i.
- cosine similarity
- For two nonzero vectors, the dot product divided by the product of their lengths. It is the cosine of the angle between them. Its value is between −1 and 1, and a larger value means the directions are more alike.
- Euclidean distance
- The length of the difference of two vectors (the straight-line distance in the text): square the difference in each position, add them all, and take the square root. A smaller value means closer.
1. What an embedding is: one position per word
An embedding gives each word (or sentence, or image) a few numbers. A list of numbers is called a vector, and how many numbers it has is its dimension. With two numbers you can draw it as a dot on a flat map. That is what the lab above does. "cat" is at (3, 3) and "apple" is at (−2, 4).
In a good embedding, words with similar meanings gather together. On the map, animals are top right, fruit is at the top, vehicles are on the left, jobs are bottom left, and people are bottom right. So a computer can find "words similar to cat" with plain arithmetic, even though it does not know what a cat is. It just looks for vectors near the cat vector.
The map on this page is a scaled-down toy. The coordinates were placed by hand to explain the idea. A real embedding has hundreds to thousands of numbers (hundreds to thousands of dimensions), and those numbers are set by a model that reads a lot of text, not by a person. That is why a real embedding usually has no number with a clear meaning like "across = how animal-like." The meaning lives in the distances and directions to other vectors.
2. The first step of an LLM: the embedding table
When an LLM gets text, it first cuts it into tokens (words or pieces of words) and gives each one a number (tokenization). The number is just a name tag. It carries no meaning. Token 7 and token 8 are not similar just because their numbers are close.
So the first step turns each number into a vector. It uses the embedding table.
- Rows = how many different tokens there are (the vocabulary size)
- Columns = the dimension
If the token number is n, take row n of the table. There is no math, only a lookup.
const vector = embeddingTable[tokenId]; // one row = one vector
The map on this page can be written as an embedding table too. It has 32 rows and 2 columns.
| Number | Word | Column 1 (across) | Column 2 (up) |
|---|---|---|---|
| 0 | dog | 4 | 2 |
| 1 | puppy | 3.6 | 1.3 |
| 2 | cat | 3 | 3 |
| … | … | … | … |
| 31 | princess | 3.2 | −3.3 |
A real LLM's table is big. For example, with 50,000 different tokens and 768 dimensions, the table holds 50,000 × 768 = 38,400,000 numbers. These numbers start out random, and they get adjusted together with the rest of the model while it trains. The vectors taken from the table then go on to the next step, attention.
3. How is this different from a one-hot vector?
The simplest way to turn words into numbers is a one-hot vector. Make one slot per word, put 1 in the word's own slot and 0 everywhere else. With only three words, dog, cat and apple, you get this.
dog = (1, 0, 0) · cat = (0, 1, 0) · apple = (0, 0, 1)
The problem is that every word is equally far from every other word. The straight-line distance from dog to cat is √2 ≈ 1.41, and from dog to apple it is also 1.41. The cosine similarity of every pair is 0. A one-hot vector cannot say "dog and cat are alike."
| One-hot vector | Embedding | |
|---|---|---|
| Number of slots | One per word (tens of thousands) | Chosen up front (hundreds to thousands) |
| Slots that are not 0 | One | Almost all |
| Words with similar meanings | As far apart as any other pair | Close together |
| How the numbers are set | Fixed by the word's number | Learned by training |
The two are connected. Multiply a one-hot vector by the embedding table (matrix multiplication) and only the row where the 1 sits is left. That is the same as looking up the row. Real code skips the multiplication and reads the row directly, because multiplying by tens of thousands of zeros is wasted work.
4. Two ways to measure "close"
How close two vectors are is usually measured in one of two ways. You can switch between them with the buttons in the lab.
cosine similarity = (u · v) ÷ (‖u‖ × ‖v‖)
This is how much the two point in the same direction, seen from the origin. 1 means the same direction, 0 means a right angle, −1 means opposite. Bigger means closer. u · v is the dot product (multiply matching numbers, then add), and ‖u‖ is the length of the vector.
straight-line distance = √((u₁ − v₁)² + (u₂ − v₂)²)
This is the length you would measure with a ruler between the two dots. Smaller means closer. With more dimensions, square the difference in every place, add them all, then take the square root.
Cosine similarity ignores length. Dots in the same direction from the origin score 1, whether they are far out or close in. When you pick cosine similarity in the lab, a green dashed line runs from the origin through the chosen word. The closer a word's direction is to that line, the higher it ranks. When you pick straight-line distance, a blue dashed circle is drawn around the chosen word. The words inside the circle are the top 5.
Try this. ① At the start (cat), the top word by cosine similarity is tiger (0.999). Switch to straight-line distance and the top word is kitten (0.81). Tiger is farther from the origin, but it points almost the same way as cat. ② Pick "man." By cosine similarity the order is princess (0.998), queen, prince, woman, boy. Switch to straight-line distance and boy (0.72) comes first. ③ Move cat to (1, 1), by dragging or by typing in the boxes. By cosine similarity, the ranks do not change at all, because the direction is the same. By straight-line distance, kitten is first (2.06) and watermelon is second (2.4). ④ Put cat among the fruit at (−1, 3.6), and both ways now list fruit as its neighbors. Press "Reset positions" to go back.
Because the map is 2D, there are only a few directions to go around, so many pairs have a cosine similarity above 0.9. Look at the order, not the value itself. With real embeddings too, what value counts as "similar" depends on the model.
5. Work it out by hand
Use dog = (4, 2), cat = (3, 3) and apple = (−2, 4) from the map.
- Dot product of dog and cat. Multiply matching numbers and add.
4 × 3 + 2 × 3 = 12 + 6 = 18. - Lengths.
‖dog‖ = √(4² + 2²) = √20 ≈ 4.47,‖cat‖ = √(3² + 3²) = √18 ≈ 4.24. - Cosine similarity.
18 ÷ (√20 × √18) = 18 ÷ √360 ≈ 18 ÷ 18.97 ≈ 0.949. It is close to 1, so they point in similar directions. - Dog and apple. The dot product is
4 × (−2) + 2 × 4 = −8 + 8 = 0, so the cosine similarity is 0 too. Seen from the origin, the two words are at a right angle. On this map, that means "unrelated." - With straight-line distance. Dog and cat:
√((4 − 3)² + (2 − 3)²) = √2 ≈ 1.41. Dog and apple:√((4 + 2)² + (2 − 4)²) = √40 ≈ 6.32. Either way, cat is closer to dog than apple is.
Pick "dog" in the lab and the table shows cat with a cosine similarity of 0.949. Switch to straight-line distance and it shows 1.41. Real embeddings use the same math. There are just 768 places instead of 2.
6. Things worth knowing
| Property | In plain words |
|---|---|
| Close = similar meaning | Training places them that way. That is why "find similar things" becomes "find nearby vectors" |
| Single numbers usually mean nothing | The meaning is in the distances and directions to other vectors |
| Cosine similarity looks at direction only, straight-line distance looks at position | If every length is 1, then ‖u − v‖² = 2 − 2 × cosine similarity, so both give the same ranking |
| Differences can hold relationships | queen − king ≈ woman − man. The word math in section 8. It does not always work |
| Only compare vectors from the same model | Each model places things its own way |
7. How it is learned: words that show up in similar places
Learning embeddings rests on one idea. Words that show up in similar places have similar meanings. In "the ___ wags its tail," both "dog" and "puppy" fit. "Apple" does not. So, across a lot of text, put words whose neighbors look alike close together.
word2vec (Mikolov et al., 2013) turned this idea into a guessing game. It walks through text one word at a time. It either guesses the middle word from the words around it (CBOW), or guesses the words around it from the middle word (Skip-gram). The vectors start out random and get nudged a little every time a guess is wrong (gradient descent). "Dog" and "puppy" have to guess the same neighbors, so they get nudged the same way and end up close. When the game is over, the guessing parts are thrown away and only the table of vectors is kept.
An LLM's embedding table does not play this game on its own. It gets adjusted along with the whole model while the model learns to guess the next token. The idea underneath (things that show up in the same places should look alike) is the same.
8. Word math: relationships hiding in directions
The difference between two vectors is an arrow. On the map, the arrow "man → woman" and the arrow "king → queen" are the same. Both are (0.4, −1.3). So
king − man + woman = king + (woman − man)
means "start at king and follow the man → woman arrow," and that is where queen sits. The word2vec paper presented this kind of math (king − man + woman ≈ queen) and tested its vectors on a large set of questions like it.
Press a button or pick words in the A, B and C boxes. The green arrow is A, the blue one subtracts B, and the purple one adds C. The answer is the word (orange) at the shortest straight-line distance from the black circle (the landing point). This map is the same scaled-down toy as above (it does not use positions you moved there).
There are three steps. ① Work out A − B + C to get the landing point. ② Find the word closest to it. ③ Leave A, B and C themselves out of the answer. With real embeddings, the word closest to the landing point is often A itself (king), so leaving them out is the usual way. This lab picks by straight-line distance. With real embeddings, people usually pick by cosine similarity.
Try this. ① "king − man + woman": (3.4, −1.6) − (2, −1.8) + (2.4, −3.1) = (3.8, −2.9). Queen is right there (distance 0). The distance is 0 because a person placed the arrows to match exactly. With real embeddings an exact hit is rare, and the closest word is taken as the answer. ② "prince − king + queen" gives princess. ③ "puppy − dog + cat" gives kitten. It moves the "adult → young" arrow over to cat. ④ "apple − man + woman" gives peach (distance 0.3). An apple has no gender, yet an answer still comes out. It is just the fruit that happened to be near the landing point, not an answer that makes sense.
Real embeddings show some of these relationships too, but not always. Plenty of questions in the paper's test were answered wrong. And as ④ shows, the math always returns some word, even when no word fits.
9. Word embeddings vs. sentence and document embeddings
A word embedding gives one vector per word. Search needs one vector per sentence or per document. These are called sentence embeddings and document embeddings.
The simplest way is to average the vectors of the words in the sentence. The lab below uses that rule.
sentence vector = (sum of the word vectors) ÷ (number of words)
Example: in #1, "A puppy and a cat play in the yard," the words on the map are puppy (3.6, 1.3) and cat (3, 3). The average is ((3.6 + 3) ÷ 2, (1.3 + 3) ÷ 2) = (3.3, 2.15).
Query point = ( , )
Blue squares are sentences. Each one sits at the average of the word vectors in it. That is a simple rule for this lab only, and real sentence embeddings are not made this way. Drag the green circle (the query point) or pick a query word, and the cosine similarity ranking changes. The 3 closest are orange.
Try this. ① The first query is "train." The top sentence is #5, "I take the bus and then the train." (0.996), and #6 is second (0.825). ② Change the query to "boy." The top sentence is #9, "The king and the queen live in a castle." (0.902). #10, the one that actually has "boy" in it, is only third (0.568). Averaging it with "dog" pulled it toward the animals. ③ Drag the query point to (3, 0) and #10 comes first (0.999). The query point can sit where there is no word at all. That is like real search, where the question goes through the same model and lands somewhere on the map.
Averaging has big weak spots. It ignores word order: "the dog follows the boy" and "the boy follows the dog" get the same vector. A single word like "not" that flips the meaning is hard to capture, and as ② shows, mixing words lands the sentence somewhere in between. So real sentence embeddings come from a model that reads the whole sentence (a transformer), and it is often trained so that sentences with the same meaning end up close. Documents are long, so they are usually cut into chunks of a few paragraphs, and each chunk gets its own vector.
With millions of sentences, measuring every single one is slow. Fast ways to find the closest ones are in vector search. Putting the sentences you found into an LLM so it can answer from them is RAG.
10. Embeddings that change with context
Word embeddings like word2vec give one vector per word. But "bat" is an animal in "a bat flew out of the cave" and a piece of sports gear in "she swung the bat." With only one vector, the word lands somewhere between its meanings.
An LLM handles this. In the embedding table at the first step, "bat" always starts as the same vector. Then, at every layer, the vector is adjusted by looking at the tokens around it. With "cave" nearby it moves toward the animal side, and with "swung" nearby it moves toward the sports side. A vector that changes with its surroundings like this is called a contextual embedding. The part that looks at the other tokens and adjusts the vector is attention.
11. How do you look at many dimensions?
Real embeddings have hundreds to thousands of dimensions, so you cannot draw them. Instead you squash them down to two. The basic method is PCA. It picks the two directions in which the dots spread out the most and drops a shadow onto that flat plane.
Squashing throws information away. Dots that look close in the 2D picture can be far apart in the real space, and the other way around. Use the picture only for the rough shape, and measure closeness with the original vectors. The map on this page works the other way. It was not squashed down. A person placed it in 2D from the start.
12. Limits
- Bias gets baked in. An embedding learns which words show up near which other words in its training text. If the text is skewed, it learns that too. If a job often appears next to words for one gender, that job's vector leans toward that gender. Search or recommendations built on these vectors pass the skew on to their results.
- Vectors from different models do not mix. Each model places things its own way. The same "cat" gets completely different numbers in different models, and the number of dimensions often differs too. Stored document vectors and query vectors must come from the same model. If you switch models, make all your stored vectors again.
- Close is not the same as "same meaning." Opposites tend to land close together. "Hot" and "cold" both fit in "it is ___ today." Showing up in similar places is closer to "same topic" than to "same meaning."
Where is it used?
- Search by meaning. "My laptop gets way too hot" finds a page called "Fixing overheating issues," even with no words in common. Turn the question and the documents into vectors with the same model, then pick the closest (vector search).
- Recommendations. Show things whose vectors are close to the article or product someone is looking at. You can also combine the vectors of things a person viewed into one vector for their taste.
- Grouping. Put vectors that are close together into groups, for example to sort customer questions by topic or to bundle similar articles.
- RAG. Find the document chunks closest to a question and give them to an LLM along with the question. The model can then answer from documents it never saw in training, like a company's own files (RAG).
- Finding near-duplicates. Pairs with a very high cosine similarity are often the same question or document written twice.
Common questions
What is an embedding?
A word or a sentence turned into a list of numbers (a vector). The vectors are trained so that things with similar meanings sit close together. That turns finding similar meanings into finding nearby vectors.
Does each number in an embedding mean something?
Usually not. No single number stands for something like how animal-like a word is. All the numbers together set the position. The meaning lives in the distances and directions to other vectors.
Should I use cosine similarity or straight-line distance?
Use what your embedding model recommends. If every vector has length 1, the two give the same order. What counts as similar (which value is high enough) differs from model to model, so look at the order.
Can I mix embeddings from different models?
No. Each model places things its own way, so the same word gets completely different numbers in different models. The number of dimensions often differs too. If you switch models, make all your stored vectors again.
What is the difference between word and sentence embeddings?
A word embedding gives one vector per word. A sentence embedding gives one vector for a whole sentence. Sentence embeddings come from a model that reads the whole sentence, and it is often trained so that sentences with the same meaning end up close.
Words
| Word used here | Word used in textbooks |
|---|---|
| embedding | embedding. For one word, a word embedding. For a sentence or document, a sentence embedding or document embedding |
| list of numbers | vector |
| how many numbers | dimension |
| table from token number to vector | embedding matrix, embedding layer |
| how many different tokens | vocabulary size |
| vector with a 1 only in its own slot | one-hot vector |
| straight-line distance | Euclidean distance |
| cosine similarity | cosine similarity. 1 − cosine similarity is called cosine distance |
| making the length 1 | normalization |
| words in similar places have similar meanings | distributional hypothesis |
| the words around a word | context, context window |
| word math | word analogy, vector arithmetic |
| embedding that changes with context | contextual embedding |
| finding the few closest | nearest neighbor search, k-NN |
| squashing down the dimensions | dimensionality reduction |
| skew | bias |
Sources
- Mikolov, Chen, Corrado, Dean (2013). Efficient Estimation of Word Representations in Vector Space. The two word2vec methods (CBOW and Skip-gram) and the word math test come from this paper.