Sub topic 4
Embeddings: representing tokens as vectors
This chapter assumes you can read basic Python, multiply matrices, and recall that tokenization turns text into integer token IDs. It covers how those IDs become vectors the network can compute with.
Why IDs are not enough
A token ID such as 4821 is just a label. Its size says nothing about meaning, and 4821 is not "close to" 4822 in any useful way. A neural network does arithmetic on real numbers, so it needs a representation where distance and direction can carry meaning.
An embedding is a vector of real numbers assigned to a token. The model stores one vector per vocabulary entry, and looking up a token means fetching its vector.
The embedding matrix
All the vectors live in one matrix E with shape (vocab_size, d_model). Row i is the vector for token ID i. The width d_model is the model dimension, often between a few hundred and several thousand.
Looking up a token is the same as multiplying a one-hot vector by E. In practice, frameworks skip the multiplication and index the row directly, which is much faster.
import numpy as np
vocab_size, d_model = 6, 4
rng = np.random.default_rng(0)
E = rng.normal(size=(vocab_size, d_model))
token_ids = np.array([2, 5, 2])
x = E[token_ids] # shape (3, 4)
print(x.shape)
# Same result using a one-hot matrix product
one_hot = np.eye(vocab_size)[token_ids]
print(np.allclose(x, one_hot @ E))The output is (3, 4) followed by True. A sequence of three token IDs becomes a (3, 4) matrix, one row per position. Token ID 2 appears twice and gets the same row both times. Context is not yet mixed in, which is the job of self-attention in the next chapter.
Where the values come from
The rows of E start as small random numbers. They are parameters, like any other weight in the network, so training adjusts them by gradient descent. Tokens that behave similarly in text, meaning they appear in similar contexts, end up with similar vectors.
Similarity is usually measured with cosine similarity, the cosine of the angle between two vectors.
def cosine(a, b):
return a @ b / (np.linalg.norm(a) * np.linalg.norm(b))
print(round(cosine(E[2], E[5]), 3))With the random matrix above, the value is arbitrary. After training, vectors for related tokens such as "cat" and "dog" score noticeably higher than unrelated pairs.
Common errors and gotchas
- Treating embeddings as word meanings. A row of
Erepresents a token, not a word. A rare word split into several subword tokens gets several vectors. - Expecting context sensitivity at this stage. The input embedding for "bank" is identical in "river bank" and "bank loan". Later layers produce context-dependent vectors.
- Shape mix-ups.
Eis(vocab_size, d_model). Indexing it with a list of lengthngives(n, d_model). Using token IDs outside0tovocab_size - 1raises anIndexError, usually from a tokenizer and model that do not match. - Forgetting order. Looking up rows gives no information about position. Position must be added separately, which the positional information chapter covers.
Exercise
Exercise
An embedding matrix has 50,000 rows and 768 columns. How many parameters does it hold, and what shape is the result of looking up a sequence of 10 token IDs?
Show answer
It holds 50,000 × 768 = 38,400,000 parameters. Looking up 10 token IDs gives a matrix of shape (10, 768), one 768-dimensional vector per position.
Exercise
The same token appears at positions 1 and 7 of a sequence. Are its embedding vectors different at the lookup step? Why or why not?
Show answer
No. The lookup depends only on the token ID, so both positions get the same row of the embedding matrix. Position information has to be added separately, and context is mixed in by later layers.