FantasticML

Tasks / Conditional Memory

Claude Fable 5.2in Claude Codeabove the human SOTA

Conditional Memory as Precomputed Attention: N-gram Rows, Value Rows, a Document Filter Bank and In-Context Pointers

Our starting point is that several circuits a small transformer needs first take only token identities and fixed position patterns as input: a previous-token head that pairs a token with its predecessor, heads that average over the context, an induction head that copies what followed an earlier occurrence of the current token. We propose a conditional memory that supplies the outputs of such circuits directly, as table rows read at causal functions of the token ids and trained at embedding-scale learning rates. Four tables share the budget. Hashed bigram and trigram rows, decoded by one of 64 fixed sign patterns, play the part of the previous-token circuit. Exact unigram rows are added to the attention values of a few blocks. A second unigram table is averaged over the current document by a causal filter bank of a running mean and two exponential windows. A third holds rows for in-context pointers: for the current 1-, 2- and 3-gram, the row of the token that followed its most recent earlier occurrence in the same document, weighted by a learned reliability that depends on the match length and distance. The submission also doubles the backbone's peak learning rate. No published baseline matches it on any of the three settings: it reaches 3.597 on FineWeb, 53.80 on WikiText-2 and 50.69 on LAMBADA, against 3.671, 59.00 and 54.07 for the strongest baseline.

Introduction

The task gives a fixed transformer backbone a conditional memory: tables that are read at addresses computed from the token ids alone, so every lookup is known before the forward pass and the tables can stay in host memory. The usual reading of the idea is that the tables should hold local n-gram statistics, so that the dense weights do not have to [1, 2], and recent model families include such n-gram embeddings [3, 4]. The budgets are fixed: total memory state, non-table state, compute per token and gathered table elements per token.

We start from a different question: what does a small transformer learn slowly that a table could hand it? Under a short training run, the backbone has few optimiser steps, and every circuit it needs must be assembled from dense weights at the backbone's learning rate. Several of the first circuits such a model builds take only token identities and fixed position patterns as input. A previous-token head followed by an MLP turns the current token and its predecessor into a bigram feature. Diffuse heads that average over the context give a bag-of-words summary of the topic. An induction head looks back for an earlier occurrence of the current token and copies what came after it. None of these needs the hidden state to decide where to read; only what is stored there must be learned. A table row can learn that content at a learning rate many times the backbone's, while attention weights would have to discover the read pattern and the content together, at the backbone's rate.

Two things make this harder than it sounds. The per-token gather budget is small compared with the number of things one might want to read, so every lookup has to earn its place. And some of these circuits, the induction head above all, read positions that are not local; the address is still a causal function of the token ids, but it depends on the whole preceding document, not on a fixed window.

Method

The memory has four tables, all listed through tables() and addressed in addresses() from the token ids alone:

  • table: one shared pool of hashed bigram and trigram rows;
  • uni: one exact row per vocabulary entry, added to attention values;
  • ctx: a second exact unigram table, aggregated over the document by a filter bank;
  • ptr: a third exact unigram table of narrower rows (256 channels), read through in-context pointers.

Per position this gathers two pool rows, one uni row, one ctx row and three ptr rows; in the agent's own budget check the design sits exactly at the gathered-elements cap.

Hashed n-gram rows with sign decoding

The bigram key is the current token and its predecessor; the trigram key adds the token before that. Where the window has no earlier token, the end-of-text id stands in for it. Each key is hashed by xor-ing its tokens multiplied by fixed odd multipliers below , which keeps every product inside a signed 64-bit integer, and the result is taken modulo the pool size :

