Upload model.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144"""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 annotationsimport jsonimport osos.environ["OMP_NUM_THREADS"] = "4"os.environ["MKL_NUM_THREADS"] = "4"os.environ["OPENBLAS_NUM_THREADS"] = "4"import 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 ModularMultiplicationModelexcept Exception:from abc import ABCclass 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]:x = int(x_str)out = []while x:out.append(x & 1); x >>= 1return out or [0]class 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):with open(cfg_path) as f:cfg.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)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 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 = W_truedev = self.deviceP = 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)if R.device.type != "cpu":R = R.cpu()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 resultsdef max_batch_size(self) -> int:return 256123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152"""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 annotationsimport jsonimport osos.environ["OMP_NUM_THREADS"] = "4"os.environ["MKL_NUM_THREADS"] = "4"os.environ["OPENBLAS_NUM_THREADS"] = "4"import torchtorch.set_num_threads(4) # condiciones del sandboxtorch.set_num_interop_threads(4)try:from modchallenge.interface.base_model import ModularMultiplicationModelexcept Exception:from abc import ABCclass ModularMultiplicationModel(ABC): # type: ignorepassimport sys_HERE = os.path.dirname(os.path.abspath(__file__))if _HERE not in sys.path:sys.path.insert(0, _HERE)from modeling.bitserial import BitCell, ExactPipeline, to_bits_lsbOUTPUT_BASE = 2MAX_PBITS = 1024MAX_COST = 5000000def _bits_lsb_first(x_str: str) -> list[int]:x = int(x_str)out = []while x:out.append(x & 1); x >>= 1return 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 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)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 >= 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]@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.deviceP = 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 resultsdef max_batch_size(self) -> int:return 256
model.py+152-144