Linear algebra for LLMsPart 1: Vectors and embedding space
Vectors and embeddings
6 min
A vector is a list of numbers
has 2 numbers, so it lives in 2 dimensions. We write : is a point in the 2-dimensional real space.
Write
The same vector is an arrow
Start at the origin, go 3 along the first axis and 1 along the second. The arrow and its tip, the point (3, 1), are two pictures of the same vector.
More numbers, more dimensions
has 4 numbers, so . You can’t draw 4 axes, but every rule in this course works the same way in any number of dimensions. Real models use hundreds or thousands: GPT-2 small has and Llama 3 8B has .
Write
The embedding table
A model gives every token in its vocabulary one vector, its embedding, stored as a row of the table . With tokens and width , has shape . These toy numbers are small integers so you can copy them quickly.
Write
Looking up a token
“cat” is token 1, so its embedding is row 1 of : . A lookup is just picking a row. In code, E[1].
A sentence becomes a matrix
“the cat sat” is the token ids [0, 1, 2]. Stack their rows and you have , one row per token: shape . This is the matrix every later layer works on.
Write
E[ids], shape .✏️ Your turn
Embed “on the mat”
The token ids are [3, 0, 4]. Write and its shape.
Work it out on paper, then go to the next card to check.
Answer: for “on the mat”
Rows 3, 0 and 4 of , in the order of the tokens. Order matters: the same tokens in another order give the same rows in another order.
Embeddings in PyTorch
emb = torch.nn.Embedding(num_embeddings=V, embedding_dim=d)
emb.weight.shape # (V, d): the table E
X = emb(ids) # ids of shape (T,) → X of shape (T, d)In a transformer
GPT-2 small has and , so its table holds numbers: almost a third of the model’s 124 million parameters. In Part 5 you’ll see that a lookup is also a matrix product: a one-hot row vector times .
📌 Recap
Vectors and embeddings in one card
- A vector in is a list of numbers: an arrow, or a point.
- The embedding table is : one row per token.
- Embedding a token = picking its row. A sequence of tokens becomes , shape .
Write