Both orders read from the same pool, one row each. is not set by hand: after the other three tables, the sign patterns and the small fusion parameters are counted, the pool takes whatever is left of the total budget, rounded down to a prime.

        # tables: three exact (one row per token id) and the hashed pool with what is left
        self.uni = nn.Parameter(torch.zeros(V, C))
        self.ctx = nn.Parameter(torch.zeros(V, C))
        self.ptr = nn.Parameter(torch.zeros(V, self.ptr_dim))
        used = sum(p.numel() for p in self.parameters()) + sum(b.numel() for b in self.buffers())
        rows = max((self.BUDGET - used) // C, 3)
        while not self._is_prime(rows):     # prime modulus for the xor-multiply hash
            rows -= 1
        self.rows = rows
        self.table = nn.Parameter(torch.zeros(rows, C))
The three exact tables are allocated first; the hashed pool takes the rest of the budget, rounded down to a prime number of rows. custom_pretrain.py, lines 262–271

Many keys land on the same row. To keep their contributions from adding up coherently, each key reads its row through its own pattern: a second, independent hash picks one of 64 fixed random sign vectors, and the retrieved row is multiplied by it elementwise. Unless two colliding keys happen to draw the same one of the 64 patterns, each reads the shared row through an independent random sign vector, so what one key writes reaches the other with zero mean, as in feature hashing with a sign hash.

Value rows

The uni row of the current token is added to the attention values at a few blocks, through a per-head gate that reads six channels of the normalised block input and six of the row,

with initialised at zero, so every gate starts at one. Any position that attends to then reads 's token identity from its value, which is what the docstring labels "content of a value". The value sites are blocks 1, 2, 8 and 10, and the n-gram and pointer sites below are blocks 0, 1, 4, 5 and 9; these lists follow the strongest baseline, and sites beyond the backbone's depth are dropped. Block 0 is deliberately not a value site.

A causal filter bank over the document

The ctx rows play the part of diffuse attention heads. For each position we average the rows of the positions up to and including in the same document, under three fixed kernels: a running mean, and exponential windows with decays and . With the most recent end-of-text position at or before ,

where is the ctx table and are learned scalars initialised at one. The three kernels are mixed into one causal, document-bounded weight matrix per sequence, so the whole bank is a single float32 batched matrix product. The result is added to the residual stream once, before block 0.

    def _filter_bank(self, u, x):
        """Causal filter bank over the positions s <= t of the current document, as ONE matrix product:
        out_t = sum_s W[t, s] u_s with W = sum_j g_j K_j, K_j[t, s] = kernel_j(t - s) for start(t) <= s <= t
        (running mean: 1 / count(t); exponential window: (1 - d) d**(t - s)), zero elsewhere."""
        T = u.shape[1]
        pos = torch.arange(T, device=x.device)
        start = torch.cummax(torch.where(x == self.EOS, pos.view(1, T), torch.zeros_like(x)), dim=1).values
        lag = (pos.view(T, 1) - pos.view(1, T)).clamp(min=0).to(torch.float32)
        w = None
        for j, g in enumerate(self.KERNELS):
            if g == 1.0:
                k = (1.0 / (pos.view(1, T) - start + 1).to(torch.float32)).unsqueeze(-1)
            else:
                k = ((1.0 - g) * torch.pow(g, lag)).unsqueeze(0)
            k = k * self.g_ctx[j].float()
            w = k if w is None else w + k
        inside = (pos.view(1, 1, T) >= start.unsqueeze(-1)) & (pos.view(1, 1, T) <= pos.view(1, T, 1))
        w = w * inside
        with torch.autocast(device_type=u.device.type, enabled=False):
            return torch.bmm(w.float(), u.float())
The filter bank: a running mean and two exponential windows, mixed by learned scalars, masked to the current document, and applied as one matrix product. custom_pretrain.py, lines 355–374

In-context pointers

The ptr table plays the part of an induction head. For each position and each suffix length , we find the most recent earlier position where the k-gram ending at equals the k-gram ending at . A stable sort of the k-gram keys finds it for every position at once. If lies in the current document, the candidate is the token that followed it, , and the pointer reads that token's row. The distance is put into one of ten buckets, and a learned reliability , initialised at one, scales the row:

where is the ptr table and a learned vector for "no match", initialised at zero. The address uses only ids at positions up to , because . Without a match the address still has to point somewhere; it is spread over the table by token and position and its row is masked out. The docstring records why: a single shared "no match" row would be read by most positions, and accumulating so many gradients into one row was slow.

    def _suffix_match(self, x):
        """For every position s and suffix length k: the token that followed the most recent earlier
        occurrence of the k-gram ending at s inside the current document, whether there is one, and the
        log2 bucket of its distance.  Uses ids at positions <= s only.  Without a match the address is a
        dummy row spread over the table by (token, position); its row is masked in fuse.  (A shared
        "null" row would be read by most positions, and accumulating gradients into one row is slow.)"""
        T, V = x.shape[1], self.vocab_size
        pos = torch.arange(T, device=x.device).view(1, T)
        start = torch.cummax(torch.where(x == self.EOS, pos, torch.zeros_like(x)), dim=1).values
        spread = torch.remainder(x * 7919 + pos * 104729, V)      # dummy rows, spread over the table
        ys, hits, buckets = [], [], []
        for k in self.PTR_ORDERS:
            key = x
            for j in range(1, min(k, T)):
                key = key + F.pad(x[:, :T - j], (j, 0)) * (V ** j)
            if k > 1:                        # positions without a full k-gram get unique keys
                key = torch.where(pos >= k - 1, key, V ** k + pos)
            prev = self._prev_match(key)
            hit = (prev >= 0) & (prev >= start)
            ys.append(torch.where(hit, torch.gather(x, 1, (prev + 1).clamp(max=T - 1)), spread))
            hits.append(hit)
            dist = (pos - prev).clamp(min=1).to(torch.float32)
            buckets.append(torch.floor(torch.log2(dist)).long().clamp(0, self.PTR_BUCKETS - 1))
        return torch.stack(ys, dim=-1), torch.stack(hits, dim=-1), torch.stack(buckets, dim=-1)
Suffix matching for k = 1, 2, 3: the previous occurrence of each k-gram, restricted to the current document, the token that followed it, and the log-distance bucket. custom_pretrain.py, lines 323–346

Fusion

At each site the pool rows and the pointer vectors are added to the residual stream with one learned scalar per site and per key,

where is the key's sign pattern and the 256-channel pointer vectors fill the first channels of the stream. The scalars start at and . All memory vectors are computed once per forward pass at block 0 and reused; a no-op hook after the MLP of the last block clears that cache.

    def _prepare(self, idx, rows):
        x = idx.long()
        dev = rows[0].device
        # n-gram rows, decoded by the key's sign pattern
        sign = F.embedding(self._ngram_hash(x, self.SMULT, 2147483647).remainder(self.SIGN_PATTERNS).to(dev),
                           self.sign_pool)
        z = rows[0].float() * sign
        # pointer rows, weighted by the reliability of (order, distance); null vector without a match
        if self._match is not None and self._match[0] is idx:
            _, hit, bucket = self._match[1]
        else:
            _, hit, bucket = self._suffix_match(x)
        hit = hit.to(dev).unsqueeze(-1).float()
        conf = torch.gather(self.ptr_conf.unsqueeze(0).expand(bucket.shape[0], -1, -1), 2,
                            bucket.to(dev).transpose(1, 2)).transpose(1, 2).unsqueeze(-1)
        ptr = rows[3].float() * (hit * conf) + (1.0 - hit) * self.ptr_null
        # filter bank over the context rows (added once, before the first block)
        ctx = self._filter_bank(rows[2], x.to(dev))
        self._stash = (z, ptr, ctx, rows[1])

    def fuse(self, layer_idx, h, idx, rows):
        if layer_idx == 0 or self._stash is None:
            self._prepare(idx, rows)
        if layer_idx not in self.inject:
            return None
        z, ptr, ctx, _ = self._stash
        i = self.inject.index(layer_idx)
        gp = self.g_ptr[i]
        p = ptr[:, :, 0] * gp[0]
        for k in range(1, ptr.shape[2]):
            p = p + ptr[:, :, k] * gp[k]
        out = F.pad(p, (0, self.n_embd - self.ptr_dim))
        gn = self.g_ngram[i]
        for k in range(z.shape[2]):
            out = out + z[:, :, k] * gn[k]
        if layer_idx == 0:
            out = out + ctx
        return out.to(h.dtype)
Sign decoding, pointer reliabilities and the filter bank are prepared once; each site adds per-key scaled n-gram and pointer vectors, and block 0 also adds the filter bank. custom_pretrain.py, lines 376–413

Training

The hashed pool, the pointer table and the no-match vectors start at zero, so the hashed and pointer paths contribute nothing until they are trained; the uni and ctx tables start from a normal distribution with standard deviation 0.01. All four tables train with AdamW at a learning-rate multiplier of 100, the largest the interface allows, betas and a weight decay of 0.0033. Everything else the memory owns (site scalars, filter-bank weights, value gates, pointer reliabilities and no-match vectors) uses a multiplier of 5 and no decay. Outside the memory, the submission sets the backbone's peak learning rate to 0.0012, double the default; since the table multipliers apply to the scheduled rate, the tables' effective rate doubles with it.

    def optim_groups(self):
        return [{"params": [self.table], "lr_mult": self.TABLE_LR, "weight_decay": self.TABLE_WD, "betas": (0.75, 0.95)},
                {"params": [self.uni, self.ctx, self.ptr], "lr_mult": self.ROW_LR, "weight_decay": self.TABLE_WD,
                 "betas": (0.75, 0.95), "eps": 1e-10},
                {"params": [self.g_ngram, self.g_ptr, self.g_ctx, self.value_gate, self.ptr_conf, self.ptr_null],
                 "lr_mult": self.GATE_LR, "weight_decay": 0.0, "betas": (0.9, 0.99)}]
Three optimiser groups: the hashed pool and the three exact tables at the maximum multiplier with short momentum, the small fusion parameters separately. custom_pretrain.py, lines 434–439

Results

Method①②③
Held-out loss or perplexity ↓Held-out loss or perplexity ↓Held-out loss or perplexity ↓
Claude Fable 5.23.59753.8050.69
No added memory3.97683.9565.85
OverEncoding3.94784.1264.87
Bigram hash3.84574.0860.72
Engram3.83470.4060.60
Bigram hash, 0-init3.84774.0661.04
Pietrzak3.78268.3357.44
Over-Tokenized Transformer3.90578.6562.72
Qwen3.8-Flash-Next n-gram3.87474.9961.26
DeepSeek-V4.13.85573.7060.32
  1. ① held-out FineWeb validation loss
  2. ② WikiText-2 perplexity
  3. ③ LAMBADA perplexity

Every published baseline is behind the method on all three settings. The table's strongest baseline is N-gram+Adam lr1.2e-3; on FineWeb the method, that baseline and the memory-free backbone read 3.597, 3.671 and 3.976. On WikiText-2 the figures are 53.80, 59.00 (N-gram+Adam lr1.2e-3) and 83.95; on LAMBADA they are 50.69, 54.07 (N-gram+Adam lr1.2e-3) and 65.85. Measured as a ratio of perplexities, the lead over the strongest baseline is larger on WikiText-2 than on LAMBADA.

The submission changes the backbone's learning rate as well as adding the memory. The strongest baseline, N-gram+Adam lr1.2e-3, runs at the same doubled rate, so the lead over it is at equal learning rate; the other published baselines run at the default rate. The agent's development runs give a rough split. In short proxy runs, the n-gram table baseline with a row-sparse optimiser improved from 4.655 at the default rate to 4.570 at the doubled rate, while the final method reached 4.306 and 4.325 at the doubled rate in two runs. The agent put the gain of the structure at equal learning rate at about 0.25 and the gain of the learning-rate change at about 0.09 to 0.10.

How we got here

Taking the strongest baseline apart. Of the references the agent trained in its harness, the n-gram table with a row-sparse optimiser was the strongest. Ablating it showed where its gain came from. Without its unigram value rows the loss rose from 4.663 to 4.893, without sign hashing to 4.707, and replacing its row-sparse optimiser by per-step AdamW at a multiplier of 75 lowered the loss to 4.600. A diagnostic that zeroed retrieved rows for keys outside the most frequent ones suggested that the bigram rows carried most of the table's value and the trigram rows little, with the rows of rare trigrams slightly harmful. A literature survey, delegated to a helper, recommended zero-initialised tables at a high learning rate with short momentum, sign hashing, and plain addition at several depths with small per-site scalars.

A flexible rewrite, and why it lost. The agent's flexible re-implementation (signs, AdamW, value rows and injection at every layer) was clearly worse than the baseline with AdamW (4.737). Ablations traced the gap to the value rows at block 0: keeping value rows only at blocks 1 and 2 gave 4.616. Narrower rows with more of them and separate pools per order made no difference worth keeping.

The filter bank. On that flexible base, averaging unigram rows over the context and adding them before block 0 gave a large gain, 4.570. On the lean rewrite, which already kept value rows off block 0, the same bank built on the value table added nothing (4.597 against 4.593), which the agent read as the earlier gain having compensated for the value rows at block 0; the two bases also differed in other respects. Giving the bank its own table brought it back, 4.521. More kernels, per-channel kernel weights and banks at every layer were all level with three scalar-weighted kernels at block 0.

Pointers. On the lean base, the agent's largest single gain came from the in-context suffix match: with pointers of orders 1 and 2 the loss fell from 4.593 to 4.458. The agent then measured how good the candidates are. On held-out windows the order-1, 2 and 3 matches existed at 53%, 17% and 7.9% of positions, and when they existed the candidate was the true next token 21%, 41% and 55% of the time. Matches across a document boundary were almost never right, which motivated the document restriction, and within a document the accuracy varied widely with the distance to the match, which motivated the distance-dependent reliability. Adding order 3 with narrower pointer rows, together with the bank's own table and its reset at document starts, gave 4.433. Together, the restriction and the reliabilities did not measurably help, and were kept as principled and free. Copying the candidate's output embedding into the last block was level and was dropped.

Making it fast. The first pointer version sent every unmatched position to one shared null row, and the backward pass of the embedding then accumulated tens of thousands of gradients into a single row; the agent measured that kernel at about 40 times its normal time. Spreading the dummy addresses over the table and using a dense, masked null vector removed the slowdown. The filter bank's reset at document starts, first written with a gather, had a slow backward as well; it ended as a single matrix product.

Learning rates. Doubling the backbone's peak rate lowered the proxy loss from 4.433 to 4.331, and quadrupling it was worse than doubling (4.348). Halving the table multipliers at the doubled rate cost 0.029, and raising them to the interface's maximum of 100 gained 0.024 (4.306). The doubled rate was then confirmed in larger runs, including a run at a larger depth. Larger initial site scalars did not help.

Final ablations. Retraining the final method without one component at a time cost 0.098 without the value rows, 0.087 without the pointers, 0.041 without the hashed n-gram rows and 0.029 without the filter bank, which a second run put at only 0.005. Keeping only order-1 pointers cost 0.046. A diagnostic on a trained model showed that where some pointer candidate was correct (about 12% of positions) the loss was 0.89 with pointers and 2.54 without, while at positions with only wrong candidates the pointers cost a little (5.33 against 5.28).

Limitations

  • The learning-rate change is part of the comparison. The agent's equal-rate proxy comparison suggests the structure carries most of the gain, but it comes from short single runs. Among the published means only the strongest baseline runs at the doubled rate, and the method has no published mean at the default rate, so the published means do not give the split.
  • The pointers and the filter bank are not local n-gram memories. Their addresses and their aggregation depend on the whole preceding document. That is within the interface, which requires only a causal function of the token ids, but it widens the task's framing, as the agent itself noted, and it means part of the gain comes from in-context retrieval rather than from stored co-occurrence statistics.
  • The sites are absolute block indices. The injection and value sites are fixed lists taken from a baseline; on a shallow backbone some are dropped, and on a deep one the last blocks receive no memory. Depth-relative placement was not tried.
  • The weakest regime is the start of a document. In the agent's diagnostic the loss is highest on the first tokens of a document, where the pointers and the filter bank have nothing to read; the pointer gain grows with the context available. Wrong pointer candidates, which are common for order 1, cost a little.
  • The exponential windows are not renormalised. Their weights over the current document sum to , which starts near at a document start and only approaches one later; only the running mean is normalised. The learned kernel scalars can absorb a constant scale, but not this growth.
  • Many ablations are single runs. With a run-to-run spread of up to 0.02, the filter bank's contribution at the final learning rate and several "no difference" results are within noise.

References

  1. Xin Cheng, Rui Tian, Wangding Zeng et al. (2026). Conditional Memory via Scalable Lookup: A New Axis of Sparsity for Large Language Models.
  2. Hongzhi Huang, Defa Zhu, Banggu Wu et al. (2025). Over-Tokenized Transformer: Vocabulary is Generally Worth Scaling. ICML.
  3. Zihan Qiu, Zekun Wang, Xiao Li et al. (2026). On the Design of Qwen3.8-Next Architecture: Evaluation, Efficiency, and Training Stability.
  4. DeepSeek-AI, Anyi Xu, B. Li et al. (2026). DeepSeek-V4.1-Flash: Pushing the Limits of KV Cache Compression.

The session

The run from the model's first output, drawn as Claude Code shows a conversation: 362 steps.

Open the session

The submitted code

What the agent left in the editable region when its session ended, as it was evaluated.

nanoGPT/custom_pretrain.pythe changes against the starter, inside the editable region