File size: 5,358 Bytes
640348a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76b01d5
 
 
 
 
 
 
 
 
 
 
640348a
 
 
 
 
 
 
 
76b01d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
640348a
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
"""Submission model — (a*b) mod p exact via learned cells composed by a
carry-save interleaved Horner recurrence.

RULES: no arithmetic shortcuts on the original values. The answer is produced by
forward passes of two trained cells applied elementwise; shifts and the Horner
recurrence are fixed data routing / architecture, with no feedback into the
encoder. Each preprocessing hook sees only its own argument.
"""

from __future__ import annotations
import json
import 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)
torch.set_num_interop_threads(4)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False

try:
    from modchallenge.interface.base_model import ModularMultiplicationModel
except Exception:
    from abc import ABC
    class ModularMultiplicationModel(ABC):  # type: ignore
        pass

import sys
_HERE = os.path.dirname(os.path.abspath(__file__))
if _HERE not in sys.path:
    sys.path.insert(0, _HERE)

try:
    from modeling.cs_pipeline import BitCell, CSPipeline
except ModuleNotFoundError:          # repo aplanado: fichero junto a model.py
    from cs_pipeline import BitCell, CSPipeline

OUTPUT_BASE = 2
MAX_PBITS = 2048
MAX_COST = 20000000


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)
        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"])
        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))
        adder.to(self.device).eval()
        sub.to(self.device).eval()

        self.pipe = CSPipeline(adder, sub, 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]
        dev = self.device
        n_all = len(inputs)
        results: list[list[int] | None] = [None] * n_all

        # SUB-BATCHING POR ANCHO DE PRIMO (ruteo por input): agrupa filas por
        # bit-length de p y procesa cada grupo homogeneo por separado. Motivo:
        # el coste del setup de K y de la reduccion final escala con el spread
        # de anchos del batch; los batches por-tier son homogeneos, pero el
        # determinism check del runner mezcla tiers en un solo batch.
        groups: dict[int, list[int]] = {}
        for i, pb in enumerate(p_bits):
            groups.setdefault(len(pb), []).append(i)

        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)

        for W_true, idxs in sorted(groups.items()):
            La = max(len(a_enc[i]) for i in idxs)
            Lb = max(len(b_enc[i]) for i in idxs)
            if W_true > self.max_pbits or (La + Lb) * W_true > self.max_cost:
                for i in idxs:
                    results[i] = [0] * out_lens[i]
                continue
            W = W_true + 2                 # margen carry-save (delta = 2)
            P = torch.tensor([p_bits[i] + [0] * (W - len(p_bits[i])) for i in idxs],
                             dtype=torch.float32, device=dev)
            A = msb_matrix([a_enc[i] for i in idxs], La)
            B = msb_matrix([b_enc[i] for i in idxs], Lb)
            R = self.pipe.modmul(A, B, P)
            if R.device.type != "cpu":
                R = R.cpu()
            for j, i in enumerate(idxs):
                k = out_lens[i]
                bits_lsb = [int(x) for x in R[j, :k].tolist()]
                results[i] = bits_lsb[::-1]
        return results

    def max_batch_size(self) -> int:
        return 256