Linear algebra for LLMsPart 1: Vectors and embedding space

Vectors and embeddings

6 min

A vector is a list of numbers

vv has 2 numbers, so it lives in 2 dimensions. We write v∈R2v \in \mathbb{R}^2: vv is a point in the 2-dimensional real space.

Write

v=[3,1]v = [3, 1], d=2d = 2.

The same vector is an arrow

v = [3, 1]

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

uu has 4 numbers, so u∈R4u \in \mathbb{R}^4. 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 d=768d = 768 and Llama 3 8B has d=4096d = 4096.

Write

A vector in Rd\mathbb{R}^d is a list of dd numbers.

The embedding table

A model gives every token in its vocabulary one vector, its embedding, stored as a row of the table EE. With VV tokens and width dd, EE has shape V×dV \times d. These toy numbers are small integers so you can copy them quickly.

Write

EE has shape V×dV \times d: one row per token.

Looking up a token

“cat” is token 1, so its embedding is row 1 of EE: [0,3,−1,2][0, 3, -1, 2]. 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 XX, one row per token: shape T×dT \times d. This is the matrix every later layer works on.

Write

“the cat sat” → ids [0, 1, 2] → XX = E[ids], shape 3×43 \times 4.

✏️ Your turn

Embed “on the mat”

The token ids are [3, 0, 4]. Write XX and its shape.

Work it out on paper, then go to the next card to check.

Answer: XX for “on the mat”

Rows 3, 0 and 4 of EE, 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 V=50,257V = 50{,}257 and d=768d = 768, so its table holds 50,257×768=38,597,37650{,}257 \times 768 = 38{,}597{,}376 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 EE.

📌 Recap

Vectors and embeddings in one card

  • A vector in Rd\mathbb{R}^d is a list of dd numbers: an arrow, or a point.
  • The embedding table EE is V×dV \times d: one row per token.
  • Embedding a token = picking its row. A sequence of TT tokens becomes XX, shape T×dT \times d.

Write

The three lines above.