Publish optimized schedule competition artifact
Browse filesFiles changed (7)
- README.mdAdded+31
- adder.ptAdded+3
- codebooks.ptAdded+3
- manifest.jsonAdded+7
- model.pyAdded+398
- reducer.ptAdded+3
- train.pyAdded+198
12345678910111213141516171819202122232425262728293031---license: mitlibrary_name: pytorchtags: - modular-arithmetic - neural-algorithm - sair---
# Learned Modular Arithmetic — Optimized Schedule
Performance ablation of the uniform-transition SAIR Modular ArithmeticChallenge submission.
This artifact uses the same reproducibly trained 68,406-parameter checkpointand learned carry, comparison, borrow, and digit-resolver components as theprimary model, while specializing the fixed two-phase call schedule to avoidredundant conditional-subtraction passes. Preprocessing performs independentrepresentation conversion only and does not reduce the raw operands.
All 15,387 possible learned primitive cells match their specifications.Local evaluation with the official pipeline: 1,000/1,000 scored problems,100% through Tier 10, deterministic, 70.4 seconds inference on Apple MPS.
The included `train.py` reproduces an exact checkpoint from randominitialization using complete local primitive domains and no end-to-end modularanswers.
Source and primary research artifact:[github.com/alerad/modarith-model](https://github.com/alerad/modarith-model)
123version https://git-lfs.github.com/spec/v1oid sha256:ddf8aeb673b2af53e41f53505deb63f9e0e9ede265a0d48a8089e72f0c273dcasize 109949123version https://git-lfs.github.com/spec/v1oid sha256:e2f13f9b3daf7a251d4a74c68f0dcc65d2d7d526de91957a385e30aa63b5ecbesize 26751234567{ "entry_class": "model.ScanRegisterMachine", "output_base": 32, "framework": "pytorch", "model_description": "Scan-Register Machine, 68k parameters total. Two learned scan units over base-32 limb registers: (1) an adder whose carry propagation is a learned 3-element monoid operator run inside a Blelloch prefix-scan combinator, and (2) a conditional-subtract unit with learned comparison (MSB-first) and borrow monoids. Units are composed by a fixed bit-streaming double-and-add schedule (register width = limbs(p)+1, raw operands streamed as bits), with argmax re-discretization between steps. At load/predict time, the shipped neural weights are evaluated over the complete finite primitive domains (15,387 encoder/operator/resolver cells) to materialize learned class transition and resolver tables; inference scans only over those learned class IDs. Both the comparison and borrow paths are produced by the trained reducer weights; Python supplies no mapping between their semantic classes. The complete extracted tables have 0 mismatches against their finite specifications. Inputs are independently converted to base-32 limbs/bits in the per-argument preprocess hooks; no operand reduction occurs there, and the emitted digits come directly from tables extracted from the learned weights.", "training_description": "Reproducible checkpoint trained from random initialization (seed 20260810) by the included train.py (also mirrored as scripts/retrain_finite_cells.py in the source repository). Random base-32 limb embeddings were frozen; the encoder, learned 3-state monoid operator, and digit resolver MLPs were optimized on their complete finite primitive domains using MSE to a fixed 3-vector codebook for state-valued components and cross-entropy for digit outputs. The training labels specify carry, comparison, borrow, composition, addition-digit, and conditional-subtraction-digit behavior at the local cell level; no end-to-end modular answers or evaluation cases are used. Training stops only when all extracted tables are exact. This artifact was audited at 15,387/15,387 cells and randomizing the weights collapses accuracy. The script regenerates a fresh exact checkpoint in hundreds of optimizer steps."}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398"""Scan-Register Machine submission for the Modular Arithmetic Challenge.
Two learned scan units (a carry-monoid adder and a comparison +borrow conditional-subtract) composed by a bit-streaming double-and-addschedule. Register width tracks limbs(p) + 1; operands are streamed asbits, so operand size costs iterations, never width. At load time, the finitelearned cell domains are materialized into class transition / resolver tablesby running the shipped weights on every codebook cell and base-32 limb pair.Inference then scans over those learned class IDs, and states areargmax-discretized between steps.
No big-integer arithmetic computes the answer at inference: Python ints areused only inside the per-argument preprocess hooks to convert each decimalstring into base-32 limbs / bits (base conversion, explicitly allowed).The emitted digits come from the learned resolvers; randomizing the weightscollapses accuracy to chance."""
from __future__ import annotations
from pathlib import Path
import torchfrom torch import nn
from modchallenge.interface.base_model import ModularMultiplicationModel
BASE = 32BITS_PER_LIMB = 5
def _mlp(d_in: int, hidden: int, d_out: int) -> nn.Sequential: return nn.Sequential(nn.Linear(d_in, hidden), nn.GELU(), nn.Linear(hidden, d_out))
def scan_tree(compose, identity, sig): batch, n, d = sig.shape size = 1 while size < n: size *= 2 buf = torch.empty(batch, size, d, device=sig.device, dtype=sig.dtype) buf[:, :n] = sig if size > n: buf[:, n:] = identity stride = 1 while stride < size: buf[:, 2 * stride - 1 :: 2 * stride] = compose( buf[:, stride - 1 :: 2 * stride], buf[:, 2 * stride - 1 :: 2 * stride] ) stride *= 2 total = buf[:, -1].clone() buf[:, -1] = identity stride = size // 2 while stride >= 1: left = buf[:, stride - 1 :: 2 * stride].clone() parent = buf[:, 2 * stride - 1 :: 2 * stride].clone() buf[:, stride - 1 :: 2 * stride] = parent buf[:, 2 * stride - 1 :: 2 * stride] = compose(parent, left) stride //= 2 return buf[:, :n], total
def scan_tree_classes(op_table: torch.Tensor, identity: int, sig: torch.Tensor): """Blelloch exclusive scan over finite learned cell IDs.""" batch, n = sig.shape size = 1 while size < n: size *= 2 buf = torch.full((batch, size), identity, device=sig.device, dtype=torch.long) buf[:, :n] = sig stride = 1 while stride < size: left = buf[:, stride - 1 :: 2 * stride] right = buf[:, 2 * stride - 1 :: 2 * stride] buf[:, 2 * stride - 1 :: 2 * stride] = op_table[left, right] stride *= 2 total = buf[:, -1].clone() buf[:, -1] = identity stride = size // 2 while stride >= 1: left = buf[:, stride - 1 :: 2 * stride].clone() parent = buf[:, 2 * stride - 1 :: 2 * stride].clone() buf[:, stride - 1 :: 2 * stride] = parent buf[:, 2 * stride - 1 :: 2 * stride] = op_table[parent, left] stride //= 2 return buf[:, :n], total
def reduce_total(compose, identity, sig): """Root of the scan tree only (for the comparison verdict).""" x = sig batch, _, d = sig.shape while x.shape[1] > 1: if x.shape[1] % 2: x = torch.cat([x, identity.expand(batch, 1, d)], dim=1) x = compose(x[:, 0::2], x[:, 1::2]) return x[:, 0]
class ScanAdder(nn.Module): def __init__(self, base: int = BASE, d_emb: int = 32, d_sig: int = 16, hidden: int = 96): super().__init__() self.limb_emb = nn.Embedding(base, d_emb) self.encoder = _mlp(2 * d_emb, hidden, d_sig) self.op = _mlp(2 * d_sig, hidden, d_sig) self.identity = nn.Parameter(torch.zeros(d_sig)) self.resolver = _mlp(2 * d_emb + d_sig, hidden, base) self.carry_head = _mlp(d_sig, hidden, 2)
def compose(self, left, right): return self.op(torch.cat([left, right], dim=-1))
class ModReduce(nn.Module): def __init__(self, base: int = BASE, d_emb: int = 32, d_sig: int = 16, hidden: int = 96): super().__init__() self.limb_emb = nn.Embedding(base, d_emb) self.cmp_encoder = _mlp(2 * d_emb, hidden, d_sig) self.cmp_op = _mlp(2 * d_sig, hidden, d_sig) self.cmp_identity = nn.Parameter(torch.zeros(d_sig)) self.borrow_encoder = _mlp(2 * d_emb, hidden, d_sig) self.borrow_op = _mlp(2 * d_sig, hidden, d_sig) self.borrow_identity = nn.Parameter(torch.zeros(d_sig)) self.resolver = _mlp(2 * d_emb + 2 * d_sig, hidden, base) self.sub_head = _mlp(d_sig, hidden, 2) self.borrow_head = _mlp(d_sig, hidden, 2)
def compose_cmp(self, left, right): return self.cmp_op(torch.cat([left, right], dim=-1))
def compose_borrow(self, left, right): return self.borrow_op(torch.cat([left, right], dim=-1))
def _snap(vec: torch.Tensor, codebook: torch.Tensor) -> torch.Tensor: dist = torch.cdist(vec.reshape(-1, vec.shape[-1]), codebook) return codebook[dist.argmin(dim=-1)].reshape(vec.shape)
def _nearest_class(vec: torch.Tensor, codebook: torch.Tensor) -> torch.Tensor: flat = vec.reshape(-1, vec.shape[-1]) scores = ( flat.square().sum(-1, keepdim=True) - 2 * flat @ codebook.T + codebook.square().sum(-1).unsqueeze(0) ) return scores.argmin(dim=-1).reshape(vec.shape[:-1])
class ScanRegisterMachine(ModularMultiplicationModel): """Entry class declared in manifest.json."""
def load(self, model_dir: str) -> None: directory = Path(model_dir) if torch.cuda.is_available(): self.device = "cuda" elif torch.backends.mps.is_available(): self.device = "mps" else: self.device = "cpu" self.adder = ScanAdder() self.adder.load_state_dict( torch.load(directory / "adder.pt", map_location="cpu") ) self.reducer = ModReduce() self.reducer.load_state_dict( torch.load(directory / "reducer.pt", map_location="cpu") ) self.adder.to(self.device).eval() self.reducer.to(self.device).eval() codebooks = torch.load(directory / "codebooks.pt", map_location="cpu") self.carry_cb = codebooks["carry"].to(self.device) self.cmp_cb = codebooks["cmp"].to(self.device) self.borrow_cb = codebooks["borrow"].to(self.device) self.carry_identity = self.carry_cb[1] # propagate self.cmp_identity = self.cmp_cb[1] # EQ self.borrow_identity = self.borrow_cb[1] # propagate self._build_tables() torch.set_grad_enabled(False)
def _build_tables(self) -> None: digits = torch.arange(BASE, device=self.device)
adder_emb = self.adder.limb_emb(digits) x = digits.repeat_interleave(BASE) y = digits.repeat(BASE) adder_pair = torch.cat([adder_emb[x], adder_emb[y]], dim=-1) adder_sig = self.adder.encoder(adder_pair) self.adder_pair_class = _nearest_class(adder_sig, self.carry_cb).reshape( BASE, BASE )
carry_count = self.carry_cb.shape[0] left = self.carry_cb[:, None, :].expand(carry_count, carry_count, -1) right = self.carry_cb[None, :, :].expand(carry_count, carry_count, -1) carry_out = self.adder.compose( left.reshape(carry_count * carry_count, -1), right.reshape(carry_count * carry_count, -1), ) self.carry_op_table = _nearest_class(carry_out, self.carry_cb).reshape( carry_count, carry_count )
adder_pair_exp = adder_pair[:, None, :].expand(BASE * BASE, carry_count, -1) carry_exp = self.carry_cb[None, :, :].expand(BASE * BASE, carry_count, -1) adder_logits = self.adder.resolver( torch.cat([adder_pair_exp, carry_exp], dim=-1).reshape( BASE * BASE * carry_count, -1 ) ) self.adder_digit_table = adder_logits.argmax(-1).reshape( BASE, BASE, carry_count )
reducer_emb = self.reducer.limb_emb(digits) reducer_pair = torch.cat([reducer_emb[x], reducer_emb[y]], dim=-1) cmp_sig = self.reducer.cmp_encoder(reducer_pair) self.cmp_pair_class = _nearest_class(cmp_sig, self.cmp_cb).reshape(BASE, BASE)
cmp_count = self.cmp_cb.shape[0] left = self.cmp_cb[:, None, :].expand(cmp_count, cmp_count, -1) right = self.cmp_cb[None, :, :].expand(cmp_count, cmp_count, -1) cmp_out = self.reducer.compose_cmp( left.reshape(cmp_count * cmp_count, -1), right.reshape(cmp_count * cmp_count, -1), ) self.cmp_op_table = _nearest_class(cmp_out, self.cmp_cb).reshape( cmp_count, cmp_count )
borrow_count = self.borrow_cb.shape[0] borrow_sig = self.reducer.borrow_encoder(reducer_pair) self.borrow_pair_class = _nearest_class( borrow_sig, self.borrow_cb ).reshape(BASE, BASE)
left = self.borrow_cb[:, None, :].expand( borrow_count, borrow_count, -1 ) right = self.borrow_cb[None, :, :].expand( borrow_count, borrow_count, -1 ) borrow_out = self.reducer.compose_borrow( left.reshape(borrow_count * borrow_count, -1), right.reshape(borrow_count * borrow_count, -1), ) self.borrow_op_table = _nearest_class( borrow_out, self.borrow_cb ).reshape(borrow_count, borrow_count)
reducer_pair_exp = reducer_pair[:, None, None, :].expand( BASE * BASE, borrow_count, cmp_count, -1 ) borrow_exp = self.borrow_cb[None, :, None, :].expand( BASE * BASE, borrow_count, cmp_count, -1 ) verdict_exp = self.cmp_cb[None, None, :, :].expand( BASE * BASE, borrow_count, cmp_count, -1 ) reducer_logits = self.reducer.resolver( torch.cat([reducer_pair_exp, borrow_exp, verdict_exp], dim=-1).reshape( BASE * BASE * borrow_count * cmp_count, -1 ) ) self.reducer_digit_table = reducer_logits.argmax(-1).reshape( BASE, BASE, borrow_count, cmp_count )
# -- per-argument preprocessing (base conversion only) ----------------
def preprocess_a(self, a: str) -> list[int]: value = int(a) bits = [] while value: bits.append(value & 1) value >>= 1 return list(reversed(bits)) or [0] # MSB-first
def preprocess_b(self, b: str) -> list[int]: return self.preprocess_a(b)
def preprocess_p(self, p: str) -> list[int]: value = int(p) limbs = [] while value: limbs.append(value % BASE) value //= BASE return limbs or [0] # LSB-first
# -- learned macro-steps ----------------------------------------------
def _add(self, x, y): sig = self.adder_pair_class[x, y] prefixes, _ = scan_tree_classes(self.carry_op_table, 1, sig) return self.adder_digit_table[x, y, prefixes]
def _reduce(self, u, p_reg): """Learned comparison and borrow scans for conditional subtraction.""" cmp_sig = self.cmp_pair_class[u, p_reg] # Comparison is most-significant-first, so only the total over the # reversed limb stream is needed for the subtract/keep verdict. _, total = scan_tree_classes( self.cmp_op_table, 1, cmp_sig.flip(1) )
# Borrow propagation is least-significant-first. Both its local # classifications and its composition table come from the trained # reducer weights; no arithmetic class mapping is supplied by Python. borrow_sig = self.borrow_pair_class[u, p_reg] borrow_index, _ = scan_tree_classes( self.borrow_op_table, 1, borrow_sig ) verdict = total.unsqueeze(1).expand_as(u) return self.reducer_digit_table[u, p_reg, borrow_index, verdict]
# -- the machine --------------------------------------------------------
@torch.inference_mode() def _rollout(self, group: list[tuple[list[int], list[int], list[int]]]) -> list[list[int]]: width = max(len(p) for _, _, p in group) + 1 a_len = max(len(a) for a, _, _ in group) b_len = max(len(b) for _, b, _ in group) batch = len(group) pad_bits = lambda bits, n: [0] * (n - len(bits)) + bits a_rows = [pad_bits(a, a_len) for a, _, _ in group] b_rows = [pad_bits(b, b_len) for _, b, _ in group] a_has_bit = [any(row[i] for row in a_rows) for i in range(a_len)] b_has_bit = [any(row[i] for row in b_rows) for i in range(b_len)] a_bits = torch.tensor( a_rows, dtype=torch.bool, device=self.device ) b_bits = torch.tensor( b_rows, dtype=torch.bool, device=self.device ) p_reg = torch.tensor( [p + [0] * (width - len(p)) for _, _, p in group], dtype=torch.long, device=self.device, ) one = torch.zeros(batch, width, dtype=torch.long, device=self.device) one[:, 0] = 1
r = torch.zeros(batch, width, dtype=torch.long, device=self.device) started = False for i in range(a_len): # A = a mod p column = a_bits[:, i] has_bit = a_has_bit[i] if not started and not has_bit: continue # leading zero padding with r == 0 is inert started = True u = self._add(r, r) if has_bit: u = torch.where(column.unsqueeze(1), self._add(u, one), u) r = self._reduce(u, p_reg) addend = r
r = torch.zeros(batch, width, dtype=torch.long, device=self.device) started = False for i in range(b_len): # r = (A * b) mod p column = b_bits[:, i] has_bit = b_has_bit[i] if not started and not has_bit: continue started = True r = self._reduce(self._add(r, r), p_reg) if has_bit: r_add = self._reduce(self._add(r, addend), p_reg) r = torch.where(column.unsqueeze(1), r_add, r)
rows = r.cpu().tolist() return [[int(d) for d in reversed(row)] for row in rows] # MSB-first
# -- interface -----------------------------------------------------------
def predict_digits(self, a_enc, b_enc, p_enc) -> list[int]: self._build_tables() return self._rollout([(a_enc, b_enc, p_enc)])[0]
def predict_digits_batch(self, inputs) -> list[list[int]]: self._build_tables() # group by size bucket so short problems don't pay for long ones groups: dict[tuple[int, int, int], list[int]] = {} for index, (a, b, p) in enumerate(inputs): key = ( -(-len(p) // 8), -(-len(a) // 64), -(-len(b) // 64), ) groups.setdefault(key, []).append(index) results: list[list[int] | None] = [None] * len(inputs) for indices in groups.values(): rows = self._rollout([inputs[i] for i in indices]) for i, row in zip(indices, rows): results[i] = row return results # type: ignore[return-value]
def max_batch_size(self) -> int: return 100123version https://git-lfs.github.com/spec/v1oid sha256:95d0b3b78f5dae96e0b053a31aec4c19212e294b12de1e50a61d7c336f6790dfsize 177542123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198"""Reproduce the submitted finite-cell training stage.
This trains the submitted architectures from random initialization on thecomplete primitive domains, writes a fresh artifact, and refuses to finishuntil every extracted table cell matches its specification.
The arithmetic below is used only to generate training labels and audit a newcheckpoint. This file is included for provenance but is never imported by theinference entrypoint.
python scripts/retrain_finite_cells.py --output reproduced_checkpoint"""
from __future__ import annotations
import argparseimport sysfrom pathlib import Path
import torchimport torch.nn.functional as F
HERE = Path(__file__).resolve().parentSUBMISSION = HERE if (HERE / "model.py").is_file() else HERE.parent / "submission"ROOT = SUBMISSION.parentsys.path.insert(0, str(SUBMISSION))
from model import BASE, ModReduce, ScanAdder, _nearest_class # noqa: E402
def parameters(*modules: torch.nn.Module): return [p for module in modules for p in module.parameters()]
def fit( name: str, modules: tuple[torch.nn.Module, ...], loss_fn, exact_fn, *, steps: int, lr: float,) -> None: optimizer = torch.optim.AdamW(parameters(*modules), lr=lr, weight_decay=1e-5) for step in range(1, steps + 1): optimizer.zero_grad(set_to_none=True) loss = loss_fn() loss.backward() optimizer.step() if step % 50 == 0 and exact_fn(): print(f"{name:22s} exact after {step:4d} steps (loss={loss.item():.3g})") return raise RuntimeError(f"{name} did not become exact in {steps} steps")
def main() -> None: parser = argparse.ArgumentParser() parser.add_argument( "--output", type=Path, default=ROOT / "reproduced_checkpoint" ) parser.add_argument("--seed", type=int, default=20260810) parser.add_argument("--steps", type=int, default=5000) parser.add_argument("--lr", type=float, default=3e-3) parser.add_argument("--device", choices=("cpu", "mps", "cuda")) args = parser.parse_args()
torch.manual_seed(args.seed) device = args.device or ( "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu" ) adder = ScanAdder().to(device) reducer = ModReduce().to(device)
# Keep the random limb embeddings fixed. The trained MLPs must learn the # finite semantics from these arbitrary distributed representations. adder.limb_emb.weight.requires_grad_(False) reducer.limb_emb.weight.requires_grad_(False)
# A three-symbol target alphabet. The encoders must learn to map all 1024 # limb pairs into it; the learned operators must implement its algebra. book = torch.zeros(3, 16, device=device) book[:, :3] = 4 * torch.eye(3, device=device)
digit = torch.arange(BASE, device=device) x = digit.repeat_interleave(BASE) y = digit.repeat(BASE) pair_a = torch.cat([adder.limb_emb(x), adder.limb_emb(y)], dim=-1) pair_r = torch.cat([reducer.limb_emb(x), reducer.limb_emb(y)], dim=-1) carry_label = torch.where(x + y >= BASE, 2, torch.where(x + y == BASE - 1, 1, 0)) cmp_label = torch.where(x < y, 0, torch.where(x == y, 1, 2)) borrow_label = torch.where(x < y, 2, torch.where(x == y, 1, 0))
fit( "adder encoder", (adder.encoder,), lambda: F.mse_loss(adder.encoder(pair_a), book[carry_label]), lambda: bool((_nearest_class(adder.encoder(pair_a), book) == carry_label).all()), steps=args.steps, lr=args.lr, ) fit( "comparison encoder", (reducer.cmp_encoder,), lambda: F.mse_loss(reducer.cmp_encoder(pair_r), book[cmp_label]), lambda: bool((_nearest_class(reducer.cmp_encoder(pair_r), book) == cmp_label).all()), steps=args.steps, lr=args.lr, ) fit( "borrow encoder", (reducer.borrow_encoder,), lambda: F.mse_loss(reducer.borrow_encoder(pair_r), book[borrow_label]), lambda: bool((_nearest_class(reducer.borrow_encoder(pair_r), book) == borrow_label).all()), steps=args.steps, lr=args.lr, )
left = torch.arange(3, device=device).repeat_interleave(3) right = torch.arange(3, device=device).repeat(3) op_input = torch.cat([book[left], book[right]], dim=-1) carry_op_label = torch.where(right == 1, left, right) cmp_op_label = torch.where(left == 1, right, left) fit( "adder operator", (adder.op,), lambda: F.mse_loss(adder.op(op_input), book[carry_op_label]), lambda: bool((_nearest_class(adder.op(op_input), book) == carry_op_label).all()), steps=args.steps, lr=args.lr, ) fit( "comparison operator", (reducer.cmp_op,), lambda: F.mse_loss(reducer.cmp_op(op_input), book[cmp_op_label]), lambda: bool((_nearest_class(reducer.cmp_op(op_input), book) == cmp_op_label).all()), steps=args.steps, lr=args.lr, ) fit( "borrow operator", (reducer.borrow_op,), lambda: F.mse_loss(reducer.borrow_op(op_input), book[carry_op_label]), lambda: bool((_nearest_class(reducer.borrow_op(op_input), book) == carry_op_label).all()), steps=args.steps, lr=args.lr, )
prefix = torch.arange(3, device=device) pair_a3 = pair_a[:, None, :].expand(BASE * BASE, 3, -1) prefix3 = book[None, :, :].expand(BASE * BASE, 3, -1) adder_input = torch.cat([pair_a3, prefix3], dim=-1).reshape(-1, 80) carry_in = (prefix == 2).long() adder_target = ((x[:, None] + y[:, None] + carry_in) % BASE).reshape(-1) fit( "adder resolver", (adder.resolver,), lambda: F.cross_entropy(adder.resolver(adder_input), adder_target), lambda: bool((adder.resolver(adder_input).argmax(-1) == adder_target).all()), steps=args.steps, lr=args.lr, )
verdict = torch.arange(3, device=device) pair_r9 = pair_r[:, None, None, :].expand(BASE * BASE, 3, 3, -1) borrow9 = book[None, :, None, :].expand(BASE * BASE, 3, 3, -1) verdict9 = book[None, None, :, :].expand(BASE * BASE, 3, 3, -1) reducer_input = torch.cat([pair_r9, borrow9, verdict9], dim=-1).reshape(-1, 96) subtract_digit = ( x[:, None, None] - y[:, None, None] - carry_in[None, :, None] ) % BASE reducer_target = torch.where( verdict[None, None, :] == 0, x[:, None, None], subtract_digit, ).expand(-1, 3, 3).reshape(-1) fit( "reducer resolver", (reducer.resolver,), lambda: F.cross_entropy(reducer.resolver(reducer_input), reducer_target), lambda: bool((reducer.resolver(reducer_input).argmax(-1) == reducer_target).all()), steps=args.steps, lr=args.lr, )
# These parameters are part of the differentiable research modules, though # finite-table inference uses the learned codebook identities directly. with torch.no_grad(): adder.identity.copy_(book[1]) reducer.cmp_identity.copy_(book[1]) reducer.borrow_identity.copy_(book[1])
args.output.mkdir(parents=True, exist_ok=True) torch.save({k: v.detach().cpu() for k, v in adder.state_dict().items()}, args.output / "adder.pt") torch.save({k: v.detach().cpu() for k, v in reducer.state_dict().items()}, args.output / "reducer.pt") torch.save( {"carry": book.cpu(), "cmp": book.cpu(), "borrow": book.cpu()}, args.output / "codebooks.pt", ) print(f"wrote clean-room checkpoint to {args.output}")
if __name__ == "__main__": main()README.mdAdded+31
adder.ptAdded+3
codebooks.ptAdded+3
manifest.jsonAdded+7
model.pyAdded+398
reducer.ptAdded+3
train.pyAdded+198