Chapter 5: Embeddings¶
Figure 5.1: We have IDs, and now each one gets a learned vector.
In the previous chapter, we turned text into tokens (Figure 5.1), but tokens are arbitrary numbers. To predict what comes next, the model needs to understand how characters relate to each other. In this chapter you will:
- Map simple token IDs to large vectors of numbers.
- Learn how these vectors capture meaning as coordinates.
- Add position information so the model knows the order of characters.
Words to Know
- Vector: A list of numbers that works like coordinates on a map, giving a token its place among the others.
- Embedding: A lookup table that gives each token ID its own vector.
Theory¶
The Problem with IDs¶
Figure 5.2: Token IDs are arbitrary labels.
After tokenization, we have our tokens as integers: A=13, B=14, a=39. The issue with using these numbers directly in our neural network is shown in Figure 5.2. Our neural network learns by finding numbers and multiplying them by each other. So it would see Z (token 38) as roughly three times as large as A (token 13). It might learn that Z is more important than A simply because of how we assigned token values.
Similar to an employee ID number they aren't five times as much of an employee just because their number is 105 and someone else's is 21. We need to convert these values into something our "Numbers Machine" can learn correlations from.
Vectors as Coordinates of Meaning¶
Figure 5.3: An embedding table maps each ID to a vector of numbers.
We fix this by using a lookup table known as an embedding (Figure 5.3). For each token ID we assign a vector which is just a set of decimals also known as floating-point numbers. Our model will have 128 floats per character.
Now when our model sees 39 for the letter a it will instead see [0.55, 0.03, -0.89, ...]. We can think of these 128 floats as coordinates, and characters that appear in similar contexts will gradually be moved closer together in this 128-dimensional space during training. Our net will understand that capital and lowercase versions of a letter behave similarly, so their vectors become similar. This is something our model learns.
Position Embeddings¶
Figure 5.4: The final representation combines what the token is with where it sits.
There is also an issue with our current model in that it reads all of the characters simultaneously. There is no way for our model to distinguish between "cat" and "act". They are made of the same characters.
The answer is to create a second lookup table called the positional embedding (Figure 5.4). Similar to before, we will look up a row in this table based on what position the character is in the sequence. We don't care about the token ID for this table. So position 0 will have a 128-number vector assigned to it. Position 1 will have another vector and so on.
Now that we have our token embedding and positional embedding, we will just add them together. Our network will learn to represent the information of what character this is and what position it is at using these 128 numbers. Since we now have a way to represent the character and position we have finished our Embeddings block from Figure 5.1. Now we have an array of numbers to feed into the next block.
In Business
When you build an assistant that writes in your company's house style, embeddings turn your archive into a map of meaning. Token embeddings capture the vocabulary, while the position embeddings give the model the order of the characters, which is what lets it pick up the shape of an invoice or a polite greeting.
Code¶
We use src/ch04_embeddings.py to create and combine these two tables.
| src/ch04_embeddings.py (excerpt) | |
|---|---|
When we run it, the script prints this:
$ python src/ch04_embeddings.py
--- 2. Looking up embeddings ---
Input token_ids shape : torch.Size([2, 5])
Token embeddings shape: torch.Size([2, 5, 128])
(B=2, T=5, C=128)
...
--- 3. Positional embeddings ---
Position indices: [0, 1, 2, 3, 4]
Position embeddings shape: torch.Size([5, 128])
--- 4. Combining token + position embeddings ---
Final x shape: torch.Size([2, 5, 128])
(B=2, T=5, C=128)
What just happened:
- Line 1 created a lookup table for the 65 characters in our vocabulary.
- Line 2 translated a batch of token IDs into their embedding vectors.
- Line 3 created a second lookup table for the sequence positions.
- Line 6 added the token and position vectors to create the final input
x.
Shape Check: Table 5.1 shows the dimensions of our data structures.
Table 5.1: Tensor shapes before and after the embedding layer.
| Variable | Shape | Meaning |
|---|---|---|
token_ids |
[B, T] |
Batch size by Time (sequence length). |
token_embeddings |
[B, T, C] |
C is the embedding dimension (128). |
position_embeddings |
[T, C] |
One vector per position. |
x |
[B, T, C] |
The combined input for the model. |
Try It¶
Try It
In src/ch04_embeddings.py, add one more token ID to each row of token_ids (any number from 0 to 64) and change T from 5 to 6. Run the script again. The output shape grows from [2, 5, 128] to [2, 6, 128], but the parameter counts stay exactly the same. The lookup tables do not care how much text you process at once.
Watch Out
A common mistake is trying to look up a token ID that is not in the vocabulary. If your vocab_size is 65, the valid IDs are 0 to 64. Passing an ID of 65 will crash the program with an "index out of bounds" error.
Key Takeaways¶
- Token IDs are arbitrary labels and cannot be used directly for math.
- Embeddings are learned lookup tables that map token IDs to vectors.
- These vectors act as coordinates that capture relationships and meaning.
- Positional embeddings are added to tell the model the order of the characters.
Check Your Understanding¶
- Why do neural networks struggle with raw token IDs?
- How many numbers make up a single character's embedding vector in our model?
- Why do we need positional embeddings in addition to token embeddings?
- Does the size of the embedding table depend on the batch size?
Assignment¶
Assignment 5: Bigger ID, bigger numbers?
About 15 minutes. You change one number and write no new code. Work in this chapter's Colab notebook or on your own laptop.
- Run it. Run
src/ch04_embeddings.pyas it is. Copy the line that starts withFirst token's embedding. It shows the first 8 of the 128 numbers for the first token. - Change one number. Find the line
token_ids = torch.tensor([[3, 14, 7, 2, 50], [10, 22, 45, 1, 8]]). These are ten token IDs. Change the first one,3, to38, so the line starts withtoken_ids = torch.tensor([[38, 14,. Run the script again. - Compare. Did the 8 numbers change? Are they bigger, now that the ID is bigger? Did any shape, or any count under
--- Summary ---, change? - Explain it. In two or three sentences a manager could follow, say what the token ID is used for here, and whether the size of the ID matters.
Hand in: both First token's embedding lines, your answers to step 3, and your sentences.
Further Reading¶
Meaning becomes geometry. If every word gets its own ID number, the model learns nothing from the numbering, and "king" sits as far from "queen" as it does from "toaster". This paper trained a deliberately cheap prediction task so that words used in similar company ended up with similar vectors, and did it fast enough to run on billions of words. Embeddings, the subject of Chapter 5, start here, and so does the vector search behind modern recommendation and retrieval.
Mikolov, T., Chen, K., Corrado, G., & Dean, J. (2013). Efficient estimation of word representations in vector space (arXiv:1301.3781). arXiv. https://doi.org/10.48550/arXiv.1301.3781
Next up: Chapter 6: Self-Attention