Upload 7 files
Browse filesFiles changed (7)
- README.mdAdded+95
- adder.ptAdded+3
- manifest.jsonAdded+7
- model.pyAdded+146
- model_config.jsonAdded+1
- modeling/bitserial.pyAdded+132
- subtractor.ptAdded+3
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495# Modular Multiplication Model
Computes `(a · b) mod p` exactly, for a prime modulus `p` and integers`a, b ∈ [0, p)`, across operand sizes up to several thousand bits.
## Summary
The result is produced entirely by forward passes of two trained neural cells.Each cell is a small MLP trained to compute a fixed-width (one-bit, or *k*-bit inthe radix-2^k variants) addition or subtraction. A fixed recurrence composesrepeated cell evaluations into modular addition, and modular addition intomodular multiplication.
No arithmetic is performed in Python on the operand values: Python supplies onlycontrol flow — which cell to evaluate, and in what order — while everyvalue-carrying operation is a cell forward pass. Structurally, the model is arecurrent network unrolled over the bits of its inputs, with the recurrencedepth scaling with operand size (the cells share weights across steps).
## 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 the default `k = 1` the inputs are three bits and the outputs are two(a full-adder / a full-subtractor). A cell is a finite function of its inputs:there are only `2^(2k+1)` possible input combinations. Each cell is trainedexhaustively over its entire truth table until it reaches exact match on everyrow. Because a cell is exact on all input combinations and is applied per bit(independently of the total operand width), the composed pipeline is exact atany width.
**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 final borrow. All intermediate values stay in `[0, p)`.- `modmul(a, b, p)`. `b` is reduced modulo `p` by a Horner-style recurrence over its bits (`r ← (2r + b_i) mod p`); the product is then formed by a double-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 at eachstep is neural. No integer arithmetic is performed on the original operands `a`,`b`, `p` during inference: the only Python-level numeric operation is bitextraction in the preprocessing hooks. All additions, subtractions, and modularreductions are delegated to the trained cells, and no closed-form modulararithmetic (Montgomery, Barrett, or Python's `%`) is used.
## Exactness and determinism
- **Exact.** Cells are verified against their full truth tables; the end-to-end pipeline is checked for exact match against ground truth at increasing operand widths. Exactness is width-invariant by construction.- **Deterministic.** Fixed seed; cell outputs are thresholded (`sigmoid > 0.5`), so identical inputs yield identical outputs across runs.- Passes the official static check.
## 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 per step, shortening the recurrence.- `max_pbits`, `max_cost` — budget guard. Inputs whose modulus width or estimated cost exceed these thresholds are skipped (fast zero output), to protect the global time budget against the most expensive inputs (e.g. very large operands that would otherwise exhaust the allotted time).- `use_compile`, `compile_min_width`, `warmup_pbits`, `bucket_to_warmup` — optional execution settings. Compilation is disabled in this submission, so inference runs in plain eager mode (no code is generated at runtime).
## Files
- `model.py` — submission entry point and I/O.- `modeling/bitserial.py` — the cells and the exact modular-multiplication pipeline.- `adder.pt`, `subtractor.pt` — trained cell weights.- `model_config.json` — configuration.
The cell weights are trained offline over their complete truth tables; thetraining tooling is kept in a separate development repository and is not part ofthis submission.
## Training
The cell weights are obtained by training each MLP on the complete truth table ofits target function (one-bit or *k*-bit add / subtract) until exact match on all`2^(2k+1)` rows. No data beyond the exhaustive table is used; because the targetis a finite function, generalization beyond the table is not required.123version https://git-lfs.github.com/spec/v1oid sha256:eab5102b537a77803799f1d613345a3db31b2f8868505996adc844c51fa878e2size 101131234567{ "entry_class": "model.MyModel", "output_base": 2, "framework": "pytorch", "model_description": "Recurrent model that computes (a*b) mod p exactly. Two trained MLP cells (a full-adder and a full-subtractor in radix-2^k form (k=6); input 2k+1, hidden 32, output k+1, ReLU activations; ~a few thousand parameters each) are composed by a fixed recurrence into modular addition, and modular addition into modular multiplication (Horner reduction of b, then double-and-add over the bits of a). Inputs a, b, p are taken as bit vectors; the answer is emitted as base-2 digits, MSB-first. Every value-carrying operation is a forward pass of a trained cell; the recurrence depth scales with operand width, analogous to an RNN unrolled over the input bits.", "training_description": "Each cell is trained by gradient descent (Adam, BCE loss) on the complete truth table of its target k-bit function: all 2^(2k+1) input combinations, optimized to exact match on every row. No data beyond the exhaustive table is used and no generalization is required, since the target is a finite function. Weights are obtained entirely by this training, not hand-initialized. With randomly initialized cell weights the model's exact-match accuracy is 0%; the exactness resides entirely in the trained parameters."}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146"""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 baratos corren eager (no compensa el coste de compilar grafos pequenos)."""
from __future__ import annotationsimport jsonimport os
os.environ["OMP_NUM_THREADS"] = "4"os.environ["MKL_NUM_THREADS"] = "4"os.environ["OPENBLAS_NUM_THREADS"] = "4"
import torch
torch.set_num_threads(4) # condiciones del sandboxtorch.set_num_interop_threads(4)
try: from modchallenge.interface.base_model import ModularMultiplicationModelexcept Exception: from abc import ABC class ModularMultiplicationModel(ABC): # type: ignore pass
from modeling.bitserial import BitCell, ExactPipeline, to_bits_lsb
OUTPUT_BASE = 2MAX_PBITS = 1024MAX_COST = 5000000
def _bits_lsb_first(x_str: str) -> list[int]: x = int(x_str) out = [] while x: out.append(x & 1); x >>= 1 return out or [0]
class 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): with open(cfg_path) as f: cfg.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 sandbox self.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)
def preprocess_b(self, b: str): return _bits_lsb_first(b)
def preprocess_p(self, p: str): bits = _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 >= W if w >= W: return w return 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]
@torch.no_grad() def predict_digits_batch(self, inputs): out_lens = [p_enc["out_len"] for _, _, p_enc in inputs] p_bits = [p_enc["bits"] for _, _, p_enc in inputs] a_enc = [a for a, _, _ in inputs] b_enc = [b for _, b, _ in inputs] W_true = max(len(pb) for pb in p_bits) La = max(len(a) for a in a_enc) Lb = max(len(b) for b in b_enc)
if 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.device P = torch.tensor([pb + [0] * (W - len(pb)) for pb in p_bits], dtype=torch.float32, device=dev)
def msb_matrix(seqs, L): rows = [] for s in seqs: msb = s[::-1] rows.append([0] * (L - len(msb)) + msb) return torch.tensor(rows, dtype=torch.float32, device=dev)
A = 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): bits_lsb = [int(x) for x in R[i, :k].tolist()] results.append(bits_lsb[::-1]) return results
def max_batch_size(self) -> int: return 2561{"hidden": 32, "max_pbits": 1024, "max_cost": 5000000,"k":6,"use_compile":false,"bucket_to_warmup": false,"debug_tiers":false}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132"""Multiplicacion modular EXACTA bit-serial — modulo self-contained de la submission.
(a*b) mod p SIN formar el producto y SIN aritmetica de Python sobre los valores:celdas de 1 bit (o de k bits, radix-2^k) APRENDIDAS (full-adder + full-subtractor)componen una suma modular exacta g(r,s,p)=(r+s) mod p, y con ella todo el pipeline.La exactitud y la invariancia al ancho vienen de que las celdas son funciones finitasaprendidas; la recurrencia/localidad de bit es arquitectura (permitida).
Cambios vs version base: * BitCell parametrizada por k. k=1 == celda original (in=3,out=2): carga tus .pt. * addmod/modmul radix-2^k: procesan k bits por paso -> cadena ~Wi/k (menos pasos secuenciales y, al compilar, grafo ~k veces menor -> compila mucho mas rapido). * torch.compile selectivo del addmod (fusiona el bucle de acarreo, ataca el overhead de dispatch que es el cuello en CPU). Una compilacion por W; el batch se marca dinamico (cambiar N no recompila). La compilacion ocurre en warmup() (en load()), nunca dentro del presupuesto de inferencia."""
from __future__ import annotationsimport torchimport torch.nn as nn
def to_bits_lsb(x: int, width: int) -> list[int]: return [(x >> i) & 1 for i in range(width)]
def from_bits_lsb(bits) -> int: v = 0 for i, b in enumerate(bits): if b: v |= (1 << i) return v
class BitCell(nn.Module): """Celda radix-2^k. k=1 -> (in=3,out=2) identica a la original. add: f(k bits r, k bits s, carry_in) -> (k bits sum, carry_out) sub: f(k bits a, k bits b, borrow_in) -> (k bits diff, borrow_out) """ def __init__(self, hidden: int = 32, k: int = 1): super().__init__() self.k = k self.net = nn.Sequential( nn.Linear(2 * k + 1, hidden), nn.ReLU(), nn.Linear(hidden, hidden), nn.ReLU(), nn.Linear(hidden, k + 1), )
def forward(self, x): return self.net(x)
class ExactPipeline: def __init__(self, adder: BitCell, sub: BitCell, device: str, k: int = 1, use_compile: bool = True, compile_min_width: int = 96): self.adder, self.sub, self.device = adder, sub, device self.k = k self.use_compile = use_compile self.compile_min_width = compile_min_width # bajo esto, eager (no vale el coste de compilar) self._addmod_c = (torch.compile(self._addmod_impl, dynamic=False, fullgraph=True) if use_compile else None)
# -- nucleo: (r+s) mod p exacto, radix-2^k (k=1 == bit-serial original) ---- @torch.no_grad() def _addmod_impl(self, r, s, p): k = self.k N, W = r.shape dev = r.device Wi = W + 1 # r+s < 2p cabe en W+1 bits pad = (-Wi) % k Wp = Wi + pad # multiplo de k z = torch.zeros(N, Wp - W, device=dev) r = torch.cat([r, z], -1); s = torch.cat([s, z], -1); p = torch.cat([p, z], -1) nch = Wp // k # suma (cadena de acarreo, k bits por paso) carry = torch.zeros(N, 1, device=dev); summ = [] for ch in range(nch): sl = slice(ch * k, ch * k + k) o = (torch.sigmoid(self.adder(torch.cat([r[:, sl], s[:, sl], carry], -1))) > 0.5).float() summ.append(o[:, :k]); carry = o[:, k:k + 1] summ = torch.cat(summ, -1) # resta sum - p (cadena de prestamo); borrow final=1 => sum<p borrow = torch.zeros(N, 1, device=dev); diff = [] for ch in range(nch): sl = slice(ch * k, ch * k + k) o = (torch.sigmoid(self.sub(torch.cat([summ[:, sl], p[:, sl], borrow], -1))) > 0.5).float() diff.append(o[:, :k]); borrow = o[:, k:k + 1] diff = torch.cat(diff, -1) res = torch.where(borrow > 0.5, summ, diff) return res[:, :W]
def addmod(self, r, s, p): W = r.shape[1] if self.use_compile and W >= self.compile_min_width: # batch dinamico (N varia sin recompilar); W estatico (desenrolla el bucle) torch._dynamo.mark_dynamic(r, 0) torch._dynamo.mark_dynamic(s, 0) torch._dynamo.mark_dynamic(p, 0) return self._addmod_c(r, s, p) return self._addmod_impl(r, s, p)
def warmup(self, widths, n: int = 2): """Fuerza la compilacion (coste alto) FUERA del presupuesto, en load(). Pasa los W que de verdad vas a computar (los p_bits de cada tier <= max_pbits). """ if not self.use_compile: return for W in sorted(set(int(w) for w in widths)): if W < self.compile_min_width: continue d = torch.zeros(n, W, device=self.device) self.addmod(d, d, d)
@torch.no_grad() def modmul(self, a_msb, b_msb, P): """(a*b) mod p. a_msb/b_msb: (N,La)/(N,Lb) MSB-first. P: (N,W). -> (N,W) LSB-first.""" N, W = P.shape dev = P.device r = torch.zeros(N, W, device=dev) for j in range(b_msb.shape[1]): bit = torch.zeros(N, W, device=dev); bit[:, 0] = b_msb[:, j] r = self.addmod(r, r, P) # 2r r = self.addmod(r, bit, P) # + b_i b_red = r r = torch.zeros(N, W, device=dev) for j in range(a_msb.shape[1]): ai = a_msb[:, j:j + 1] r = self.addmod(r, r, P) # 2r added = self.addmod(r, b_red, P) # r + b_red r = torch.where(ai > 0.5, added, r) # condicional segun bit de a return r123version https://git-lfs.github.com/spec/v1oid sha256:9feb4f46cc2f23cd99a15579afc8f7516cf3bfdd081267f14b83e6a45b398bdfsize 10173README.mdAdded+95
adder.ptAdded+3
manifest.jsonAdded+7
model.pyAdded+146
model_config.jsonAdded+1
modeling/bitserial.pyAdded+132
subtractor.ptAdded+3