Introduction
A conditional memory stores local co-occurrence statistics in a sparse table addressed from token ids, leaving dense weights to model longer-range interactions. The design must choose a key, collision policy, fusion site, and update rule under fixed table and compute budgets. Scalable conditional lookup motivates this separation [1], while over-tokenization explores a related way to buy extra local capacity [2].
We choose a deliberately simple two-table design. The hashed table handles every context; an exact table removes collisions for the most frequent contexts supplied by the corpus statistics.
Method
Keying
Let be the token at position and the vocabulary size. For later positions, the hashed address is
The first position uses the reserved row. Frequent bigrams are packed as , sorted, and located by binary search; row zero is the miss row.
def _bigram_hash(self, idx):
mod = self.bigram_vocab_size - 1
x = idx.to(torch.int32)
out = torch.zeros_like(x)
out[:, 0] = mod
out[:, 1:] = torch.bitwise_xor(36313 * x[:, 1:], 27191 * x[:, :-1]) % mod
return out.long()
def tables(self):
return [self.bigram_embed.weight, self.exact_embed.weight]
def addresses(self, idx):
if self.exact_k:
previous = torch.zeros_like(idx)
previous[:, 1:] = idx[:, :-1]
packed = previous * 50304 + idx
slot = torch.searchsorted(self.exact_keys, packed)
found = slot.clamp_max(self.exact_k - 1)
hit = (slot < self.exact_k) & (self.exact_keys[found] == packed)
hit[:, 0] = False
exact = torch.where(hit, found + 1, torch.zeros_like(found))
else:
hit = torch.zeros_like(idx, dtype=torch.bool)
exact = torch.zeros_like(idx)
self._exact_hit = hit
return [self._bigram_hash(idx), exact]class ConditionalMemory(nn.Module):
"""Hashed bigram memory with exact frequent-context corrections."""
def __init__(self, config):
super().__init__()
self.n_embd = config.n_embd
self.n_layer = config.n_layer
self.vocab_size = config.vocab_size
self.bigram_vocab_size = config.vocab_size * 5
self.bigram_embed = nn.Embedding(self.bigram_vocab_size, config.n_embd)
remaining = 211013189 - self.bigram_vocab_size * config.n_embd - 2 * config.n_layer
self.exact_capacity = (remaining - config.n_embd) // (config.n_embd + 1)
self.exact_embed = nn.Embedding(self.exact_capacity + 1, config.n_embd)
self.bigram_lambdas = nn.Parameter(torch.full((config.n_layer,), 0.1))
self.exact_lambdas = nn.Parameter(torch.full((config.n_layer,), 0.1))
stats = config.ngram_stats
if stats is None or 2 not in stats:
self.exact_k = 0
keys = torch.empty(0, dtype=torch.long)
else:
self.exact_k = min(self.exact_capacity, stats[2][0].shape[0])
grams = stats[2][0][:self.exact_k].long()
keys = (grams[:, 0] * 50304 + grams[:, 1]).sort().values
self.register_buffer("exact_keys", keys, persistent=False)Sharing and fusion
There is one hashed row and at most one exact row per position, shared by every block. The exact row is masked out on a miss. The two rows are combined with separate learned scalar gates and returned as a residual injection before each block. The fusion depends only on token ids; the running hidden state is not used to gate it.
def _memory(self, layer_idx, rows):
mask = self._exact_hit.to(rows[1].dtype).unsqueeze(-1)
return self.bigram_lambdas[layer_idx] * rows[0] \
+ self.exact_lambdas[layer_idx] * rows[1] * mask
def fuse(self, layer_idx, h, idx, rows):
return self._memory(layer_idx, rows)
def init_weights(self):
nn.init.zeros_(self.bigram_embed.weight)
nn.init.zeros_(self.exact_embed.weight)
nn.init.constant_(self.bigram_lambdas, 0.1)
nn.init.constant_(self.exact_lambdas, 0.1)
def optim_groups(self):
return [{"params": [self.bigram_embed.weight, self.exact_embed.weight], "lr_mult": 75.0,
"weight_decay": 0.1 * 5.0 / 150.0, "betas": (0.75, 0.95)},
{"params": [self.bigram_lambdas, self.exact_lambdas], "lr_mult": 5.0,
"weight_decay": 0.0, "betas": (0.9, 0.99)}]The hashed table is allocated first, and the exact table receives the remaining state budget. If corpus statistics are absent, the exact path is disabled and only the hashed contribution remains.
Results
| Method | ① | ② | ③ |
|---|---|---|---|
| Held-out loss or perplexity ↓ | Held-out loss or perplexity ↓ | Held-out loss or perplexity ↓ | |
| No added memory | 3.976 | 83.95 | 65.85 |
| OverEncoding | 3.947 | 84.12 | 64.87 |
| Bigram hash | 3.845 | 74.08 | 60.72 |
| Engram | 3.834 | 70.40 | 60.60 |
| Bigram hash, 0-init | 3.847 | 74.06 | 61.04 |
| Pietrzak | 3.782 | 68.33 | 57.44 |
| Over-Tokenized Transformer | 3.905 | 78.65 | 62.72 |
| Qwen3.8-Flash-Next n-gram | 3.874 | 74.99 | 61.26 |
| DeepSeek-V4.1 | 3.855 | 73.70 | 60.32 |
- ① held-out FineWeb validation loss
- ② WikiText-2 perplexity
- ③ LAMBADA perplexity
The run's per-setting means are unavailable, so we make no claim for its method. The published baselines are shown above. Lower is better; the strongest published reference is N-gram+Adam lr1.2e-3 on FineWeb at 3.671, N-gram+Adam lr1.2e-3 on WikiText-2 at 59.00, and N-gram+Adam lr1.2e-3 on LAMBADA at 54.07.
How we got here
The code supports only the final account: a hashed bigram table covers all positions, exact rows correct frequent contexts, and the state budget determines the split. It also records the fallback to a hashed contribution alone when corpus statistics are unavailable. We cannot say which alternatives or measurements led to these choices.
Limitations
- The active key is only a bigram, so longer context must remain in the dense backbone.
- Hash collisions remain for contexts without an exact-key hit, and the hash constants are fixed in code.
- The residual injection is token-only and cannot suppress a misleading row using the hidden state.
- The first position shares one reserved hashed row and never receives an exact correction.
References
- Xin Cheng, Rui Tian, Wangding Zeng et al. (2026). Conditional Memory via Scalable Lookup: A New Axis of Sparsity for Large Language Models.
- Hongzhi Huang, Defa Zhu, Banggu Wu et al. (2025). Over-Tokenized Transformer: Vocabulary is Generally Worth Scaling. ICML.
- Zihan Qiu, Zekun Wang, Xiao Li et al. (2026). On the Design of Qwen3.8-Next Architecture: Evaluation, Efficiency, and Training Stability.
- DeepSeek-AI, Anyi Xu, B. Li et al. (2026). DeepSeek-V4.1-Flash: Pushing the Limits of KV Cache Compression.