Primer — N-grams & hashed N-gram memory tables

Open In Colab

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 = tokens
bigrams  = [tuple(tokens[i:i+2]) for i in range(len(tokens) - 1)]
trigrams = [tuple(tokens[i:i+3]) for i in range(len(tokens) - 2)]

print("Unigrams (1-grams):", unigrams)
print("Bigrams  (2-grams):", bigrams)
print("Trigrams (3-grams):", trigrams)
Unigrams (1-grams): ['the', 'river', 'bank', 'flooded', 'after', 'the', 'storm']
Bigrams  (2-grams): [('the', 'river'), ('river', 'bank'), ('bank', 'flooded'), ('flooded', 'after'), ('after', 'the'), ('the', 'storm')]
Trigrams (3-grams): [('the', 'river', 'bank'), ('river', 'bank', 'flooded'), ('bank', 'flooded', 'after'), ('flooded', 'after', 'the'), ('after', 'the', 'storm')]

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 torch

def 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)) & 0xFFFFFFFF
    return 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 = 500
bigrams = [(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 in range(H)) for bg in bigrams]
    unique = len(set(signatures))
    collided = len(bigrams) - unique
    print(f"H = {H} hash head(s) | unique addresses: {unique:4d} / 2000 | exact collisions: {collided:4d}")
H = 1 hash head(s) | unique addresses:  491 / 2000 | exact collisions: 1509
H = 2 hash head(s) | unique addresses: 1963 / 2000 | exact collisions:   37
H = 4 hash head(s) | unique addresses: 2000 / 2000 | exact collisions:    0
H = 8 hash head(s) | unique addresses: 2000 / 2000 | exact collisions:    0

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}\):

Property Dense matrix \(\mathbf{S} \in \mathbb{R}^{d\times d}\) Hashed N-gram table \(\mathbf{T} \in \mathbb{R}^{R\times d}\)
Addressing Continuous dot product \(\mathbf{S}\mathbf{q}_t\) (semantic similarity) 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 rows
doc_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_bigrams

print("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.

Where these come back