Embeddings: Giving Each Token a Meaning
Token IDs name pieces but describe no meaning. Learned vectors provide usable features. Follow the lookup, its training signal, and the choice to share input and output weights.
#Section 9An Id Is a Name Tag, Not a Quantity
After Part I, our sentence has become seven ids: 791, 8415, 7731, 1606, 433, 574, 19781. It would be tempting to feed those integers straight into the network as numbers. That would be a disaster, and seeing why is the whole motivation for this part.
Token IDs are labels. Renumbering them consistently would not change meaning, so treating their numerical distance as a semantic distance would be arbitrary.
An embedding is a learned feature vector for a token. A vector is an ordered list of numbers, and its dimension is the number of entries. These features replace arbitrary IDs in downstream computation.
#Section 10The Lookup Table
The embedding matrix has one row per token and one column per feature. A matrix is a grid of numbers. Looking up a token ID selects its learned row.
To turn an id into a vector, copy the row with that number. Nothing is computed. For our sentence, seven ids fetch seven rows, and stacking them gives a grid with 7 rows and 512 columns. That grid is called , and it is the input to everything that follows.
The lookup gives one feature vector per input position. Stacking them preserves the sequence order for later operations.
The same token always fetches the same row, regardless of position. A batch processes several sequences together; the additional axis identifies which sequence each vector belongs to.
In code the whole step is one line:
emb = torch.nn.Embedding(32000, 512) # the table E, 16,384,000 numbers
x = emb(ids) # ids: (B, T) integers -> x: (B, T, 512)#Section 11Why a Lookup Counts as a Matrix Multiply
An embedding lookup equals a matrix multiply, which explains how training adjusts the table like any other weight.
A one-hot vector is zero everywhere except at the selected ID. Multiplying it by the embedding table selects exactly that row, because all other rows are multiplied by zero.
Code performs a direct lookup instead of constructing the mostly-zero vector. The multiplication view explains why input-lookup gradients touch only the selected rows.
#Section 12A Map of Meaning
Each embedding is a list of 512 numbers, which you can think of as a point in a 512-dimensional space. Nobody can picture 512 dimensions, so the drawings squash things down to two, but the idea survives the squashing. After training, words that are used in similar ways end up close together. Animals sit near animals, vehicles near vehicles, feelings near feelings.
Word2vec, introduced by Tomas Mikolov and colleagues in 2013, showed that learned directions can capture relationships such as king to queen. Such examples illustrate geometry; they are not a guarantee that every relationship is a clean direction.
Measuring "similar": cosine similarity
To say how similar two vectors are, we need a number. The standard choice is cosine similarity, which asks one question: do the two arrows point the same way? It ignores how long the arrows are and looks only at the angle between them.
Read it piece by piece. The top, , is the dot product: multiply the two vectors entry by entry and add up the results. The bottom multiplies their lengths, where the length is the square root of the sum of squared entries. Dividing by the lengths removes the effect of size, leaving only direction. The result runs from 1 (same direction) through 0 (at right angles, nothing in common) to (opposite directions).
The dot product is central to this chapter. In Part VI, attention uses it to decide how much one token listens to another, without dividing by the vector lengths.
#Section 13Where the Map Comes From
Nobody writes these vectors by hand, and nobody tells the model that cats and kittens are related. At the start of training, every row of is filled with small random numbers. The map is noise. Then training begins: the model predicts next tokens, measures how wrong it was, and nudges every weight, including the rows of that were used, a tiny bit in the direction that would have made the prediction better. Part XIII covers that loop in detail.
Why do clusters form? Because of a simple pressure. cat and kitten appear in similar sentences: both are followed by purred, sat, was hungry. If their vectors are similar, the rest of the network can handle them with the same machinery, and predictions after either one improve together. Every update that helps predict "the cat purred" also nudges cat toward whatever direction is useful for "purred", and so does every update for "the kitten purred". Over millions of steps, words used in similar contexts get pulled toward similar vectors. The map is a side effect of learning to predict.
This idea has a name in linguistics, the distributional hypothesis, usually quoted from J. R. Firth in 1957: "You shall know a word by the company it keeps." Embeddings are that hypothesis turned into an optimization.
#Section 14The Size of the Table, and Sharing It
Embedding storage grows with vocabulary size and feature width. In a small model it can be a large share of the weights.
There is a second matrix of exactly the same size at the far end of the model. After the last layer, each position holds a 512-number vector, and the model must turn it into 32,000 scores, one per possible next token. That job is done by the LM head (language-model head), a matrix of shape , which Part XII covers. Notice that it has the same shape as flipped on its side, written (the transpose: rows become columns).
Weight tying uses one matrix for both input lookup and output scoring. These jobs connect token identity with learned features in opposite directions. Press and Wolf, and Inan and colleagues, proposed tying in 2016.
Whether to tie is a size question. GPT-2 tied its embeddings, and so does Finch-19. Llama 3.2's small 1B and 3B models tie them too. Llama 3 8B and larger models keep them separate, because in a big model the table is a small fraction of the total and the extra flexibility helps.
Sharp edges of embeddings
Out-of-range ids crash. If the tokenizer produces id 32,003 but the table only has 32,000 rows, the lookup fails. On a GPU the error message is often a confusing "device-side assert". This usually happens after someone adds special tokens to the tokenizer and forgets to resize the model's table. Always check that the tokenizer and the model agree on , including special tokens.
Padding has a row too. When sentences of different lengths are batched together, short ones are filled up with a padding token. That token still fetches a row and produces a vector. The model will happily attend to it unless you mask it out, which Part VIII shows how to do, and you must also exclude it from the loss.
Rare tokens barely move. A token that appears a handful of times in training gets a handful of updates, so its row stays close to random. This is the mechanism behind the under-trained tokens of Section 8.
Scaling conventions differ. Some architectures rescale embeddings before adding position information. Match the checkpoint's convention; a different scale changes every input.