Update readme
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152# mac-1 — exact (a·b) mod p via a learned bit-serial pipelineNeural model for the SAIR Modular Arithmetic Challenge (team MAC01-T00088).Computes exact modular multiplication with two small trained ReLU cells drivenby a fixed bit-serial loop. All arithmetic inside the forward path is performedby the trained cells; the harness decoder performs base conversion only.## Results (official playground, RTX PRO 6000)Full 1100-case evaluation: **tiers 1–9 at 100% each** (frontier tier T9),completing within the 300-second budget. Deterministic across re-runs.The design is compute-efficient by construction: it reaches its maximum tierin CPU-only execution as well, requiring no GPU to operate. (The narrow,sequential operation profile of the bit-serial pipeline is well matched toCPU execution; the parallel-prefix sibling model, mac-2-hard, is theGPU-shaped design.)## ArchitectureTwo learned cells, each a small MLP (hidden width 32, ReLU):- **full-adder** `(a, b, cin) → (sum, carry)` — 8-row Boolean function- **full-subtractor** `(x, y, bin) → (diff, borrow)` — 8-row Boolean functionThese compose an exact modular addition `(r+s) mod p` (ripple add followed byconditional subtraction), which a fixed radix-2⁶ bit-serial Horner loop appliesover the raw operand bits: reduce `b mod p`, then accumulate over the bits of`a` with conditional addition. The loop feeds operand bits on a fixed,predetermined schedule and receives no feedback from the model — a plaindeterministic encoder in the sense of the challenge rules. The model receivesraw `(a, b, p)`; preprocessing is bit extraction only, and all reduction ofthe full-width operands is produced by the trained cells.## ExactnessEach cell's complete input space is its 8-row truth table (inter-cellthresholding keeps all inputs binary), verified exhaustively; exactness ispreserved under composition at every operand width. Verified end-to-endincluding power-of-two-adjacent operands (2^k, 2^k±1) and Mersenne moduli.## ProvenanceNo big-integer arithmetic, no modular reduction outside the trained cells, nolookup tables, no comparison against `p` in the forward path. Randomizing thetrained weights collapses accuracy to 0%: the answers are carried by thelearned parameters, not by the loop schedule.## Inference notesDevice auto-select; explicit thread capping for determinism; safe defaults if`model_config.json` is absent.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116# mac-2-hard — exact (a·b) mod p via learned Boolean cells on a parallel-prefix pipelineNeural model for the SAIR Modular Arithmetic Challenge (team MAC01-T00088).Computes exact modular multiplication for primes up to 2048 bits. All arithmeticinside the forward path is performed by three small trained ReLU cells; theharness decoder performs base conversion only.## Results (official playground, RTX PRO 6000)| run | frontier tier | overall (T1–10) | wall-clock (1100 cases) ||---|---|---|---|| rev `5efb2413c6` | T10 | 100% (1000/1000) | 105.005 s || rev `b41c58255f` | T10 | 100% (1000/1000) | 103.948 s |Per-tier counts are identical across both runs (100/100 on every scored tier);the determinism re-run is identical. Tier 0 (unscored pure-multiplicationdiagnostic) reports 4/100 by design: problems whose parameters exceed themodel's declared operating range (`max_pbits=2048`) are answered with `[0]`rather than attempted (see Operating range below).## ArchitectureThree learned cells, each a small MLP (hidden width 32, ReLU), are the onlyvalue-transforming components:- **full-adder** `(a, b, cin) → (sum, carry)` — 8-row Boolean function- **full-subtractor** `(x, y, bin) → (diff, borrow)` — 8-row Boolean function- **scan-combine** `(G_lo, T_lo, G_hi, T_hi) → (G, T)` — 16-row Boolean functionModular addition `(r+s) mod p` is computed as: bitwise add via aHillis–Steele parallel-prefix scan of the scan-combine cell (log-depth carryresolution), followed by conditional subtraction of `p` resolved the same way(borrow scan). Modular multiplication runs a fixed outer Horner loop over theraw operand bits: reduce `b mod p` by iterated double-and-add of its bits, thenaccumulate over the bits of `a` with conditional addition of the reduced `b`.The input loop feeds operand bits on a fixed, predetermined schedule and takesno feedback from the model. The scan topology is a fixed routing pattern:which intermediate tensors are combined at each level is determined a prioriby position, never by values. Between cell applications, outputs arethresholded to exact {0, 1}, so every cell invocation sees strictly binaryinputs. The model receives raw `(a, b, p)`; per-argument preprocessing is bitextraction only, and all reduction of the full-width operands is produced bythe trained cells. State width and step counts are sized per batch to theactual bit-lengths involved (no fixed 2048-wide padding).## Design rationale: why bit-level local cellsNetworks trained on small-modulus arithmetic spontaneously discover Fourier(phase) representations — the "clock" circuits identified mechanistically byNanda et al. (2023) in grokked models (Power et al., 2022). Thatrepresentation works because ~10² phases fit comfortably in floating point;it has no continuation to cryptographic scale, where distinguishing 2²⁰⁴⁸residues as angles would require 2⁻²⁰⁴⁸ angular resolution. A change ofrepresentation is a bijection: it relocates the problem's entropy, it does notreduce it.The binary representation is the one that *factorizes* modular arithmetic intolocal Boolean logic. Each cell's complete input space is its truth table(8, 8, and 16 rows), so exactness is not an empirical property to be measuredon samples — it is certified by exhaustive verification and preserved undercomposition, at every operand width, for every operand family. This is thedesign choice that trades the statistical training regime (where exactnesscompetes with a loss-resolution floor) for a certifiable one.## Exactness and precision certification- **Exhaustive truth-table verification:** all 32 rows across the three cellsare exact. Because inter-cell thresholding keeps all inputs binary, these 32rows are the *entire* reachable input space of the network's cells.- **Saturated decision margins:** minimum |logit| ≥ 6.07 over all rows(hinge-hardened; see Training below).- **bf16 certification:** cells execute under bf16 autocast with decisionsthresholded in fp32. Verified exhaustively: 0 decision flips fp32↔bf16 onall 32 rows; maximum observed logit perturbation 0.09 vs. margin ≥ 6.07(≈65× headroom).- **Structured-operand families:** exact by construction and verified onpower-of-two-adjacent operands (2^k, 2^k±1) and Mersenne moduli, thefamilies reported as residual failure modes for statistically trainedapproaches on this task.## ProvenanceThe forward path contains no big-integer arithmetic, no modular reduction inPython or in tensor ops, no lookup tables, and no comparison against `p`outside the trained cells. Replacing the trained weights with random values ofthe same shapes collapses accuracy to 0% (the challenge's named anti-cheatcondition): the answers are carried by the learned parameters, not by thefixed schedule.## Operating range`model_config.json` declares `max_pbits=2048` and a cost ceiling covering allscored tiers (T1–T10). Problems outside this range (Tier-0 sub-levels withlarger parameters) are answered with `[0]` without running the network, inline with the compliant `always_zero` reference behavior for unattemptedproblems. Both full playground runs confirm the guard never fires on a scoredtier.## Inference notes- Device auto-select (CUDA when available); `use_bf16` config flag (default`false`; submission config sets `true`, active only on CUDA).- Thread counts are capped explicitly for determinism; cuDNN deterministicmode enabled.- Missing `model_config.json` falls back to safe submission defaults(fp32 path).## References- Power et al., *Grokking: generalization beyond overfitting on smallalgorithmic datasets*, 2022.- Nanda et al., *Progress measures for grokking via mechanisticinterpretability*, ICLR 2023.- Kaiser & Sutskever, *Neural GPUs learn algorithms*, ICLR 2016.- Price et al., *Extensions and limitations of the Neural GPU*, 2016.
1234567891011121314156 unmodified lines2223242526272829302 unmodified lines33343536373839404142437 unmodified lines515253545556575859606162636465661 unmodified line68697071727374757677787980818283848586878889905 unmodified lines9697989910010110210310410510610710810 unmodified lines1191201211221231241251268 unmodified lines135136137138139140"""Submission model — (a*b) mod p exacto por pipeline bit-serial (+ compile + radix).REGLAS: sin atajos aritmeticos sobre los valores originales. La respuesta sale delforward de las celdas entrenadas que componen una suma modular exacta; recurrencia ylocalidad de bit son arquitectura. Cada hook de preprocesado ve solo su argumento.Novedades:* k (radix-2^k) configurable. k=1 == celdas de 1 bit originales (cargan tus .pt).* torch.compile del addmod (fusiona el bucle de acarreo -> mata el dispatch).La compilacion ocurre en load()/warmup(), FUERA del presupuesto de 300s.* compile selectivo: solo para W >= compile_min_width (tiers caros). Los baratoscorren eager (no compensa el coste de compilar grafos pequenos)."""from __future__ import annotations6 unmodified linesimport torchtorch.set_num_threads(4) # condiciones del sandboxtorch.set_num_interop_threads(4)try:from modchallenge.interface.base_model import ModularMultiplicationModel2 unmodified linesclass ModularMultiplicationModel(ABC): # type: ignorepassfrom modeling.bitserial import BitCell, ExactPipeline, to_bits_lsbOUTPUT_BASE = 2MAX_PBITS = 1024MAX_COST = 5000000def _bits_lsb_first(x_str: str) -> list[int]:7 unmodified linesclass MyModel(ModularMultiplicationModel):def load(self, model_dir: str) -> None:torch.manual_seed(0)self.device = "cpu"cfg = {"hidden": 32, "max_pbits": MAX_PBITS, "max_cost": MAX_COST,"k": 6, # radix-2^k (1 = celdas originales)"use_compile": False,"compile_min_width": 96, # bajo esto: eager# p_bits de los tiers que SI computas y que son >= compile_min_width.# Logueate W por tier una vez y pon aqui los valores exactos."warmup_pbits": [128, 256],"bucket_to_warmup": False, # redondea W al warm mas cercano (evita recompilar en inferencia)}cfg_path = os.path.join(model_dir, "model_config.json")if os.path.exists(cfg_path):1 unmodified linecfg.update(json.load(f))self.max_pbits = cfg["max_pbits"]self.max_cost = cfg["max_cost"]self.k = cfg["k"]self._bucket = cfg["bucket_to_warmup"]self._warm = sorted(int(w) for w in cfg["warmup_pbits"])adder = BitCell(cfg["hidden"], k=self.k)sub = BitCell(cfg["hidden"], k=self.k)adder.load_state_dict(torch.load(os.path.join(model_dir, "adder.pt"), map_location=self.device,weights_only=True))sub.load_state_dict(torch.load(os.path.join(model_dir, "subtractor.pt"), map_location=self.device, weights_only=True))adder.to(self.device).eval(); sub.to(self.device).eval()torch.set_num_threads(4) # condiciones del sandboxself.pipe = ExactPipeline(adder, sub, self.device, k=self.k,use_compile=cfg["use_compile"],compile_min_width=cfg["compile_min_width"])# COMPILA AHORA (fuera del presupuesto). Sin esto, el primer tier caro pagaria# la compilacion (decenas de s) dentro de los 300s.self.pipe.warmup(self._warm)def preprocess_a(self, a: str):return _bits_lsb_first(a)5 unmodified linesbits = _bits_lsb_first(p)return {"bits": bits, "out_len": len(bits)}def _bucket_width(self, W: int) -> int:if self._bucket:for w in self._warm: # menor warm >= Wif w >= W:return wreturn W # sin warm mayor: usa W (puede compilar 1 vez)def predict_digits(self, a_enc, b_enc, p_enc) -> list[int]:return self.predict_digits_batch([(a_enc, b_enc, p_enc)])[0]10 unmodified linesif W_true > self.max_pbits or (La + Lb) * W_true > self.max_cost:return [[0] * n for n in out_lens]W = self._bucket_width(W_true) # padding a ancho warm (mod p inalterado)n = len(inputs)dev = self.deviceP = torch.tensor([pb + [0] * (W - len(pb)) for pb in p_bits],dtype=torch.float32, device=dev)8 unmodified linesA = msb_matrix(a_enc, La)B = msb_matrix(b_enc, Lb)R = self.pipe.modmul(A, B, P)results = []for i, k in enumerate(out_lens):123456789106 unmodified lines171819202122232425262 unmodified lines293031323334353637383940414243444546477 unmodified lines5556575859606162636465661 unmodified line6869707172737475767778798081828384858687888990919293945 unmodified lines10010110210310410510 unmodified lines1161171181191201211228 unmodified lines131132133134135136137138"""Submission model — (a*b) mod p exact via learned cells composed by aparallel-prefix scan.RULES: no arithmetic shortcuts on the original values. The answer is produced byforward passes of trained cells that compose an exact modular addition; the scantopology and the Horner recurrence are fixed data routing / architecture. Eachpreprocessing hook sees only its own argument."""from __future__ import annotations6 unmodified linesimport torchtorch.set_num_threads(4)torch.set_num_interop_threads(4)torch.backends.cudnn.deterministic = Truetorch.backends.cudnn.benchmark = Falsetry:from modchallenge.interface.base_model import ModularMultiplicationModel2 unmodified linesclass ModularMultiplicationModel(ABC): # type: ignorepassimport sys_HERE = os.path.dirname(os.path.abspath(__file__))if _HERE not in sys.path:sys.path.insert(0, _HERE)try:from modeling.pp_pipeline import BitCell, CombineCell, PPPipelineexcept ModuleNotFoundError: # repo aplanado: fichero junto a model.pyfrom pp_pipeline import BitCell, CombineCell, PPPipelineOUTPUT_BASE = 2MAX_PBITS = 2048MAX_COST = 20000000def _bits_lsb_first(x_str: str) -> list[int]:7 unmodified linesclass MyModel(ModularMultiplicationModel):def load(self, model_dir: str) -> None:torch.manual_seed(0)cfg = {"hidden": 32,"max_pbits": MAX_PBITS,"max_cost": MAX_COST,"device": "auto","use_bf16": False,}cfg_path = os.path.join(model_dir, "model_config.json")if os.path.exists(cfg_path):1 unmodified linecfg.update(json.load(f))self.max_pbits = cfg["max_pbits"]self.max_cost = cfg["max_cost"]if cfg["device"] == "auto":self.device = "cuda" if torch.cuda.is_available() else "cpu"else:self.device = cfg["device"]adder = BitCell(cfg["hidden"])sub = BitCell(cfg["hidden"])comb = CombineCell(cfg["hidden"])adder.load_state_dict(torch.load(os.path.join(model_dir, "adder.pt"),map_location="cpu", weights_only=True))sub.load_state_dict(torch.load(os.path.join(model_dir, "subtractor.pt"),map_location="cpu", weights_only=True))comb.load_state_dict(torch.load(os.path.join(model_dir, "combine.pt"),map_location="cpu", weights_only=True))adder.to(self.device).eval()sub.to(self.device).eval()comb.to(self.device).eval()self.pipe = PPPipeline(adder, sub, comb, self.device,use_bf16=cfg.get("use_bf16", False))def preprocess_a(self, a: str):return _bits_lsb_first(a)5 unmodified linesbits = _bits_lsb_first(p)return {"bits": bits, "out_len": len(bits)}def predict_digits(self, a_enc, b_enc, p_enc) -> list[int]:return self.predict_digits_batch([(a_enc, b_enc, p_enc)])[0]10 unmodified linesif W_true > self.max_pbits or (La + Lb) * W_true > self.max_cost:return [[0] * n for n in out_lens]W = W_truedev = self.deviceP = torch.tensor([pb + [0] * (W - len(pb)) for pb in p_bits],dtype=torch.float32, device=dev)8 unmodified linesA = msb_matrix(a_enc, La)B = msb_matrix(b_enc, Lb)R = self.pipe.modmul(A, B, P)if R.device.type != "cpu":R = R.cpu()results = []for i, k in enumerate(out_lens):
README.md+95-31
model.py+50-52