What an N-gram is, how multi-head hashing compresses trillions of token combinations into a fixed lookup table, and why Zipfian word frequencies create hot-row collisions — each with a runnable demo. Optional: read it when a module points here.
1. What is an N-gram?
An N-gram is simply a contiguous window of \(N\) consecutive tokens (words or subword pieces) in a sequence:
1-gram (unigram): a single token — "cat"
2-gram (bigram): a pair of adjacent tokens — ("the", "cat"), ("cat", "sat")
3-gram (trigram): three adjacent tokens — ("the", "cat", "sat")
Before neural networks, language models worked by counting how often each N-gram appeared in a corpus and predicting the next word from the last \(N-1\) words. Modern LLMs don’t replace Transformers with N-grams — instead, some recent architectures attach a learned N-gram embedding table alongside the Transformer’s early layers. Why? Because a single token like "bank" is ambiguous, whereas the bigram ("river", "bank") or ("central", "bank") disambiguates it immediately via a cheap table lookup before attention even runs.
tokens = ["the", "river", "bank", "flooded", "after", "the", "storm"]unigrams = tokensbigrams = [tuple(tokens[i:i+2]) for i inrange(len(tokens) -1)]trigrams = [tuple(tokens[i:i+3]) for i inrange(len(tokens) -2)]print("Unigrams (1-grams):", unigrams)print("Bigrams (2-grams):", bigrams)print("Trigrams (3-grams):", trigrams)
2. The hashing trick: fitting \(V^N\) N-grams into \(R\) rows
A modern LLM vocabulary has \(V \approx 100{,}000\) tokens. Giving every possible bigram its own embedding row would require \(V^2 = 10^{10}\) rows; for trigrams, \(V^3 = 10^{15}\) rows — completely impossible in memory.
The fix is hashing. Pick a manageable table size \(R\) (say \(R = 100{,}000\) rows) and map any N-gram tuple to a row index \(j \in \{0, \dots, R-1\}\) with a deterministic hash function:
\[j = h(x_{t-1}, x_t) \bmod R.\]
Because \(V^2 \gg R\), two unrelated N-grams will occasionally land on the same row (hash collision). To make collisions harmless, real N-gram memory layers use \(H\) independent hash heads (e.g. \(H = 16\)): each head \(m \in \{1, \dots, H\}\) hashes the N-gram with a different salt into its own row \(j_m\), and the layer concatenates or sums all \(H\) retrieved vectors. Even if two N-grams collide in head 1, the probability they collide in all\(H\) heads at once is \((1/R)^H \approx 0\).
import torchdef hash_ngram(ngram_ids, head_id, num_rows):# Simple deterministic multiplicative hash per head h =2166136261^ (head_id *16777619)for tok in ngram_ids: h = ((h *16777619) ^ (tok +1315423911)) &0xFFFFFFFFreturn h % num_rows# Compare exact-match collision rate for 2,000 distinct bigrams in a small table (R = 500)# as we increase the number of independent hash heads H from 1 to 8.torch.manual_seed(0)R =500bigrams = [(int(a), int(b)) for a, b in torch.randint(0, 50000, (2000, 2))]for H in [1, 2, 4, 8]: signatures = [tuple(hash_ngram(bg, h, R) for h inrange(H)) for bg in bigrams] unique =len(set(signatures)) collided =len(bigrams) - uniqueprint(f"H = {H} hash head(s) | unique addresses: {unique:4d} / 2000 | exact collisions: {collided:4d}")
Look at the drop: with \(H = 1\) head in a small 500-row table, 1,509 of 2,000 bigrams collide. With \(H = 2\) independent heads, exact collisions drop to 37, and by \(H = 4\) they hit 0 — every bigram gets a unique multi-head fingerprint while the table stays tiny!
3. Sparse N-gram tables vs. dense fast-weight matrices
Now compare a dense fast-weight matrix\(\mathbf{S} \in \mathbb{R}^{d \times d}\) (from M1–M4) with a hashed N-gram memory table\(\mathbf{T} \in \mathbb{R}^{R \times d}\):
Discrete hash lookup \(\mathbf{T}[h(x_{t-1}, x_t)]\) (exact local token match)
Write footprint
Dense rank-1 outer product touches all entries of \(\mathbf{S}\)
Sparse write touches only the \(H\) hashed rows
Capacity wall
Saturates around rank \(d\) (linear superposition)
Scales with table rows \(R \gg d\) (far less cross-key interference)
Generalization
Similar query vectors \(\mathbf{q} \approx \mathbf{k}\) still retrieve
Zero fuzzy match: a different phrasing hashes to totally different rows!
That last row is the whole story of Delta N-gram (Wu, Oct 2026): - Writing into a sparse patch \(\mathbf{T} = \mathbf{T}^0 + \Delta\) avoids the dense \(d\times d\) rank ceiling cleanly and lets you retrofit a frozen LLM with a tiny 4.1M-parameter writer. - Two structural catches follow directly from discrete token hashing: 1. Zipfian hot rows: frequent structural bigrams like (":", "\n") or ("of", "the") appear thousands of times across every document. Every write touching them piles onto the exact same rows, causing massive relative drift (4.4–11.7× ||T^0||) on general prompts. 2. Exact-match addressing mismatch: if you write “Alice moved to Paris” and later ask “Where does Alice live?”, the question contains different local bigrams than the stored sentence — so the N-gram lookup never hits the updated rows!
# Mini demonstration of the two catches: exact-match addressing & Zipfian hot rowsdoc_tokens = ["alice", "moved", "to", "paris", "."]query_tokens = ["where", "does", "alice", "live", "?"]doc_bigrams =set(zip(doc_tokens[:-1], doc_tokens[1:]))query_bigrams =set(zip(query_tokens[:-1], query_tokens[1:]))overlap = doc_bigrams & query_bigramsprint("Stored doc bigrams :", sorted(doc_bigrams))print("Query bigrams :", sorted(query_bigrams))print("Shared bigrams :", overlap, " -> 0 exact hits! The query never reads the written rows.")
Stored doc bigrams : [('alice', 'moved'), ('moved', 'to'), ('paris', '.'), ('to', 'paris')]
Query bigrams : [('alice', 'live'), ('does', 'alice'), ('live', '?'), ('where', 'does')]
Shared bigrams : set() -> 0 exact hits! The query never reads the written rows.
That single print line explains why Delta N-gram improves exact continuation perplexity (where the same local N-grams recur) yet scores 0.44 F1 on zero-shot LoCoMo QA (where questions rephrase stored facts with different bigrams). Sparse discrete tables solve dense rank saturation, but trade away semantic fuzzy matching.