A network multiplies and adds numbers. But much of what we want it to read is not a number: a word, a user ID, a product code, a country. The first idea is to give each category a number, so that “cat” is 1, “dog” is 2 and “carburettor” is 3. That fails in an unobvious way: a weight multiplies the id, so id 4 would count twice as much as id 2, and “dog” would sit exactly between “cat” and “carburettor” for no reason at all. The ids are labels, not quantities.
The second idea is a one-hot vector (P3.A11): one slot for each of the categories, with a in the slot of the category and everywhere else. It is honest about the labels, but it has two faults:
- It is huge and almost empty. For a vocabulary of tokens, every token is a vector of numbers, and of them are zero.
- It treats every pair as equally different. Any two different one-hot vectors are apart and have cosine similarity (P1.B3). To the network, “cat” is exactly as unlike “dog” as it is unlike “carburettor”, and nothing it learns about one carries over to the other.
An embedding layer fixes both. It gives every id a short vector of learned numbers (for example ), and training moves the vectors so that ids used in similar ways get similar vectors. This lesson shows how the layer works, why its output is just a row of a table, how the table is trained, and what to watch for in practice.
The embedding table
Make a toy vocabulary of four tokens, numbered to , with numbers per token. These are the made-up values of the matrix-map lesson (P1.B15), not trained values. They are the rows of the embedding table, a matrix with one row per id, so its shape is :
The embedding of id is row of , written . The embedding of “cat” (id ) is . That is the whole layer: a lookup.
A lookup is a product, done as indexing
P1.B6 showed a product as a mix of rows. A one-hot vector, as a row, has a single at the id, so it mixes the rows of with weight for one row and for the others:
For the two tokens “cat sat” (ids and ), stack the one-hot rows into a matrix of shape and multiply:
So a lookup is a matrix product with a one-hot matrix. Real code never builds . Multiplying would cost multiplications per token, almost all of them by zero, and would need a matrix. Indexing copies the numbers of the row and does no arithmetic: in NumPy E[ids], in PyTorch emb(ids). The two give identical numbers, and the equality matters because it tells us how gradients behave (see the section on how the table is learned).
A batch of ids
The ids are integers, not floats: they are positions in a table. A batch of sequences of ids is an integer tensor of shape , and indexing the table with it gives a float tensor of shape : every id is replaced by its row, and a new last axis of length appears. With the toy table and ids [[1, 2, 1], [3, 0, 2]] (two sequences of three tokens, , ), the output has shape : the first sequence becomes and the second .
This is the tensor that the leading-axes box of P4.5 describes. A layer such as nn.Linear(d, d_out) that comes next acts on the last axis only, on each of the vectors on its own. The widget builds the output for one sequence.
Things to try. Build “cat cat cat” and watch row appear three times in the output. Switch to Training step: row gets the sum of three gradients, and the other seven rows get none. Add a token and the count of rows with gradient goes up by at most one.
How the table is learned
The table is a matrix of parameters, like the weights of P4.5. It starts random (PyTorch’s nn.Embedding draws every number from a normal distribution with mean and standard deviation ) and is trained by backpropagation (P4.8).
Write the lookup as with fixed (it only holds the ids). Suppose the layers above hand back , the gradient of the loss with respect to , one row for each position. The shape rule is the one for a layer’s weights: the fixed factor, transposed, times the upstream gradient. It gives
Read it as a recipe: each position adds its row of to the row of that it used. Take “cat sat cat”, ids , and let the gradients arriving at the three positions be , and . Then:
- Row (“cat”) was used at positions and , so it gets .
- Row (“sat”) was used once, so it gets .
- Rows and were not used, so their gradient is .
One gradient step with learning rate changes only the used rows: row goes from to and row from to . The rows of “the” and “mat” stay exactly as they were.
Two consequences follow:
- Repeated ids add up. This is the “add with
+=” rule of the autograd lesson (P4.9): a value used twice receives two contributions. It is also the most common bug when you write the backward pass by hand: in NumPy,g[ids] += Gapplies the update once per distinct id, so a repeated id loses all but one contribution (the first code cell shows instead of ). The correct call isnp.add.at(g, ids, G), which is what the matrix product computes. - The update is sparse. With plain gradient descent, a step changes only the rows that appeared in the batch. In a table with rows, a step updates at most as many rows as there are tokens in the batch, and a rare id is updated rarely, so its row can stay poorly trained. (An output layer that shares the table, or an optimizer with memory, can touch the other rows too. Both come back below.)
What the rows learn
Nothing tells the network what an id means. The rows only get pushed by the loss, and that is enough for structure to appear. If two ids lead to the same answers, the same later layers must turn both their vectors into the same output, so training pulls the two rows towards each other. Ids that are used in similar ways get nearby rows, and cosine similarity (P1.B3) measures how nearby.
A tiny experiment shows it (the second code cell). Take made-up ids that secretly fall into groups of three. The task is to predict one of three outcomes from the id alone, and the id’s group decides the outcome percent of the time. A learned linear layer reads each id’s row and scores the three outcomes (and is trained too). The table has numbers per id, starting random, with one extra id, number , that never appears in the data. After 300 plain gradient steps:
- The mean cosine between two ids of the same group goes from to , and between ids of different groups from to (three groups spread out at about in two numbers, which gives a cosine of about ).
- The loss on a fixed test sample goes from to , close to the best this noisy task allows, about .
- The row of the unused id is unchanged, exactly as the sparse-update rule says.
Nobody told the model about the groups. The geometry of the table reflects how the ids are used in the task. For a table trained on text, the “task” is to predict words, so words that appear in similar contexts get similar rows. Word2vec (Mikolov and co-authors, 2013) trained word vectors with two simple architectures (CBOW and skip-gram) on a corpus of 1.6 billion words in under a day, and the 2013 paper reports that vector arithmetic such as lands closest to the vector of “Queen”. That is a reported result of a particular method, and P6.3 and P6.4 look at how it works and where it fails.
How big is the table?
The table has parameters. For and that is . The released GPT-2 small model (its config lists a vocabulary of and a width of ) has numbers in its token table, about MB in 32-bit floats (taking 1 MB bytes). A lookup is cheap, since it only copies numbers, but the table sits in memory in full. In a small language model the table can be a large share of all parameters. There is no rule for : a wider vector can hold more distinctions but costs more memory, and the right size depends on the task. Real tables range from a handful of numbers per id up to thousands.
Details that matter in practice
Padding. A batch needs sequences of the same length, so shorter ones are padded with a reserved id. PyTorch’s padding_idx makes the row of that id start as zeros and never receive gradient, so the padding row stays at zero. The model still has to be told to ignore padded positions elsewhere (masking, P7.8).
Unknown ids. An id outside the range is an error, not a quiet zero. Text pipelines reserve one id for “unknown” and send every unseen word to it, or avoid unknowns by splitting words into pieces (P10.A2). For a category with many rare values, you can also give all rare values one shared row, or hash each value to one of a fixed number of rows (P3.A11), so that several categories share a row.
More than one categorical feature. A recommender may have a user ID and a product ID, each with its own table. Their vectors are combined, for example by joining them end to end, before the next layer.
Positions. Order is not in a token’s row: “dog bites man” and “man bites dog” would have the same rows. A common fix is a second table with one row per position, , and the vector sent on is the token row plus the position row. The released GPT-2 small learned such a table with rows. P7.6 compares learned tables with fixed formulas.
Sharing the table with the output layer. A language model ends by scoring every one of the ids, with a layer whose weight matrix has shape , the same shape as . Weight tying uses one matrix for both. Press and Wolf (2017) recommended it for language models. It saves parameters, and because the output layer scores every id, every row of the table now gets gradient at every step.
Depth: three ways to see it
Intuition
An embedding table is a rack of pigeonholes, one for each id, and each pigeonhole holds a card with numbers on it. A lookup reads the card in one pigeonhole. Training rewrites the cards: when the loss pushes, only the cards that were read are rewritten, and cards read in similar situations drift to look alike. The analogy breaks in two places. The pigeonhole numbers have no order (id 5 is not near id 6), and what a card means is not written anywhere, it is only visible in how it compares with the other cards.
Math
The layer is , with having one per row, so . The gradient is : row of it is the sum of the rows over all positions with , and it is the zero row if does not occur.
The lookup is also a linear layer without a bias: nn.Linear(V, d, bias=False) applied to a one-hot vector gives column of , so the table is . The only difference is the cost, indexing against a product.
If the next operation is a linear layer, its weights can absorb any rotation of the embedding space, , so a network with rotated embeddings and adjusted weights computes the same function. So training has no reason to give an individual axis (“number 0”, “number 1”) a meaning of its own: in this simple setting only the distances, angles and directions between rows are determined.
Code
import torch
import torch.nn as nn
torch.manual_seed(0)
big = nn.Embedding(10000, 64).weight.detach()
print("default init: mean %.2f, std %.2f" % (big.mean(), big.std()))
emb = nn.Embedding(num_embeddings=5, embedding_dim=3, padding_idx=0)
print("weight shape:", tuple(emb.weight.shape))
print("padding row :", emb.weight[0].tolist())
ids = torch.tensor([[1, 2, 1], [3, 0, 0]]) # (B, T); 0 = padding
out = emb(ids)
print("ids", tuple(ids.shape), "-> out", tuple(out.shape))
print("same as indexing :", torch.equal(out, emb.weight[ids]))
onehot = nn.functional.one_hot(ids, 5).float() # (2, 3, 5)
print("one-hot @ E equal:", torch.allclose(onehot @ emb.weight, out))
out.sum().backward()
print("rows with gradient:", (emb.weight.grad != 0).any(1).tolist())
print("row 1 (used twice):", emb.weight.grad[1].tolist())
print("row 0 (padding) :", emb.weight.grad[0].tolist())
print("parameters, 50257 x 768:",
sum(p.numel() for p in nn.Embedding(50257, 768).parameters()))Output from a local run with PyTorch 2.9.1:
default init: mean -0.00, std 1.00
weight shape: (5, 3)
padding row : [0.0, 0.0, 0.0]
ids (2, 3) -> out (2, 3, 3)
same as indexing : True
one-hot @ E equal: True
rows with gradient: [False, True, True, True, False]
row 1 (used twice): [2.0, 2.0, 2.0]
row 0 (padding) : [0.0, 0.0, 0.0]
parameters, 50257 x 768: 38597376nn.Embedding(num_embeddings, embedding_dim) is the table. With out.sum() as the loss, the gradient at every output number is , so row , used twice, gets in every entry. Row was never used and the padding row is switched off, so only rows , and have a gradient.
Go deeper Optimizers with memory touch unused rows
“Only the used rows change” holds for plain gradient descent. SGD with momentum (P4.13) keeps a running sum of past gradients and adds it at every step, so a row that was used in an earlier step keeps moving in a later step in which it was not used. A local check with PyTorch 2.9.1 and momentum confirmed that a row used once moved again on the next step, in which the batch did not contain it. Adam keeps running averages of the gradient for every number, so a row used earlier keeps moving after its gradient has stopped, and weight decay (P4.17), when it is applied to the table, shrinks every row at every step. PyTorch offers sparse=True on nn.Embedding together with optimizers that update only the used rows, which trades this behaviour for speed and memory on huge tables (some options are not supported with sparse gradients: a local check with PyTorch 2.9.1 showed that plain Adam and SGD with weight decay raise an error, and SparseAdam exists for this case).
Go deeper Weight tying in more detail
With tying, the scores for the next token are , where is the final vector of numbers: the score of id is the dot product of with the row . So the row of an id plays two roles: the vector for reading the id in, and the direction that gets a high score when the model predicts it. This requires the output layer to have the same width as the embedding. The saving for the lesson’s example, and , is another parameters that would otherwise be stored separately. In the Hugging Face implementation of GPT-2 the two are tied by default (its config sets tie_word_embeddings to true). Not every model ties them, so check the model’s own configuration.
Try it in Python
The first cell uses the toy table of this lesson: a lookup as indexing and as a one-hot product, the cosines of the toy rows, and the gradient of a lookup with the repeated-id bug. The second cell is the training experiment of the section on what the rows learn.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Running the cell gives shape , equality of the two ways of looking up, the cosines , and , row of the wrong gradient and of the right one , and the updated table with rows and .
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The cell prints a loss of before and after training, a mean cosine within groups of before and after, and across groups before and after, and that row is unchanged. Because the test sample is finite and random, a loss slightly below the floor of can occur. Try a different seed, a smaller step size, or and see what changes.
Common mistakes
Quiz
Check your understanding
An embedding table has shape . A batch of integer ids has shape . What is the shape of the output of the lookup?
Each of the ids is replaced by its row of numbers, so a new last axis of length is added to the shape . A last axis of is the size of the one-hot version of the ids, which the lookup never builds. Shape would mean the positions were merged or averaged, and the lookup does neither. The table’s own axes do not move to the front of the output.
In a vocabulary of tokens, what is the cosine similarity between the one-hot vectors of two different tokens?
Two different one-hot vectors have their in different slots, so their dot product is and so is the cosine: every pair looks equally unrelated. The number is their distance, not a cosine, and a cosine never exceeds . The value would mean the same direction, which holds only for the same token. One-hot vectors are built without any text, so no co-occurrence enters.
A batch contains the ids , and the table has rows. Which rows get a nonzero gradient from this batch?
Each position adds its gradient to the row it used, so a repeated id receives the sum of its positions’ gradients, and the unused rows get zero. An average would come from a different loss, not from the lookup itself. The statement that every row is reached is wrong for a plain lookup. Keeping only the last gradient is exactly the bug of writing
g[ids] += Gin NumPy.A model has an embedding table for ids with . How many parameters does the table have?
Each of the ids has its own row of numbers, and . The sum confuses a count of rows plus columns with a count of entries. The number of ids alone, , ignores the width. The value is the product with , half the width.
What does
padding_idx=0in PyTorch’snn.Embeddingdo?The padding row is initialised to zeros and is excluded from gradient updates, so it stays at zero. The table keeps all its rows, and the padding id still indexes row . Skipping padded positions in later layers is the job of a mask (P7.8), not of the embedding layer. Only the one row is zero, not the embedding of every id.
Exercises
- With the toy table of this lesson, what is the product of the one-hot row for “mat” (id ) with , and what is ?
Show answer
The one-hot row is , so the product is row of , . The cosine of and is . - A model reads batches of sequences of ids from a vocabulary of , with . What is the shape of the output of the embedding layer, and how many parameters does the table have?
Show answer
The output has shape . The table has parameters, whatever the batch size is. - The ids are with the toy table, and the gradients arriving at the three positions are , and . Find the gradient of , and the table after one step with .
Show answer
Row gets and row gets , and rows and get . After the step row is and row is . Rows and are unchanged, and . - A table for ids with is stored in 32-bit floats (4 bytes each). How much memory does the table take?
Show answer
It has numbers, which is bytes, or MB (taking 1 MB bytes). - A language model has and . How many parameters does an output layer of shape add if it is separate from the embedding table, and how many extra if the two are tied?
Show answer
Separate: another parameters (ignoring a bias). Tied: no extra parameters, because the output layer reuses the table.
Next: P4.22 gives a training recipe and debugging routine for networks like the ones built so far, and P6.3 shows how word vectors are trained from text. P7.6 adds positions to token vectors, and P7.3 shows what attention does with them.