Highlights

Contents

Part II
02

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.

YOU ARE HERE"raw text"tokenizerembeddings+ positionslearnedwavesRoPEDECODER BLOCK× NnormattentionQKVsoftmaxmaskheadsn × n+normMLP+residual streamKV cachefinal normLM headsoftmaxP(next)training: the loss sends a correction back to every weight

#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.

TOKEN IDS ON A NUMBER LINE: THE DISTANCES MEAN NOTHING08,00016,00024,00032,000␠it 433The 791␠because 1606␠sat 7731␠cat 8415␠kitten 23140␠tired 19781"cat" sits next to "sat" and far from "kitten":a seat number, not a description
Figure 1.12Token ids on a number line. Numerical closeness is an accident of when each merge was learned: cat lands next to sat and far from kitten. Any arithmetic on raw ids would learn from that accident.

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 EE 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 xx, and it is the input to everything that follows.

xi=E[idi]x∈RT×dmodelx_i = E[\text{id}_i] \qquad x \in \mathbb{R}^{T \times d_{\text{model}}}

The lookup gives one feature vector per input position. Stacking them preserves the sequence order for later operations.

THE EMBEDDING LOOKUP: EACH ID COPIES ONE ROW OF EThe791␠cat8415␠sat7731␠because1606␠it433␠was574␠tired19781E (32,000 × 512)row 8415one row per token in the vocabularyx (7 × 512)a copy, not a calculation
Figure 1.13The embedding lookup. Each id selects one row of E and copies it into the input grid x. The table does not care about order or neighbours: the same token always gets the same row, wherever it appears.

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:

python
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.

LOOKUP = ONE-HOT ROW × TABLE (TOY: V = 5, d = 4)00100one-hot for id 21 × 5×0.2-0.10.50.30.90.4-0.20.10.30.80.6-0.4-0.50.20.10.70.0-0.60.40.201234E (5 × 4)=0.30.80.6-0.4exactly row 2 of Eevery other row ismultiplied by zero
Figure 1.14A lookup written as a multiply. The one-hot row for id 2 selects row 2 of the table; every other row is multiplied by zero and contributes nothing.
onehot(id)⋅E=E[id]\text{onehot}(\text{id}) \cdot E = E[\text{id}]

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.

A 2-D SKETCH OF EMBEDDING SPACE (REAL ONES HAVE HUNDREDS OF DIMENSIONS)catkittendogpuppyhorsecartruckbusbicyclehappygladsadtiredkingmanwomanqueensame "male → female" directionking − man + woman≈ queen
Figure 1.15A two-dimensional sketch of embedding space. Similar words cluster. Directions can carry meaning too: the arrow from man to woman is roughly parallel to the arrow from king to queen. (Positions are illustrative.)

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 θ\theta between them.

cos⁡θ=a⋅b∥a∥ ∥b∥\cos\theta = \frac{a \cdot b}{\lVert a \rVert \, \lVert b \rVert}

Read it piece by piece. The top, a⋅ba \cdot b, is the dot product: multiply the two vectors entry by entry and add up the results. The bottom multiplies their lengths, where the length ∥a∥\lVert a \rVert 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 −1-1 (opposite directions).

COSINE SIMILARITY ONLY LOOKS AT THE ANGLE BETWEEN TWO ARROWSθ = 0° cos = 1.00same directionθ = 60° cos = 0.50relatedθ = 90° cos = 0.00unrelatedθ = 180° cos = −1.00opposite
Figure 1.16Cosine similarity depends only on the angle. Same direction gives 1, a sixty-degree angle gives 0.5, a right angle gives 0, and opposite directions give minus one.
SIX TOY 4-NUMBER EMBEDDINGS AND THEIR COSINE SIMILARITIEScat0.80.60.10.0kitten0.70.70.20.1dog0.70.40.3-0.1car0.10.00.90.4truck0.00.10.80.6the-0.30.2-0.20.91.000.980.950.170.14-0.140.981.000.930.290.28-0.020.950.931.000.350.25-0.330.170.290.351.000.960.150.140.280.250.961.000.40-0.14-0.02-0.330.150.401.00catcatkittenkittendogdogcarcartrucktruckthethesimilar meaning, similar stripsbright blocks = clusters
Figure 1.17Six toy embeddings as colour strips (left) and every pairwise cosine similarity (right). The animals form one bright block, the vehicles another, and the resembles nothing.

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 EE 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 EE 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.

TRAINING PULLS WORDS USED IN SIMILAR SENTENCES TOGETHER (ILLUSTRATIVE)step 0: random rowscatdogkittenpuppycarbustruckhappysadgladafter training: clusterscatdogkittenpuppycarbustruckhappysadglad
Figure 1.18Before and after training. At step 0 the rows are random and the map has no structure; after training, words that appear in similar contexts have been pulled into clusters. (Illustrative.)

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.

ONE LOOKUP, TWO CONTEXTSriverbanksavingsbankE[bank]same vectorbank + river contextbank + savings contextembedding lookupafter attentionthe row knows the token; attention supplies the neighbours
Figure 1.19The token bank fetches the same embedding in both phrases. Attention can then produce different vectors because river and savings supply different context. Phrase fragments are illustrative.

#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 512×32,000512 \times 32{,}000, which Part XII covers. Notice that it has the same shape as EE flipped on its side, written E⊤E^\top (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.

WEIGHT TYING: ONE MATRIX USED AT BOTH ENDS OF THE MODELembedding E32,000 × 512LM head = Eᵀ512 × 32,0008 blockssamenumberstied (Finch-19)42,128,384untied58,512,384untying adds 16,384,000 parameters (+39%)
Figure 1.20Weight tying. The embedding matrix E is reused, transposed, as the LM head. For Finch-19 this saves 16,384,000 parameters, which would otherwise add 39% to the model.

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 VV, 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.