bit-serial learned reducer
Browse files- README.md +5 -0
- manifest.json +7 -0
- model.py +208 -0
- weights.pt +3 -0
README.md
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# bitserial-modmul-v2
|
| 2 |
+
|
| 3 |
+
Submission for the SAIR Modular Arithmetic Challenge. 32-bit cell, tiers 1-4 (overall 0.412). Runs on CPU/Mac. Smaller/faster variant for testing.
|
| 4 |
+
|
| 5 |
+
One shared, p-conditioned recurrent cell in a fixed bit-serial Horner loop computes (a * b) mod p; the cell learns the per-step transition s' = (2s + d*x) mod p (including the modular wrap) and the loop only sequences bits. Randomising the weights collapses accuracy to 0 (the capability is in the trained parameters). entry_class model.BitSerialReducer, output_base 2.
|
manifest.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"entry_class": "model.BitSerialReducer",
|
| 3 |
+
"output_base": 2,
|
| 4 |
+
"framework": "pytorch",
|
| 5 |
+
"model_description": "One shared, p-conditioned recurrent transition cell (~471K parameters: a bidirectional 2-layer GRU over three bit-channels, a control-bit embedding, and a per-bit output head) applied in a fixed bit-serial loop, at 32-bit state width. Inputs: each operand is tokenised per-argument into its MSB-first bit list; the modulus is fed as its 32-bit binary form. The cell maps (state_bits, multiplicand_bits, modulus_bits, control_bit) to the next state bits and is invoked three ways with the same weights: reduce a mod p, reduce b mod p (multiplicand fixed to 1), and the modular multiply of the two residues (multiplicand fixed to a mod p, control bits scanning b mod p). Output: base-2 digits, reconstructed by the harness decoder. State is carried as bits between steps, so no integer reconstruction or modular product happens in Python. Trained regime is primes below 2^32 and operands up to 96 bits (tiers 1-4); outside it the model abstains and emits a single zero. Same architecture as bit-serial-v1, widened from 16 to 32 bits.",
|
| 6 |
+
"training_description": "Trained from random initialisation. The single transition cell is fit to one-step transitions s' = (2*s + d*x) mod p sampled over moduli covering tiers 1-4 (modulus bit-length stratified across 1-32 bits so small primes get the same signal as the dense 32-bit band, wrap-boundary transitions oversampled). Objective is per-output-bit binary cross-entropy; optimiser AdamW (lr 2e-3, weight decay 0.01, gradient clipping), 10k steps of batch 384 on an Apple MPS device. No precomputed tables, no hand-coded reduction or multiplication: the per-step modular transition (including the conditional wrap, which is at most two subtractions of p since 2*s + d*x < 3*p) is what is learned; the loop only sequences the bits. The capability lives in the weights, so randomising them collapses exact-match accuracy to chance. Evaluation primes are unseen during training (tiers 2-4 use a secret seed)."
|
| 7 |
+
}
|
model.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bit-serial learned reducer for the Modular Arithmetic Challenge.
|
| 2 |
+
|
| 3 |
+
A single shared, p-conditioned transition cell, applied in a fixed bit loop,
|
| 4 |
+
computes ``(a * b) mod p``. The cell learns the per-step transition
|
| 5 |
+
|
| 6 |
+
s' = (2*s + d*x) mod p
|
| 7 |
+
|
| 8 |
+
(state ``s``, multiplicand ``x``, control bit ``d``, modulus ``p``). The Python
|
| 9 |
+
loop only sequences the bits most-significant-first (Horner form) -- the
|
| 10 |
+
explicitly-allowed recurrent / looped structure. No modular product is computed
|
| 11 |
+
in Python or in hand-coded tensor arithmetic: every reduction and the multiply
|
| 12 |
+
itself are produced by the trained cell. Randomising the weights collapses
|
| 13 |
+
accuracy to chance, which is the operational provenance test.
|
| 14 |
+
|
| 15 |
+
Pipeline per problem (a, b, p):
|
| 16 |
+
|
| 17 |
+
reduce(a) = scan bits of a MSB-first with x=1 -> a mod p
|
| 18 |
+
reduce(b) = scan bits of b MSB-first with x=1 -> b mod p
|
| 19 |
+
multiply = scan bits of (b mod p) MSB-first with x=(a mod p) -> (a*b) mod p
|
| 20 |
+
|
| 21 |
+
State is carried as bits between steps (no integer reconstruction inside the
|
| 22 |
+
loop); the harness decoder reconstructs the integer answer from the emitted
|
| 23 |
+
base-2 digits.
|
| 24 |
+
|
| 25 |
+
Regime: the cell is trained for primes ``p < 2^32`` and operands up to 96 bits
|
| 26 |
+
(tiers 1-4). Outside that regime the model abstains and emits ``[0]`` -- the
|
| 27 |
+
honest fallback -- rather than running the cell out of distribution.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
from __future__ import annotations
|
| 31 |
+
|
| 32 |
+
from pathlib import Path
|
| 33 |
+
|
| 34 |
+
import torch
|
| 35 |
+
from torch import nn
|
| 36 |
+
|
| 37 |
+
from modchallenge.interface.base_model import ModularMultiplicationModel
|
| 38 |
+
|
| 39 |
+
# State / modulus bit-width. Covers tiers 1-4: every prime there is < 2^32, and
|
| 40 |
+
# every residue is < p, so 32 bits hold both the state and the modulus features.
|
| 41 |
+
L = 32
|
| 42 |
+
# Tiers 1-4 operands are at most 96 bits. Beyond this we are out of regime.
|
| 43 |
+
MAX_OP_BITS = 96
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def to_bits(vals: torch.Tensor, width: int = L) -> torch.Tensor:
|
| 47 |
+
"""Small non-negative ints -> (N, width) bit tensor, MSB-first.
|
| 48 |
+
|
| 49 |
+
Used only on the modulus and the constant multiplicand x=1 (both small);
|
| 50 |
+
this is representation, not arithmetic on the operands.
|
| 51 |
+
"""
|
| 52 |
+
shifts = torch.arange(width - 1, -1, -1, device=vals.device)
|
| 53 |
+
return (vals[:, None] >> shifts[None, :]) & 1
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class Cell(nn.Module):
|
| 57 |
+
"""Shared per-step transition: (s_bits, x_bits, p_bits, d) -> next s_bits.
|
| 58 |
+
|
| 59 |
+
The three bit-channels are read as a length-L sequence by a bidirectional
|
| 60 |
+
GRU; the control bit d is injected as an embedding. The head emits one
|
| 61 |
+
logit per output bit position. The same weights are used for the reduce
|
| 62 |
+
steps (x=1) and the multiply steps (x = a mod p)."""
|
| 63 |
+
|
| 64 |
+
def __init__(self, dmodel: int = 96, hidden: int = 128):
|
| 65 |
+
super().__init__()
|
| 66 |
+
self.in_proj = nn.Linear(3, dmodel)
|
| 67 |
+
self.d_emb = nn.Embedding(2, dmodel)
|
| 68 |
+
self.gru = nn.GRU(
|
| 69 |
+
dmodel, hidden, num_layers=2, batch_first=True, bidirectional=True
|
| 70 |
+
)
|
| 71 |
+
self.head = nn.Linear(2 * hidden, 1)
|
| 72 |
+
|
| 73 |
+
def forward(self, feat: torch.Tensor, d: torch.Tensor) -> torch.Tensor:
|
| 74 |
+
x = self.in_proj(feat) + self.d_emb(d)[:, None, :]
|
| 75 |
+
h, _ = self.gru(x)
|
| 76 |
+
return self.head(h).squeeze(-1)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _bits_of(n: int) -> list[int]:
|
| 80 |
+
"""Non-negative int -> MSB-first bit list. Per-argument tokenisation."""
|
| 81 |
+
if n <= 0:
|
| 82 |
+
return [0]
|
| 83 |
+
out: list[int] = []
|
| 84 |
+
while n > 0:
|
| 85 |
+
out.append(n & 1)
|
| 86 |
+
n >>= 1
|
| 87 |
+
out.reverse()
|
| 88 |
+
return out
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class BitSerialReducer(ModularMultiplicationModel):
|
| 92 |
+
def __init__(self) -> None:
|
| 93 |
+
self.model: Cell | None = None
|
| 94 |
+
self.device: torch.device | None = None
|
| 95 |
+
|
| 96 |
+
# -- lifecycle ------------------------------------------------------
|
| 97 |
+
|
| 98 |
+
def load(self, model_dir: str) -> None:
|
| 99 |
+
if torch.backends.mps.is_available():
|
| 100 |
+
self.device = torch.device("mps")
|
| 101 |
+
elif torch.cuda.is_available():
|
| 102 |
+
self.device = torch.device("cuda")
|
| 103 |
+
else:
|
| 104 |
+
self.device = torch.device("cpu")
|
| 105 |
+
ckpt = torch.load(
|
| 106 |
+
Path(model_dir) / "weights.pt",
|
| 107 |
+
map_location=self.device,
|
| 108 |
+
weights_only=True,
|
| 109 |
+
)
|
| 110 |
+
self.model = Cell(**ckpt.get("config", {}))
|
| 111 |
+
self.model.load_state_dict(ckpt["state_dict"])
|
| 112 |
+
self.model.to(self.device)
|
| 113 |
+
self.model.eval()
|
| 114 |
+
|
| 115 |
+
# -- per-argument tokenisation (each hook sees only its own argument) --
|
| 116 |
+
|
| 117 |
+
def preprocess_a(self, a):
|
| 118 |
+
return _bits_of(int(a))
|
| 119 |
+
|
| 120 |
+
def preprocess_b(self, b):
|
| 121 |
+
return _bits_of(int(b))
|
| 122 |
+
|
| 123 |
+
def preprocess_p(self, p):
|
| 124 |
+
return int(p)
|
| 125 |
+
|
| 126 |
+
# -- inference ------------------------------------------------------
|
| 127 |
+
|
| 128 |
+
@torch.no_grad()
|
| 129 |
+
def predict_digits(self, a_enc, b_enc, p_enc):
|
| 130 |
+
return self.predict_digits_batch([(a_enc, b_enc, p_enc)])[0]
|
| 131 |
+
|
| 132 |
+
@torch.no_grad()
|
| 133 |
+
def predict_digits_batch(self, inputs):
|
| 134 |
+
out: list[list[int]] = [[0] for _ in inputs]
|
| 135 |
+
idx, a_lists, b_lists, p_vals = [], [], [], []
|
| 136 |
+
for i, (a_enc, b_enc, p_enc) in enumerate(inputs):
|
| 137 |
+
p = int(p_enc)
|
| 138 |
+
a_bits = list(a_enc)
|
| 139 |
+
b_bits = list(b_enc)
|
| 140 |
+
# Out of the trained regime (tiers 4+, or tier-0 giant operands):
|
| 141 |
+
# abstain instead of running the cell out of distribution.
|
| 142 |
+
if (
|
| 143 |
+
p < 2
|
| 144 |
+
or p >= (1 << L)
|
| 145 |
+
or len(a_bits) > MAX_OP_BITS
|
| 146 |
+
or len(b_bits) > MAX_OP_BITS
|
| 147 |
+
):
|
| 148 |
+
continue
|
| 149 |
+
idx.append(i)
|
| 150 |
+
a_lists.append(a_bits)
|
| 151 |
+
b_lists.append(b_bits)
|
| 152 |
+
p_vals.append(p)
|
| 153 |
+
|
| 154 |
+
if not idx:
|
| 155 |
+
return out
|
| 156 |
+
|
| 157 |
+
dev = self.device
|
| 158 |
+
p_bits = to_bits(torch.tensor(p_vals, device=dev)).float()
|
| 159 |
+
ra = self._reduce(a_lists, p_bits, dev) # (N, L) residue bits
|
| 160 |
+
rb = self._reduce(b_lists, p_bits, dev)
|
| 161 |
+
prod = self._mul(ra, rb, p_bits) # (N, L) answer bits
|
| 162 |
+
|
| 163 |
+
prod_list = prod.long().tolist()
|
| 164 |
+
for j, i in enumerate(idx):
|
| 165 |
+
out[i] = [int(x) for x in prod_list[j]]
|
| 166 |
+
return out
|
| 167 |
+
|
| 168 |
+
def max_batch_size(self) -> int:
|
| 169 |
+
return 256
|
| 170 |
+
|
| 171 |
+
# -- internals ------------------------------------------------------
|
| 172 |
+
|
| 173 |
+
def _step(self, s_bits, x_bits, p_bits, d):
|
| 174 |
+
feat = torch.stack([s_bits, x_bits, p_bits], dim=-1)
|
| 175 |
+
logits = self.model(feat, d)
|
| 176 |
+
return (torch.sigmoid(logits) > 0.5).float()
|
| 177 |
+
|
| 178 |
+
def _reduce(self, bit_lists, p_bits, dev):
|
| 179 |
+
"""Free-running Horner reduction of each operand to its residue mod p.
|
| 180 |
+
|
| 181 |
+
x is fixed to 1; the control bit at each step is the operand bit.
|
| 182 |
+
Leading zeros (from padding shorter operands to the batch width) keep
|
| 183 |
+
the state at 0, so padding is harmless."""
|
| 184 |
+
n = len(bit_lists)
|
| 185 |
+
width = max(len(b) for b in bit_lists)
|
| 186 |
+
padded = torch.zeros((n, width), dtype=torch.long, device=dev)
|
| 187 |
+
for r, bl in enumerate(bit_lists):
|
| 188 |
+
if bl:
|
| 189 |
+
padded[r, width - len(bl):] = torch.tensor(
|
| 190 |
+
bl, dtype=torch.long, device=dev
|
| 191 |
+
)
|
| 192 |
+
s_bits = torch.zeros((n, L), device=dev)
|
| 193 |
+
x_bits = to_bits(torch.ones(n, dtype=torch.long, device=dev)).float()
|
| 194 |
+
for pos in range(width): # MSB-first
|
| 195 |
+
s_bits = self._step(s_bits, x_bits, p_bits, padded[:, pos])
|
| 196 |
+
return s_bits
|
| 197 |
+
|
| 198 |
+
def _mul(self, ra_bits, rb_bits, p_bits):
|
| 199 |
+
"""(a mod p) * (b mod p) mod p via Horner over the residue's L bits.
|
| 200 |
+
|
| 201 |
+
x is fixed to (a mod p); the control bit at each step is a bit of
|
| 202 |
+
(b mod p), scanned MSB-first."""
|
| 203 |
+
n = ra_bits.shape[0]
|
| 204 |
+
s_bits = torch.zeros((n, L), device=ra_bits.device)
|
| 205 |
+
rb_long = rb_bits.long()
|
| 206 |
+
for k in range(L): # MSB-first over the 16-bit residue
|
| 207 |
+
s_bits = self._step(s_bits, ra_bits, p_bits, rb_long[:, k])
|
| 208 |
+
return s_bits
|
weights.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:92015d9c2aa4e3e9aa6eda9e33e50eb1848a723fd4d7f6a02168201437277450
|
| 3 |
+
size 1889623
|