Chapter 5: Embeddings¶
Figure 5.1: We have IDs, and now each one gets a learned vector.
Previously, we converted our text to tokens (Figure 5.1), but those tokens are arbitrary numbers. The model needs to know how characters relate to other characters to predict what is next. 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
Embeddings allow your archive to become a map of meaning if you train an assistant to write in your company's house style. While the token embeddings represent the vocabulary, position embeddings allow the model to learn the order of the characters. This is what allows the model to understand the shape of an invoice or a courteous salutation.
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
Modify src/ch04_embeddings.py. Add one additional token ID to each row of token_ids (it can be any integer from 0-64), and update T from 5 to 6. Then run the script again. You should see that the output shape increases from [2, 5, 128] to [2, 6, 128], but your parameter counts remain precisely the same. Lookup tables do not care how much text you run through them at once.
Watch Out
A mistake that trips people up is trying to look up a token ID that isn't in your vocabulary. So if your vocab_size is 65, you have tokens that range from 0-64. If you were to enter a token ID of 65, you would get an "index out of bounds" error.
Key Takeaways¶
- Token IDs are arbitrary identifiers that we can't use directly for math.
- Embeddings are learned lookup tables that translate token IDs into vectors.
- These vectors are coordinates that encode relationships and semantics.
- Positional embeddings are added to provide information about the order of the characters to the model.
Check Your Understanding¶
- Why do neural networks struggle with raw token IDs?
- What is the length of the embedding vector for each character in our model?
- Why do we need positional embeddings besides the token embeddings?
- Is the embedding table size affected by 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.pyunchanged. Copy the line beginning withFirst token's embedding. This prints out the first 8 of 128 numbers from the embedding for the first token. - Change one number. Locate the line that says
token_ids = torch.tensor([[3, 14, 7, 2, 50], [10, 22, 45, 1, 8]]). This line contains ten token IDs. Replace the first3with38, so that the line beginstoken_ids = torch.tensor([[38, 14,. Run the script again. - Compare. Did the eight numbers change? Are they larger, now that we used a larger ID? Did any of the shapes change? Did any of the counts under
--- Summary ---change? - Explain it. In two or three sentences that your manager could understand, explain what we're using the token ID for here. And say if 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. Imagine if we assigned an ID number to every word. You'd learn nothing from that numbering system. "King" would be just as far away from "queen" as it is from "toaster". Instead of assigning numbers, this paper trained a very cheap prediction task so that words that appear in similar contexts would wind up with similar vectors to each other. It could do this at scale on billions of words. Embeddings begin here, which we cover in Chapter 5. Also beginning here is the vector search that powers many recommendation and retrieval systems today.
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