Linear algebra for LLMsPart 1: Vectors and embedding space
High dimensions
6 min
In 2D, a random angle can be anything
Pick two random directions in the plane and the angle between them is anywhere from 0° to 180°. Their cosine is often close to or . In thousands of dimensions, something very different happens.
In high dimensions, random vectors are nearly orthogonal
| typical of two random vectors | |
|---|---|
| 2 | |
| 64 | |
| 768 | |
| 4,096 |
The cosine of two random directions has an average of and a spread (standard deviation) of . At two random embeddings are almost exactly at 90°.
Write
Why: the products cancel
Each product is as likely to be negative as positive, so most of them cancel. What’s left grows only like , while the lengths and each grow like too. Divide and you get about .
The size of a random dot product
A sum of independent terms, each with variance 1, has variance . Its typical size, the standard deviation, is : 8 for , about 11.3 for .
Write
✏️ Your turn
How big?
Query and key entries are random with mean 0 and variance 1. Roughly how big is a typical ?
Work it out on paper, then go to the next card to check.
Answer: about 10
Scores of are a problem, as the next card shows.
Big scores make softmax pick one winner
Softmax (Part 5) turns scores into weights that sum to 1. With scores around , almost all the weight lands on one key, and the gradients for the others nearly vanish. Divided by 10, the same scores give a useful spread.
In a transformer
This is why attention computes : dividing by brings random scores back to a typical size of about 1, whatever the head width.
Write
Room for many more directions than dimensions
| Directions at… | How many fit in |
|---|---|
| exactly 90° | at most |
| nearly 90° | exponentially many in |
has room for only directions at exactly 90° to each other. But if “nearly 90°” is enough (say for every pair), the number of directions you can fit grows exponentially with .
In a transformer
One explanation of how models store more concepts than they have dimensions, called superposition, relies on this: features get nearly orthogonal directions, so they interfere only a little (Anthropic, Toy Models of Superposition, 2022).
Try it in PyTorch
a, b = torch.randn(2, 4096) # two random vectors, entries ~ N(0, 1)
F.cosine_similarity(a, b, dim=0) # typically within ±0.03
(a @ b) / 4096 ** 0.5 # typically between −2 and 2Run it a few times: the cosine hugs 0, and the scaled dot product behaves like a draw from .
📌 Recap
High dimensions in one card
- Two random vectors in are nearly orthogonal: .
- With unit-variance entries, has variance and typical size .
- Big scores make softmax put nearly all the weight on one key, so attention divides by .
- Exactly orthogonal: directions. Nearly orthogonal: exponentially many.
Write