Linear algebra for LLMsPart 7: Decompositions and low rank
PCA on embeddings
6 min
The goal
You have embeddings in and want to see them on a screen. Principal component analysis finds the directions along which the points spread out the most, so projecting onto the top two loses as little as possible.
Write
Step 1: center
Stack the points as rows and subtract the mean of each column. These four points already have mean . Without centering, the top direction would just point at the mean.
Write
Step 2: the directions
The principal directions are the eigenvectors of (proportional to the covariance), which are the right singular vectors of . Their eigenvalues are and measure the spread along each direction.
Write
Step 3: project
The new coordinates of each point are its dot products with the principal directions: . Keep the first columns. PC1 ranges over , PC2 over .
Explained variance
The first direction captures 80% of the spread. For real embeddings, the top two components often capture only a small share of the variance, which is a reason to be careful about reading too much into a 2D plot.
Write
✏️ Your turn
Project a point
Write ’s two principal coordinates.
Work it out on paper, then go to the next card to check.
Answer
In practice
Xc = X - X.mean(dim=0)
U, S, Vh = torch.linalg.svd(Xc, full_matrices=False)
coords = Xc @ Vh[:2].T # (n, 2): the 2D plot
explained = S**2 / (S**2).sum()In a transformer
Transformer hidden states often have a few dimensions with very large values (“outlier” or “massive” activations). They can dominate the top principal components, so the plot shows those dimensions rather than meaning. Normalizing first, or dropping them, helps.
📌 Recap
PCA in one card
- Center the data, take the SVD, project: coordinates .
- Principal directions are eigenvectors of (right singular vectors).
- Explained variance: .
- Outlier dimensions can dominate; check before you interpret.
Write