Introduction
Much of what a small language model learns early is local: which token follows a frequent pair, how a common phrase continues. A conditional memory stores such statistics in a large table that is read sparsely, at rows chosen from the last few token ids, so the dense weights are freed for everything else. Because the address depends only on the ids, it is known before the forward pass and the table can be held in host memory and prefetched. Lookup-based memories of this kind have been proposed as a separate axis of sparsity for large models [1], hashed n-gram input embeddings are a close relative [2], and n-gram embeddings appear in recent model families as well [3, 4].
The task fixes the backbone, its training recipe and four budgets: the memory's total state, its non-table state, its compute per token and the number of table elements gathered per token. Inside those limits we choose how the memory is keyed, how its rows are shared, how they are fused with the hidden state and how they are trained. Three properties of the problem shaped our design.
Rows are scarce and n-gram frequencies are very uneven. In the agent's own count over a prefix of its development corpus, the million most frequent bigrams covered about 80% of all bigram occurrences, while the million most frequent trigrams covered about 38% and the million most frequent 4-grams about 16%. Hashing every n-gram into the same pool spends most rows on n-grams that are rarely seen, and forces frequent n-grams to share rows with them.
Collisions are biased, not just noisy. When two n-grams hash to the same row, each sees the other's vector added to its own, with the same sign every time. A plain hash therefore injects a systematic error that the model has to learn around.
Longer n-grams are less reliable. A bigram row is updated often and its vector can be trusted; a 4-gram row, or a hashed row shared by many rare 4-grams, is updated rarely. A fusion rule that treats all orders the same either drowns the bigram signal or amplifies the noisy ones.
Method
The memory has two tables. The n-gram table holds rows for bigrams, trigrams and 4-grams, each order
split into an exact segment and a hashed segment. The token table holds one row per vocabulary entry
and is injected at the attention values. Both are listed through tables(), so they can live on the
host; the hooks only receive the gathered rows. Each position gathers three rows from the first table
and one from the second, all at the model width.
Canonical keys
Before any key is formed, each token id is mapped to a canonical id, a vocabulary compression we take from the Engram baseline. The map is built once from the tokenizer's vocabulary: a token's text is NFKC-normalised, decomposed, stripped of combining accent marks, lower-cased, and its runs of spaces, tabs and newlines are collapsed; surrounding whitespace is then removed, except that a token made only of spaces, tabs and line breaks becomes a single space. A token that normalises to nothing keeps its raw text. Tokens whose bytes are not valid text on their own keep a byte-level key. Tokens that normalise to the same string share a canonical id, so " The", "the" and "THE" address the same rows. The canonical map is used only for keying; the backbone's own embedding still sees the raw ids.
For each position and order the key is the canonical n-gram ending at , . Positions before the start of the sequence are filled with the canonical id of the end-of-text token.
Exact rows for the head, hashed rows for the tail
The interface can hand the memory corpus counts of the most frequent n-grams of each order. We map those n-grams to canonical ids, add up the counts of n-grams that become identical, and keep the most frequent canonical n-grams, with , and . Each is packed into a single integer, base , and the sorted list is stored as a persistent buffer, so a checkpoint carries it.
for n in self.ORDERS:
K = self.KROWS[n]
dst = torch.zeros(K, dtype=torch.long)
if stats is not None and n in stats:
grams, counts = stats[n]
g = cmap[grams.long()]
key = torch.zeros(len(g), dtype=torch.long)
for j in range(n):
key = key * self.BASE + g[:, j]
uniq, inv = torch.unique(key, return_inverse=True)
agg = torch.zeros(len(uniq), dtype=torch.float64)
agg.index_add_(0, inv, counts.double())
k = min(K, len(uniq))
order = torch.argsort(agg, descending=True, stable=True)[:k]
sel = torch.sort(uniq[order]).values
dst[:k] = sel
if k < K:
dst[k:] = sel[-1] + 1 + torch.arange(K - k, dtype=torch.long)
self.register_buffer("keys%d" % n, dst)At addressing time a binary search looks the key up in that list. A hit is sent to its own row; a miss is hashed into the order's tail segment of , or rows with a multiply-and-xor hash,
where is the order's offset in the shared table and are fixed odd multipliers. The three addresses of a position are stacked into one lookup; the token table is addressed by the raw id.
def addresses(self, idx):
shifts = self._shifts(idx)
addrs = []
for n in self.ORDERS:
K, R, off = self.KROWS[n], self.RROWS[n], self.offsets[n]
keys = self.keys2 if n == 2 else (self.keys3 if n == 3 else self.keys4)
key = torch.zeros_like(shifts[0])
for j in range(n):
key = key * self.BASE + shifts[n - 1 - j]
pos = torch.searchsorted(keys, key.reshape(-1)).reshape(key.shape)
hit = (pos < K) & (keys[pos.clamp_max(K - 1)] == key)
a = off + torch.where(hit, pos, K + torch.remainder(self._mix(shifts, n), R))
addrs.append(a)
return [torch.stack(addrs, dim=-1), idx]Signed rows
Every retrieved n-gram row is multiplied elementwise by a pattern that depends on the n-gram and on the channel: if in wrapping signed 32-bit arithmetic and otherwise, where is the low 32 bits of the n-gram's multiply-and-xor hash above. Two n-grams that share a hashed row then see each other's contribution with a sign that varies across channels, so the cross-talk no longer adds up coherently, in the manner of a count sketch. The decorrelation is weaker than with independent random signs: every pattern is the same channel sequence , shifted by an offset derived from the hash, so two patterns whose offsets differ by (circularly, in units of ) have correlation about . Over random pairs that correlation is zero on average but spread evenly between and , rather than concentrated near zero. The pattern is computed, not stored, so it costs no memory and no gathered elements. It is applied to exact rows too, where it is harmless: an exact row has a single owner and the fixed pattern is simply absorbed into what the row learns.
Reliability-graded rescaling and a short convolution
Each order's signed vector is rescaled by its root mean square, but not to the same degree:
with a learned scalar initialised at one (a small constant is added under the root). The bigram vector is normalised fully, so its scale is set by and the fusion coefficients. The trigram and 4-gram vectors are only compressed: a larger row still produces a larger output, so the row norm can keep acting as a confidence signal for orders whose rows are often noisy. Each rescaled vector then receives a residual causal depthwise convolution, , with four taps at lags 0, 3, 6 and 9 positions. Its weights are shared across orders and start at zero, so the convolution is inactive until training moves it.
def _signs(self, mix):
h = mix.to(torch.int32).unsqueeze(-1)
v = h * 2654435761 + self.chan * 2246822519
return torch.where(v >= 0, 1.0, -1.0)
def _combined(self, idx, rows):
shifts = self._shifts(idx)
r = rows[0]
out = []
for j, n in enumerate(self.ORDERS):
mj = r[:, :, j] * self._signs(self._mix(shifts, n)).to(r.dtype)
_rms = mj.float().square().mean(dim=-1, keepdim=True)
mj = (mj.float() * torch.rsqrt(_rms + 1e-6) ** (1.0 if j == 0 else 0.5)).to(r.dtype)
if j == 0:
mj = mj * self.mscale[0]
y = F.conv1d(F.pad(mj.float().transpose(1, 2), (9, 0)), self.conv_w.float(), dilation=3, groups=mj.size(-1))
out.append((mj.float() + F.silu(y).transpose(1, 2)).to(r.dtype))
return outFusion before every block
The three order vectors are computed once per forward pass, at the first layer, and reused. Before block the memory adds
to the residual stream . The scale is per layer and per order and starts at 0.08; the gate vector starts at zero, so every gate starts at one half and the initial coefficient is exactly . As grows, the gate can learn to pass a retrieved vector where it agrees with the hidden state and to suppress it where it does not. Injecting at every layer from one shared table means each row is trained by the gradient of every layer that uses it, and the model decides through where the memory is useful.
Token value embeddings
The second table is a token-keyed value embedding. At every block, the value projection receives a per-head gated copy of the current token's row ,
where is the block's normalised attention input and a small per-layer matrix initialised at zero, so every head starts with a gate of one. The gate reads only six channels of each input, which keeps its cost small.
def fuse(self, layer_idx, h, idx, rows):
if layer_idx == 0 or self._cache is None:
self._cache = self._combined(idx, rows)
hn = F.rms_norm(h.float(), (h.size(-1),))
out = None
for j, mj in enumerate(self._cache):
mn = F.rms_norm(mj.float(), (mj.size(-1),))
gate = torch.sigmoid((hn * self.gq[layer_idx, j] * mn).sum(-1, keepdim=True))
term = self.lam[layer_idx, j] * 2.0 * gate * mj
out = term if out is None else out + term
return out.to(h.dtype)
def attn_value(self, layer_idx, v, h_attn_in, idx, rows):
B, T, C = v.shape
ve = rows[1].to(v.dtype)
xn = F.rms_norm(h_attn_in, (C,))
gate_in = torch.cat([xn[..., :6], ve[..., :6]], dim=-1)
gate = 2 * torch.sigmoid(F.linear(gate_in, self.ve_gate[layer_idx].to(v.dtype)))
aux = (gate.unsqueeze(-1) * ve.view(B, T, self.n_head, C // self.n_head)).view(B, T, C)
return v + auxTraining the memory
The n-gram table is initialised at zero, so the model starts as the dense backbone and the table grows only where gradients push it; the token table starts from a normal distribution with standard deviation 0.01. Both tables have their own AdamW groups with a learning-rate multiplier of 75 (n-gram table) or 70 (token table), betas and a small weight decay of . A table row receives a gradient only when its key occurs, so it needs a much larger step than a dense weight to learn within the same number of gradient signals; the multiplier and betas of the n-gram table are those of the bigram-hash baseline, which also uses a small weight decay. The scales, gates and convolution weights train at a multiplier of 5 without weight decay.
def optim_groups(self):
return [{"params": [self.table], "lr_mult": 75.0, "weight_decay": 0.1 * 5.0 / 150.0,
"betas": (0.75, 0.95)},
{"params": [self.ve_table], "lr_mult": 70.0, "weight_decay": 0.1 * 5.0 / 150.0,
"betas": (0.75, 0.95)},
{"params": [self.lam, self.gq, self.ve_gate, self.mscale, self.conv_w], "lr_mult": 5.0, "weight_decay": 0.0,
"betas": (0.9, 0.99)}]Outside the memory, the submission uses the one backbone knob the task leaves open: it sets the peak learning rate to 0.0012, twice the recipe's default, with the minimum following at a tenth of it. The schedule itself is unchanged. Because the table groups scale with the scheduled rate, this change also doubles the tables' effective learning rate.
Results
| Method | ① | ② | ③ |
|---|---|---|---|
| Held-out loss or perplexity ↓ | Held-out loss or perplexity ↓ | Held-out loss or perplexity ↓ | |
| Muse Wonder Full | 3.591 | 51.90 | 51.08 |
| 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 submission is ahead of every published baseline on every setting. On FineWeb it reaches 3.591 against 3.671 for the strongest baseline, N-gram+Adam lr1.2e-3, and 3.976 for the backbone without memory. On WikiText-2 it reaches 51.90 against 59.00 (N-gram+Adam lr1.2e-3) and 83.95 without memory, and on LAMBADA 51.08 against 54.07 (N-gram+Adam lr1.2e-3) and 65.85 without memory.
WikiText-2 and LAMBADA both report a perplexity; in relative terms our margin on WikiText-2 exceeds our margin on LAMBADA.
These are measurements of the whole submission, and the submission changes two things: the memory and the backbone's peak learning rate. In the agent's longest development runs, the final memory reached a validation loss of 3.769 with the doubled learning rate and 3.913 with the default one. The strongest baseline on every setting, N-gram+Adam lr1.2e-3, is named for a learning rate of 1.2e-3, the value of our peak learning rate, and we are ahead of it on every setting. The other published baselines did not change the learning rate, so the comparison with them credits both changes together, and the evaluation gives no way to split them.
How we got here
Reading the baselines. The agent first diffed every baseline in its workspace against the starter and trained all but one of them in its harness (the bigram hash without zero initialisation was left out). In the short screens the simplest one led: the zero-initialised bigram hash, injected before every layer with a per-layer scalar and trained at a learning-rate multiplier of 75, reached 5.641, against 5.756 for the n-gram table with a row-sparse optimiser and 6.160 without memory. The agent took that baseline's table optimiser recipe as its starting point. It also noticed that none of the baselines used the corpus n-gram counts that the interface offers, and measured the coverage figures quoted in the introduction.
Hashing first, then an exact head. The first candidate already had canonical keys, signed hashed bigram and trigram segments in one shared table, and per-layer, per-order injection at every layer; it reached 5.585. Splitting each order into exact rows for frequent n-grams and a hashed tail brought this to about 5.564. Removing parts of that version one at a time, the agent measured 5.598 without canonical keys, 5.629 without the sign patterns, 5.584 with more rows given to hashing than to exact keys, and 5.687 at a table multiplier of 30 instead of 75 (100 was level with 75).
What did not help. An auxiliary loss that asked the memory alone to predict the next token through the model's output head made the loss worse at weight 0.3 (5.608) and did nothing at weight 0.05. Narrower table rows with a learned up-projection, which would have allowed more rows, lost steadily as the rows narrowed (5.617, 5.645 and 5.729 for three widths). An additional injection next to the MLP, on top of the residual-stream fusion, was slightly worse, and a row-sparse optimiser for the tables made no measurable difference. A lighter canonicalisation that kept more distinctions was worse than the aggressive one. One sign-hash variant turned out to have a bug that made every sign positive; its result was discarded.
What was kept. The hidden-state gate and the token value embeddings were added next; the value embeddings were the largest single gain in that round, taking a screen from 5.551 to 5.536. A 4-gram tier improved the screen from 5.537 to 5.521, although in runs four times longer its advantage over the two-order memory disappeared (4.3345 against 4.3322). Normalising every order's vector helped without the 4-gram tier and hurt with it (5.580). The agent's reading was that full normalisation removes the row norm as a confidence signal, which matters most for the unreliable 4-gram tail. Normalising only the bigram vector gave 5.508, and the graded form, full for bigrams and half-exponent for longer orders, gave 5.492. The short convolution gained a few thousandths on two earlier bases, but added to the graded form it was level (5.4941 against 5.4922). In the longer runs the graded form with the convolution and the bigram-only form were level (4.3248 against 4.3228). Under the raised learning rate the graded form led (4.1438 against 4.1529), and it was kept.
The learning rate, last. In the screens a higher backbone peak learning rate helped strongly, which the agent suspected was an artefact of the short horizon. It checked the effect in longer runs, where it held, and then in its longest runs, where 0.0012 gave the 3.769 against 3.913 quoted above. A rate of 0.0015 was level with 0.0012 at that length (3.7675), and the agent kept the smaller value. In its remaining time it tried a table multiplier of 50 and a fusion scale initialised at 0.15; both tied the submitted values and were not adopted.
Limitations
- The learning-rate change confounds the comparison. In the agent's own runs, doubling the peak learning rate lowered the longest-run validation loss by about 0.14 (3.769 against 3.913). Only one published baseline, the strongest on every setting, is named for the same learning rate; the others run at the default rate, and against them the results above do not show how much the memory design alone gains. That would need the memory at the default rate, or those baselines at the doubled one.
- The exact head is frozen at construction. Which n-grams get exact rows is decided once, from counts over a prefix of the training corpus. In the agent's development measurement the exact rows caught about 58% of bigram positions, 13.6% of trigram positions and 3.9% of 4-gram positions in held-out text. Text whose frequent n-grams differ from the training prefix falls back to the hashed tail.
- Many constants were set by short screens. The row allocation across orders and tiers, the half-exponent for longer orders, the convolution's dilation and the table multipliers were chosen in short development runs, and several later checks at longer horizons ended in ties. The 4-gram tier, in particular, lost its measured advantage in longer runs and stayed in the design.
- The sign patterns are only weakly independent. Because every pattern is a shifted copy of one channel sequence, many pairs of colliding n-grams share most of their signs, and their cross-talk is then barely reduced. The agent measured a clear gain from the signs, but a pattern drawn from a better per-channel hash would likely decorrelate collisions further; the one such variant tried had a bug that made every sign positive, so this remains untested.
- N-grams cross document boundaries. The keys do not reset at end-of-text tokens, so a key can span the end of one document and the start of the next, and every window's first positions are padded as if a document had just ended. No boundary handling was tested in this run.
- Several pieces are borrowed. The table multiplier and betas follow the bigram-hash baseline, the canonicalisation follows the Engram baseline, and value embeddings and gated fusion are established ideas. What this design adds is the frequency-tiered exact head built from the interface's corpus counts, computed sign patterns on a shared table, and order-dependent rescaling that keeps the row norm as a confidence signal for the less reliable orders.
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.