Hashing n-grams into tables
The multiplicative-XOR hash, why each head's table has a prime size, why several heads, and how big the tables get.
Too many n-grams for an exact table
N-Grammer could afford an exact table because it paired a few hundred cluster ids. Engram keys on real tokens. With about 98,600 compressed ids:
So Engram hashes. Every n-gram gets squeezed into a fixed table of M rows. Two different n-grams can land on the same row - a collision - and the design is about making collisions rare and survivable.
The hash
Each layer draws one odd 64-bit multiplier per position in the window. For the n-gram ending at token t:
The bigram and trigram at a position share the first two terms of the XOR: the trigram is the bigram's mix XOR one more product, which is why the code builds them in one loop.
Watch it collide
Real tables have about 646,000 rows per head. These have 31 to 43, so collisions show up in a single sentence.
No two different n-grams here collide in both heads.
Why several heads, why primes
Each order has K heads (8 in the paper and the demo), and each head has its own table with a different prime number of rows. The demo picks them by walking up from the target size and skipping any prime already taken, across both orders and every Engram layer.
A row of one head can be shared by several n-grams, but the memory vector concatenates all heads, so two n-grams only read identical memory if they collide in every head at once. If the heads behaved like independent uniform hashes, two given n-grams would share all K rows with probability 1 / (p₁·p₂·…·p_K). Different moduli are what keep the heads from colliding on the same pairs: with equal table sizes, two mixes that differ by a multiple of p would collide in every head together.
Quick check
Bigram ids (3, 5), multipliers m₀ = 2, m₁ = 7, head prime 11. Which row? (current token 5, previous 3)
How big are the tables?
The demo config: 2 orders × 8 heads, each table a prime just above 5 × 129,280 = 646,400 rows, each row 512 / 8 = 64 numbers. Hyperfield's prime search gives the same sizes as the demo's:
| DEMO LAYER | SMALLEST / LARGEST PRIME | ROWS | PARAMETERS (×64) |
|---|---|---|---|
| 1 | 646,403 / 646,619 | 10,344,164 | 662,026,496 |
| 15 | 646,631 / 646,879 | 10,348,242 | 662,287,488 |
Each token reads 16 rows of 64 numbers per layer - 1,024 values out of 662 million. That ratio is the whole pitch: parameters that cost memory, but almost no compute.
Quick check
Two different trigrams collide in head 0 but not in head 1. What does the layer read for them?