From house number to coordinate
So far every token only has a number. A network can't do much with that: 42 isn't “more similar” to 43 than to 900. So an embedding gives every token a whole list of numbers, and the model sets them itself during training.
Picture a map. Every token gets a place with coordinates. At the start the places are scattered randomly. During training, tokens that occur in similar contexts move closer together: “cat” ends up near “dog”, far away from “tax return”. Nobody tells the model where things belong. It emerges from the data; the next section shows how.

A mini example with three tokens and two numbers each:
| ID | Token | First component | Second component |
|---|---|---|---|
| 0 | cat | 0.2 | 0.7 |
| 1 | dog | 0.4 | 0.6 |
| 2 | sofa | -0.3 | 0.1 |
For ID 1 we look up [0.4, 0.6]. That is the embedding of “dog”. The numbers here are made up. In a real model they start out random and get shifted during training. We don't decide that the first number means “kind of animal” and the second “size”.
The length of the list is called the embedding dimension or width D, here D = 2. Real models use hundreds or thousands of numbers per token. Nobody can picture a map with a thousand directions, but computing with it works just like with two.
You can tell a word by the company it keeps
Try a fill-in-the-blank: “The ___ sleeps on the sofa.” What fits? Cat, dog, grandma, maybe child. “Tax return” doesn't fit, and neither does “soup”. With “The ___ tastes good” it is exactly the other way round.
Words that fit into the same blanks evidently have something in common. Training makes use of exactly that. The model is supposed to predict the next word. If similar words usually follow “cat” and “dog”, the most convenient thing for the model is to give both of them similar lists of numbers too. Then everything it has learned about cats automatically applies to dogs as well, at least in part. So the gradient pushes the lists in that direction all by itself.
By the way, this doesn't happen in a separate step beforehand. The embedding table starts out just as random as all the other weights and is learned in the same training run. (In the past, for example with the word2vec method from 2013, embeddings really were trained separately in advance. That is where the common picture “first embeddings, then the rest” comes from.)
Below you can watch such a training run live. The model reads a good 400 simple sentences about animals, people, furniture, food and money. Every word starts at a random place. Press “Start learning” and watch little groups form. Afterwards, tap “bank”.
Counting instead of guessing
The basic idea is so simple that it even works without any training: for every word, count which other words stand with it in a sentence. “Cat” stands next to “sleeps”, “eats”, “sofa”. So does “dog”. So their count rows look alike.
Such a count row already is a kind of embedding, just a very long and rough one: one number for every word in the vocabulary. Real models instead learn short, dense lists with a few hundred numbers. How similar two lists are is measured with the cosine similarity: 1 means “point in exactly the same direction”, 0 means “have nothing in common”. The calculation behind it is in a math corner further down.
In the lab you can write your own sentences and watch which words become similar as a result. At the very bottom it squeezes the long count rows down to two numbers each. Those are coordinates like on the map above.
The embedding table
All these lists sit in one big table with one row per token: V rows, D columns, so shape [V,D]. For ID 42 the model simply reads row 42. No searching for meaning, just looking up, like in a phone book.
import torch
from torch import nn
embedding = nn.Embedding(100, 16)
ids = torch.tensor([[4, 12, 4]])
x = embedding(ids)
assert x.shape == (1, 3, 16)
assert torch.equal(x[0, 0], x[0, 2])The two occurrences of ID 4 get exactly the same vector here. They only become different later, when position and context come in.
The mathematically curious sometimes hear about the one-hot vector: a list with a 1 at the position of the ID and zeros everywhere else, so [0,1,0] for ID 1. Multiply it by the table and you get exactly the row you want. In practice you skip the long list of zeros and look up directly.
No built-in meaning drawers
Tempting but wrong: “number 0 means animal, number 1 means color”. The individual components have no fixed meaning. You could rotate the whole map, and with adjusted weights the model would work just as well.
Sometimes, though, directions can be interpreted. The most famous example comes from word2vec: compute “king − man + woman” and you land near “queen”. So the direction from “man” to “woman” is roughly the same as from “king” to “queen”. Neat, but it only works roughly, only for some word pairs, and more by luck than by system.
“Similar words end up close together” is also a tendency, not a guarantee. A small model, for example, first learns letter and syllable patterns. It doesn't get a map of meanings from us.
One word, several meanings
The word “bank” always has the same ID and therefore the same row in the table, whether it is about money or a river. On the word map above you can see what follows from that: the bank ends up somewhere between the furniture corner and the money corner. Its embedding is like a dictionary entry that lists all meanings at once.
Only the rest of the sentence can settle which bank is meant. In “money at the bank” the bank has to slide toward money, in “sitting on the bank by the river” toward the riverside. That is exactly what attention does later: every word looks at the other words in the sentence and mixes in matching information. What comes out is called a contextual embedding or hidden state.
So the division of labor is:
- Embedding: what does this word mean in general?
- Attention: what does it mean here, in this sentence?
And at the end, back to tokens
At the model's output the whole thing runs the other way: an internal list of numbers has to become a rating for every possible token again.
An example: let the internal list be h = [1,2]. For three tokens we have the rows [1,0], [0,1] and [1,1] in a weight table. We take the dot product of each with h and get 1, 2 and 3: three logits, one per token. Softmax turns them into percentages. And there is the prediction.
The output layer as a formula
In general: . h is the internal list with D numbers. is a table with V rows and D columns; each row yields one logit. b is a bias list with V entries. z are the V finished logits.
In technical texts you will often read . The ∈ means “is an element of”, and ℝ stands for the real numbers. All it means: h is a list of D ordinary decimal numbers. Likewise the output lives in , so it has V numbers.
Weight tying: one table for two jobs
Interesting: the input table (ID → list) and the output table (list → rating per token) both have one row per token. So you can merge them into a single table. That is called weight tying:
self.embed = nn.Embedding(V, D)
self.head = nn.Linear(D, V, bias=False)
self.head.weight = self.embed.weightThe shared table is trained in both roles. That saves parameters and keeps small models tidy. Whether it is always better depends on the model.
Measuring similarity
How do you measure whether two lists are “similar”? Compare a = [1,0] with b = [2,0]. Both point in the same direction; b is just twice as long. The dot product is 2. The length of a list is the square root of the sum of its squares: a has length √(1²+0²) = 1, b has length √(2²+0²) = 2.
Dividing the dot product by both lengths gives 2/(1×2) = 1. This cosine similarity is 1 for the same direction, −1 for opposite directions and 0 for perpendicular ones.
The dot is the dot product; the double bars mean length. If a list has length zero, the division doesn't work, and the experiment shows no value.
Another measure is the Euclidean distance, the plain distance as with a ruler: square the differences per component, add them up, take the square root. From [1,0] to [2,0] it is 1. Same direction, but not the same place.
The experiment uses freely adjustable two-dimensional lists, not real learned embeddings. And even with real ones: close together doesn't automatically mean the same meaning.
A sizing example
With V = 4096 tokens and D = 256 numbers per token, the table has 4096 × 256 = 1,048,576 parameters. In the Float32 format each number needs 4 bytes. That makes 4 MiB (one MiB is 1,048,576 bytes, a bit over a million). Two separate tables: 8 MiB.
Training needs much more memory, though, because gradients and optimizer states come on top. “The table fits in memory” doesn't yet mean “training fits”. More on number formats in the chapter on precision.
Build it yourself: in step 4 of part VII you program the embedding tables including weight tying.
Key points
- An embedding is a learnable list of numbers per token, looked up in a table of shape [V, D]. It is learned in the same training run as everything else.
- Words that occur in similar sentences get similar lists, because that helps with predicting, not because someone prescribes meanings.
- A word with several meanings still has only one row. Which meaning is meant is settled by the context, that is, by attention.