Training it: centroid loss and zero init
Why the ids get no gradient, how the auxiliary centroid loss trains the codebook, what dead centroids are, and why a fresh layer is a no-op.
The ids can't be trained by backprop
argmin returns an integer. Nudge a centroid a little and the id usually doesn't change at all, so there is no useful gradient through it. The language-model loss can train the bigram table and the projection (they are on the path to the output), but not the centroids.
So the layer adds its own small loss that pulls each chosen centroid toward the slices that chose it:
h is detached, so this loss only moves the centroids - it never drags the model's hidden states toward the codebook. It is k-means, done with gradient descent.
Watch the centroids learn
Ninety 2D points in three groups, four centroids. Press train and watch the loss fall.
- centroid 030 pts
- centroid 130 pts
- centroid 230 pts
- centroid 30 pts
Quick check
Which parameters does the centroid loss update?
Dead centroids
A centroid that is never the nearest one for any slice gets no gradient, so it never moves, so it is never chosen. Its rows in the bigram table never train either. In the demo, centroid 3 is dead from the start.
EMA k-means implementations commonly fight this by re-seeding unused centroids from recent data. The Yumon version documents that it does not re-seed yet - worth knowing if you train one: count how many ids are actually used per head.
A fresh layer does nothing - on purpose
The output projection starts at zero (nn.init.zeros_(self.out.weight)), so on step 0, out(emb) = 0 and the layer returns x unchanged. A model with the layer starts as the exact same function as one without it, which makes A/B runs fair and keeps early training stable. The projection grows only as fast as the bigram memory proves useful.
Slide the projection scale up from zero and watch |y − x| appear:
Quick check
What does a freshly initialized layer return?
One more thing: generation
When generating one token at a time with a KV cache, the new token still needs its previous id. The Hyperfield port of Yumon stores each N-Grammer layer's last-position ids in the cache next to the keys and values, so a cached step pairs the new id with them instead of with the start id K. Cached logits equal the full forward pass exactly.
- Split, normalize, snap: a vector becomes H small ids.
- Pair each id with the previous one: an exact row in one table.
- Look up, normalize, project, add - shape in equals shape out.
- Centroids learn from their own loss; the projection starts at zero.
Last check
During cached generation, what extra state does an N-Grammer layer need?