Linear algebra for LLMsPart 1: Vectors and embedding space
Add, scale, combine
6 min
Adding vectors
Add entry by entry: first with first (), second with second (). Both vectors must have the same length.
Write
Adding is putting arrows tip to tail
Draw , then draw starting where ends. goes from the start of to the end of : the point .
Scaling a vector
Multiplying by a number scales every entry: is twice as long, points the opposite way, is half as long. The direction only changes when the number is negative.
Write
A linear combination
Scale some vectors, then add them up: that’s a linear combination. Almost everything in this course is one: a matrix times a vector, attention’s weighted average, the residual stream.
Write
Every vector is a combination of the axes
and are the standard basis: one 1, the rest 0. A vector’s entries are exactly how much of each basis vector it contains.
✏️ Your turn
Combine these
Write the result.
Work it out on paper, then go to the next card to check.
Answer
Scale first (3 times each entry, 2 times each entry), then subtract entry by entry.
The residual stream is a running sum
In a transformer
Each layer of a transformer reads the current vector , computes something, and adds it back: . The final vector is the embedding plus every layer’s contribution. This sum is called the residual stream (Part 6).
Write
Averaging vectors
The mean adds the rows and divides by how many there are: . Many sentence-embedding models get one vector for a whole text this way, called mean pooling.
Write
In PyTorch
a + b # elementwise sum (shapes must match, or broadcast)
2 * a # scale every entry
2 * a - b # a linear combination
X.mean(dim=0) # average the rows of X: (T, d) → (d,)dim=0 means “collapse axis 0”, the rows. Part 4 covers axes properly.
📌 Recap
Add, scale, combine in one card
- adds entry by entry; as arrows, tip to tail.
- scales every entry; a negative flips the direction.
- A linear combination is : scale, then add.
- The residual stream: , a running sum of every layer’s output.
- Mean pooling: .
Write