Upload README.md
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116# 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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112# mac-1 β exact (aΒ·b) mod p via a learned bit-serial pipelineNeural model for the SAIR Modular Arithmetic Challenge (team MAC01-T00088).Computes `(a Β· b) mod p` exactly, for a prime modulus `p`, across operand sizesup to several thousand bits. The result is produced entirely by forward passesof two trained neural cells; the harness decoder performs base conversion only.## Results (official playground environment)Full 1100-case evaluation: **tiers 1β9 at 100% each** (frontier tier T9),completing in **211.8 s** of the 300-second budget. Deterministic acrossre-runs (identical per-tier counts).**This submission executes entirely on CPU by design** (`device` is fixed to`cpu`): the bit-serial pipeline's narrow, sequential operation profile ismatched to CPU execution, and the measured result above requires no GPU. (Theparallel-prefix sibling model, mac-2-hard, is the GPU-shaped design.)Problems outside the configured operating range β Tier-0 diagnostics andTier-10 problems above the cost ceiling β are answered with `[0]` withoutrunning the network, to protect the global time budget (see Configuration).## How it computes**Cells (`adder`, `subtractor`).**Each cell is an MLP `Linear(2k+1 β h) β ReLU β Linear(h β h) β ReLU βLinear(h β k+1)`. For `k = 1` the inputs are three bits and the outputs two(a full-adder / full-subtractor). A cell is a finite function of its inputs:there are only `2^(2k+1)` possible input combinations, and each cell istrained exhaustively over its entire truth table until exact match on everyrow. Because a cell is exact on all input combinations and is applied per bit(independently of total operand width), the composed pipeline is exact at anywidth.**Composition (fixed architecture).**- `addmod(r, s, p) = (r + s) mod p`. A bit-serial carry chain (the `adder`cell) forms `r + s`; a bit-serial borrow chain (the `subtractor` cell) forms`(r + s) β p`; the in-range value is selected from the two by the finalborrow. All intermediate values stay in `[0, p)`.- `modmul(a, b, p)`. `b` is reduced modulo `p` by a Horner-style recurrenceover its bits (`r β (2r + b_i) mod p`); the product is then formed by adouble-and-add recurrence over the bits of `a` (`r β 2r`, and conditionally`r β (r + b) mod p`). The final `r` equals `(a Β· b) mod p`.The recurrence is what scales with input size; the arithmetic performed ateach step is neural. The loop feeds operand bits on a fixed, predeterminedschedule and receives no feedback from the model β a plain deterministicencoder in the sense of the challenge rules. The model receives raw`(a, b, p)`: the only Python-level numeric operation is bit extraction in theper-argument preprocessing hooks, and all reduction of the full-width operandsis produced by the trained cells. No closed-form modular arithmetic(Montgomery, Barrett, or Python's `%`) is used anywhere in the forward path.## Exactness and determinism- **Exact.** Cells are verified against their full truth tables (inter-cellthresholding keeps all inputs binary, so the truth tables are the entirereachable input space); the end-to-end pipeline is checked for exact matchagainst ground truth at increasing operand widths. Exactness iswidth-invariant by construction, and verified end-to-end includingpower-of-two-adjacent operands (2^k, 2^kΒ±1) and Mersenne moduli.- **Deterministic.** Fixed seed; cell outputs are thresholded(`sigmoid > 0.5`), so identical inputs yield identical outputs across runs;thread counts are capped explicitly.- Passes the official static check.## 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.## Interface- Entry point: `model.MyModel`. Output base: 2.- Preprocessing converts each input independently to its bit representation(each preprocessing hook sees only its own argument).- Inference is batched (`predict_digits_batch`).## Configuration (`model_config.json`)- `hidden` β cell hidden width.- `k` β radix. `k = 1` uses one-bit cells; `k > 1` processes `k` bits perstep, shortening the recurrence (this submission uses `k = 6`).- `max_pbits`, `max_cost` β budget guard. Inputs whose modulus width orestimated cost exceed these thresholds are skipped (fast `[0]` output), toprotect the global time budget against the most expensive inputs.- `device` β fixed to `cpu` in this submission (see Results).- `use_compile`, `compile_min_width`, `warmup_pbits`, `bucket_to_warmup` βoptional execution settings. Compilation is disabled in this submission, soinference runs in plain eager mode (no code is generated at runtime).Missing `model_config.json` falls back to the submission defaults above.## Files- `model.py` β submission entry point and I/O.- `modeling/bitserial.py` β the cells and the exact modular-multiplicationpipeline.- `adder.pt`, `subtractor.pt` β trained cell weights.- `model_config.json` β configuration.## TrainingThe cell weights are obtained by training each MLP from random initializationon the complete truth table of its target function (one-bit or *k*-bitadd / subtract) until exact match on all `2^(2k+1)` rows. No data beyond theexhaustive table is used; because the target is a finite function,generalization beyond the table is not required. The training tooling is keptin a separate development repository and is not part of this submission.
README.md+107-111