Snapping to centroids: product quantization
Split a vector into heads, RMS-normalize each slice, and pick the nearest centroid with the |c|² − 2h·c distance trick.
Many small codes instead of one big one
One codebook for a whole 256-wide vector would need an enormous number of centroids to tell vectors apart. Product quantization splits the vector into H heads of dh = w / H numbers and gives each head its own small codebook of K centroids.
A vector becomes H ids, one per head. That is KH possible combinations (25616 for Yumon) from only H·K centroids. Each head then gets its own bigram, so the layer reads H rows per token.
Quick check
Width w = 512 and H = 8 heads. How many numbers are in each head's slice?
Normalize first
Before snapping, each slice is RMS-normalized:
The distance trick
The id is the nearest centroid by squared distance. Expand it:
For one slice h, the |h|² term is the same for every centroid, so it can't change which one wins. Drop it:
That is exactly what the code computes: c.pow(2).sum(-1) - 2 * h @ c.transpose(1, 2), then argmin.
Try it in 2D
Real heads have 16 dimensions, but the geometry is the same in two. Drag the point and the centroids, and compare the two distance columns.
| id | |h − c|² | |c|² − 2 h·c |
|---|---|---|
| 0 ← id | 0.168 | -1.832 |
| 1 | 1.838 | -0.162 |
| 2 | 3.988 | 1.988 |
| 3 | 8.333 | 6.333 |
| 4 | 2.241 | 0.241 |
The two columns differ by exactly |h|² = 2.000 on every row, so they always pick the same winner. The second column never needs |h|², and for all centroids at once it is one matrix multiply.
Quick check
When finding the nearest centroid, which term can safely be dropped?
Quick check
You multiply x by 3 before the layer. Do its cluster ids change?