Linear algebra for LLMsPart 1: Vectors and embedding space
Norms and cosine similarity
7 min
The length of a vector
Pythagoras: square the entries, add, take the square root. This is the norm, written or .
Write
Same rule in any dimension
A neat way to remember it: . The length squared is the vector dotted with itself.
Write
The norm
adds the sizes of the entries: the distance walking along the grid instead of in a straight line. It shows up in regularization and sparsity; “norm” on its own almost always means .
Write
Unit vectors
Divide a vector by its length and you get a unit vector: the same direction, length 1. Check: . This is called normalizing.
Write
✏️ Your turn
Normalize this
Write , then .
Work it out on paper, then go to the next card to check.
Answer
Every entry divided by 3. The direction didn’t change; only the length did.
Cosine similarity
Rearrange and you get the cosine: how aligned two vectors are, from (opposite) through (orthogonal) to (same direction), whatever their lengths.
Write
A dot product is not a cosine
| Key | ||
|---|---|---|
| 5 | 0.707 | |
| 1 | 0.995 |
With , the dot product prefers because it’s long. Cosine similarity prefers because it points almost exactly along . Which one you want depends on whether length should count.
Write
Unit vectors make them the same
In a transformer
Search with embeddings ranks documents by cosine similarity. Normalize every vector once and a plain dot product gives the cosine, which is what vector databases compute fast. Many embedding APIs return unit-length vectors already (OpenAI’s do).
Write
In PyTorch
torch.linalg.vector_norm(a) # |a|, the L2 norm
torch.linalg.vector_norm(a, ord=1) # the L1 norm
F.normalize(a, dim=-1) # a / |a|, along the last axis
F.cosine_similarity(a, b, dim=-1) # a·b / (|a| |b|)F is torch.nn.functional.
📌 Recap
Norms and cosine similarity in one card
- , and . : .
- is a unit vector: same direction, length 1.
- , from to , ignoring length.
- For unit vectors, .
Write