Introduction
A conditional memory gives a language model a large, sparsely read table whose rows are selected from the local token context, typically an n-gram ending at the current position. Because the address is a function of token ids alone, every lookup is known before the forward pass runs, and the table can sit in host memory and be prefetched. The hope is that surface co-occurrence statistics, such as which token tends to follow which, are stored in that table instead of being forced into the dense weights. Engram makes this a separate axis of sparsity next to mixture-of-experts [1]. Over-tokenized transformers scale the input vocabulary with hashed n-gram embeddings [2]. Recent production architectures carry n-gram embeddings or Engram-style memories of their own [3, 4].
The question in this task is how to design such a memory under a fixed memory budget: what it is keyed on, how entries are shared, where and how the retrieved rows enter the network, and how the table is trained. The backbone, the training recipe and the budgets on state, compute and gathered elements are all fixed.
The difficulty is in the statistics of the keys. Bigram frequencies are heavy-tailed. There are far more distinct bigrams than any affordable table has rows, so almost every design hashes keys into rows, and a hashed row is then a superposition of every key that lands on it. That superposition hurts in two different ways at the two ends of the frequency spectrum:
- At the head, a few very frequent bigrams carry a large share of the tokens. When two of them collide, the shared row has to serve two strong, incompatible signals, and the error is paid on a large fraction of positions.
- In the tail, a rare bigram is seen a handful of times in training. A hashed row for it is dominated by whatever more frequent keys share it, so what it returns at a rare position is mostly noise from unrelated contexts.
Multiple hash heads, gates and projections reduce the damage but keep the superposition. We asked whether the address computation itself can do what classical n-gram smoothing does: give the well-estimated keys their own parameters, and send the poorly estimated ones to a coarser but well-estimated distribution.
Method
Our memory, which we call Backoff Memory, has a single table in the residual-stream width , read once per position and shared by all layers.
"""Hierarchical conditional memory with frequency-exact addressing and unigram backoff.
KEYING -- bigrams. The K most frequent corpus bigrams are addressed EXACTLY: their sorted
keys live in a buffer and the slot is found by binary search, so the keys that
carry most of the probability mass have ZERO hash collisions. A rare bigram
BACKS OFF to its unigram (the current token): the tail holds exactly one row per
vocabulary item, so the backoff table is itself an exact, well-estimated unigram
table rather than a collision blur.
SHARING -- one row per key, shared across all layers. The unigram backoff row is shared by
every context ending in that token (hierarchical / Kneser-Ney-style smoothing).
FUSION -- the retrieved row is added to the residual stream at every block with a learned
per-layer scale. No projection: the table lives directly in the residual
coordinate frame (a learned rotation misaligns the diagonal Adam preconditioner).
TRAINING-- zero-init table; a high-LR AdamW group (sparsely-touched rows need large steps).
"""Two-level addressing
Let be the token at position , the vocabulary size, and the integer key of the bigram ending at . The task supplies corpus counts of the most frequent bigrams of the training data. We take the most frequent, sort their keys , and store them in a buffer . The address read at position is
with . The head lookup is a binary search (torch.searchsorted) followed by an
equality test, so a head bigram always lands on its own row and nothing else lands there. The tail
does not hash the bigram at all: it addresses the current token directly, and the last rows
before the sequence-start row form an exact unigram table. Every address is collision-free.
Information is still lost, but deliberately: a rare bigram is replaced by its unigram rather than mixed
with arbitrary other bigrams.
def addresses(self, idx):
x = idx.to(torch.int64)
prev = torch.zeros_like(x)
prev[:, 1:] = x[:, :-1]
key = x * self.V + prev
if self.K > 0:
pos = torch.searchsorted(self.hh_keys, key)
posc = pos.clamp(max=self.K - 1)
hit = (pos < self.K) & (self.hh_keys[posc] == key)
else:
hit = torch.zeros_like(x, dtype=torch.bool)
# Unigram backoff: exactly one tail row per vocabulary item, addressed directly.
tail = self.K + x
addr = torch.where(hit, posc, tail) if self.K > 0 else tail
addr = addr.clone()
addr[:, 0] = self.R - 1
return [addr]Why the backoff row is a continuation estimate
The gradient a row receives determines what it learns. A head row is updated only at positions where the exact bigram occurs, so it is an uncontaminated per-bigram estimate. The backoff row is updated only at positions where follows a context that is not in the head, never where is a frequent bigram, because those positions read the head row instead. It therefore learns what to add to the residual stream when appears after an unusual predecessor, not the average over all of 's occurrences. That is the idea behind Kneser-Ney backoff, where the lower-order distribution is fitted to novel continuations rather than to raw frequency. Here it comes out of the addressing, with no counts or discounts in the forward pass.
Filling the budget exactly
The state budget counts the table, the key buffer and any other parameter. With per-layer scales and the table sized as , the constraint gives
with and a margin of elements. The head therefore receives every row the budget allows once the unigram backoff and the sequence-start row have their rows. The buffer of keys always has entries, padded with when no corpus counts are available. A checkpoint therefore restores with the same shapes either way, and the memory degrades to a pure unigram table rather than failing.
self.V = config.vocab_size
D = config.n_embd
# Fill the state budget: table R*D + hh_keys K + lambdas, with the tail holding exactly
# one row per vocabulary item (R = K + V + 1, the last row is the sequence-start row).
R = (211_013_189 + 1 + self.V - config.n_layer - 50_000) // (D + 1)
K = R - self.V - 1
self.K = max(0, min(K, 1_000_000, R - 2))
self.R = self.V + 1 + self.K
self.bigram_embed = nn.Embedding(self.R, D)
self.bigram_lambdas = nn.Parameter(torch.full((config.n_layer,), 0.1))
stats = config.ngram_stats
# hh_keys is ALWAYS K rows (config-determined shape) so the checkpoint restores cleanly
# whether or not the corpus counts are available at construction time.
if stats is not None and 2 in stats and self.K > 0:
g = stats[2][0][:self.K]
keys = g[:, 1].to(torch.int64) * self.V + g[:, 0].to(torch.int64)
keys = torch.sort(keys).values
if len(keys) < self.K:
keys = torch.cat([keys, torch.full((self.K - len(keys),), -1, dtype=torch.long)])
else:
keys = torch.full((self.K,), -1, dtype=torch.long)
self.register_buffer('hh_keys', keys)
self.tail_mod = max(1, self.R - 1 - self.K)Fusion and training
The retrieved row enters the residual stream before every block, scaled by a learned scalar per layer:
There is no projection between the table and the residual stream. The table lives directly in the residual coordinate frame. Our reason is that Adam's preconditioner is diagonal and therefore not rotation-equivariant: a learned rotation between the table and the stream makes the table's per-coordinate second moments refer to directions that are not the stream's coordinates. We measured the cost of a projection directly (Section 4).
The table is initialised to zero, so the model starts as the dense backbone, and the scales start at . The training recipe is the one used by the hashed-bigram baseline from modded-nanogpt and was not changed: an AdamW group for the table at 75 times the scheduled learning rate with and weight decay , and a second group for the scales at 5 times the learning rate with no decay. Rarely touched rows need large steps to move at all.
def init_weights(self):
nn.init.zeros_(self.bigram_embed.weight)
nn.init.constant_(self.bigram_lambdas, 0.1)
def fuse(self, layer_idx, h, idx, rows):
if layer_idx >= self.n_layer:
return None
return self.bigram_lambdas[layer_idx] * rows[0]
def optim_groups(self):
return [{"params": [self.bigram_embed.weight], "lr_mult": 75.0,
"weight_decay": 0.1 * 5.0 / 150.0, "betas": (0.75, 0.95)},
{"params": [self.bigram_lambdas], "lr_mult": 5.0,
"weight_decay": 0.0, "betas": (0.9, 0.99)}]Each position gathers exactly one row of width . The address computation is one binary search per position. The hooks never look at the hidden state, so the memory is entirely prefetchable.
Results
| Method | ① | ② | ③ |
|---|---|---|---|
| Held-out loss or perplexity ↓ | Held-out loss or perplexity ↓ | Held-out loss or perplexity ↓ | |
| Qwen4-Max | 3.786 | 68.14 | 58.43 |
| 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
Backoff Memory improves on the dense backbone on every setting: 3.786 against 3.976 on FineWeb, 68.14 against 83.95 on WikiText-2 and 58.43 against 65.85 on LAMBADA. Its closest relative among the baselines is the hashed bigram table, which has the same fusion and the same optimiser groups and differs in the addressing and in having fewer rows (ours fills the state budget). Against it we are better on all three settings: 3.845, 74.08 and 60.72. We are also ahead of Engram (3.834, 70.40, 60.60), of its DeepSeek-V4.1-Flash variant, of the Qwen n-gram embedding and of both over-tokenization baselines on every setting.
The baselines we do not beat everywhere are the n-gram table trained with row-sparse Adam and the same table at a learning rate of 1.2e-3, which is ahead of us on every setting. On WikiText-2 we are ahead of every other baseline, at 68.14 against 68.33 for the n-gram table. On FineWeb we are just behind the n-gram table, at 3.786 against 3.782. On LAMBADA we are behind it, at 58.43 against 57.44. Changing the addressing and filling the budget, while keeping the hashed-bigram recipe, closes most of the gap between the hashed bigram table and the n-gram table with row-sparse Adam. On WikiText-2 it closes all of it. On LAMBADA it does not.
How we got here
Before writing a memory of our own, we analysed the task's corpus counts. The coverage curve of the most frequent bigrams showed that a head of moderate size already covers most token positions. In our development runs, a head of 150,000 exact rows was hit at 60% of positions. Our first hypothesis was that collisions among those frequent keys are the main defect of a hashed table. The rest of the design was narrowed by experiments. Every figure below is from our own short development runs, on reduced training lengths and validation subsets, and is reported as a development measurement (validation loss, lower is better).
- A collision-free head helps, but modestly. Adding an exact head tier in front of a hashed bigram tail improved on the hashed bigram table by about 0.05 (5.3057 against 5.3520, and 5.2634 against 5.3208 on a second backbone). A collision audit of the hashed tail explained why this could not be the whole story: a tail key's row was about 87% other keys' mass. The literature we read pointed the same way. It reported that a collision-free hot tier for Engram was a statistical tie, and that frequency-aware double hashing works for recommendation embeddings.
- Projections and multiple heads were worse. A single table behind an orthogonal projection (5.3805) and four narrow hash heads with a gate (5.4669) were both behind the plain exact tier (5.3057). This led to the coordinate-alignment hypothesis of Section 2. An identity-initialised projection recovered part of the loss (5.2975) but still trailed no projection at all (5.2634), so we dropped the projection.
- The memory is a persistent residual bias, not an input embedding. Injecting only before the first block (5.5879), or only beside the last block's MLP (5.5315), was far worse than injecting before every block (5.2634). The learned scales agreed with this. The first layer's scale stayed near zero (0.003 to 0.02), and all later ones settled near 0.25.
- Direct supervision hurt. An auxiliary cross-entropy on the memory's own next-token prediction made things worse (5.3359 against 5.2634). The memory should learn the residual correction, not the whole conditional distribution.
- A two-tier table with full-width head rows and narrow tail rows tied the single-width design (5.2652 against 5.2634) but ran about 44% slower per step, so we did not keep it.
- The backoff was the breakthrough. Replacing the hashed bigram tail with a row for the current token took the loss from 5.2634 to 5.1027, the largest single step in the run. Collapsing the tail to a single shared row was much worse (5.3377 against 5.2478 for a hashed tail, on a canonicalised variant), so the tail carries real signal. It needs to be well-estimated signal, not hashed signal.
- Canonicalising tokens (merging case and whitespace variants before keying) helped the hashed tail slightly (5.2542 against 5.2634) but hurt the backoff design (5.1285 against 5.1027). The backoff row needs to know, for example, whether the next token is capitalised.
- Higher orders did not pay at this budget. Adding trigrams to the keys made things worse (5.4150). Splitting a fixed number of rows across orders thins the bigram head.
- Soft backoff did not beat hard backoff. With the head grown to fill the whole budget, hard backoff reached 5.0745. An interpolated version, which always adds the unigram row and adds a bigram row on a hit, reached 5.0777. Count-dependent shrinkage between the two reached 5.0790 to 5.0869. We kept the hard switch. In those runs, substituting the clean unigram row was better than blending noisy low-count bigram signal back in.
- A row-sparse Adam that moves only touched rows was no better than dense AdamW in our short runs (5.2554 against 5.2478, on a canonicalised variant). We kept the hashed-bigram baseline's optimiser unchanged.
Two longer development runs checked that the effect survives training. On one backbone at the full training length, the final memory reached 3.5383 against the hashed bigram table's 3.5923. On another backbone at an intermediate length, it reached 4.2942 against 4.3957. A final diagnostic bucketed validation loss by the corpus count of each position's bigram and compared the trained model with its memory switched off. Reliance on the memory was large in every bucket, about 1.8 on the rarest bigrams (served by the backoff) and 1.9 on mid-count bigrams (served by the head). The switched-off model is not a fair dense baseline, so this measures reliance, not gain.
Limitations
- We do not beat the strongest baseline on any setting. The n-gram table with row-sparse Adam is ahead of us on every setting at a learning rate of 1.2e-3, and at its original learning rate on LAMBADA, and narrowly on FineWeb. Our development process missed this. In our short runs that baseline was behind the hashed bigram table (5.5877 against 5.3520), so we treated the hashed bigram table as the reference to beat. Our own row-sparse optimiser test was also run only at short length. The published results are consistent with the table's optimiser mattering more over a full training run than our short runs showed, though that baseline differs from ours in more than its optimiser. We left that axis unchanged.
- The advantage shrinks with training. In our full-length development run, the training-loss gap to the hashed bigram table narrowed from about 0.44 early on to about 0.05 at the end. Backoff Memory helps most where the tail is undertrained. With much more data per row, collisions in a hashed table matter less, and we expect the advantage to shrink further.
- Bigrams only. Keying on longer contexts made things worse at this budget. We did not find a way to use higher orders, for example an exact trigram head that backs off to the bigram head, which is the natural next level of the same hierarchy.
- The fusion ignores the hidden state. The retrieved row is added with a per-layer scalar whatever the context. A hit-dependent gate was tried only on a hashed-tail variant, and no context-aware gate was tried with the final design.
- The head is fixed at construction. Which bigrams get private rows is decided once, from corpus counts of the training data. Text whose frequent bigrams differ falls back to the unigram rows more often. Without corpus counts, the head rows go unused and the memory is a unigram table.
- Small rough edges. The first position reads one shared start row and so loses its own token's
unigram row. The code also keeps an unused attribute (
tail_mod) from an earlier hashed-tail version. - The training recipe is inherited. The learning-rate multiplier, betas and decay come from the hashed bigram baseline. They were not re-derived for a table whose rows now have very different update frequencies from one another.
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.