Skip to content
INDIE / MACHINE
MATHLESSON 3 OF 67 MIN

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.

STEP 1 / 7QUIZ 0 / 3
01 /

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.

dh = w / H = 256 / 16 = 16
Yumon cp1: w = 256, H = 16, so each head is a 16-number slice with its own 256 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.

02 / CHECK YOURSELF

Quick check

Width w = 512 and H = 8 heads. How many numbers are in each head's slice?

03 /

Normalize first

Before snapping, each slice is RMS-normalized:

ĥ = h / √(mean(h²) + ε)
ε = 1e-6 keeps the division safe for an all-zero slice.
INTERACTIVE / RMS NORM
rms = √(mean(h²)) = 0.755
RAW h
1.20
-0.40
0.80
0.20
h / rms(h)
1.59
-0.53
1.06
0.26
RMSNorm divides a vector by the square root of its mean square. Scale the raw vector up or down: the normalized bars do not move. That is why the cluster id depends on a slice's direction, not its size.
04 /

The distance trick

The id is the nearest centroid by squared distance. Expand it:

|h − c|² = |h|² − 2 h·c + |c|²

For one slice h, the |h|² term is the same for every centroid, so it can't change which one wins. Drop it:

id = argmin_c ( |c|² − 2 h·c )
−2h·c for all centroids at once is a single matrix multiply: h @ cᵀ.

That is exactly what the code computes: c.pow(2).sum(-1) - 2 * h @ c.transpose(1, 2), then argmin.

05 /

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.

INTERACTIVE / NEAREST CENTROID
01234
id|h − c|²|c|² − 2 h·c
0 ← id0.168-1.832
11.838-0.162
23.9881.988
38.3336.333
42.2410.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.

Drag the white point (one head's slice of the residual) or any centroid. The id is the region the point lands in. With normalization on, the point is first pulled onto the unit-RMS circle, so only its direction matters.
06 / CHECK YOURSELF

Quick check

When finding the nearest centroid, which term can safely be dropped?

07 / CHECK YOURSELF

Quick check

You multiply x by 3 before the layer. Do its cluster ids change?

LESSON 3 COMPLETE

Up next: Bigram ids and the embedding table