HCho commited on
Commit
4fc906a
·
verified ·
1 Parent(s): 2b0da7b

BitStream Modular Machine - submission 1

Browse files
Files changed (9) hide show
  1. README.md +1 -0
  2. data.py +185 -0
  3. manifest.json +7 -0
  4. miner.py +168 -0
  5. model.py +282 -0
  6. perturb_test.py +114 -0
  7. train.py +346 -0
  8. verify.py +209 -0
  9. weights.pt +3 -0
README.md ADDED
@@ -0,0 +1 @@
 
 
1
+ 46k parameter rnn that computes a * b mod p.
data.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import random
4
+
5
+ import numpy as np
6
+ import torch
7
+
8
+ PAD_HEAD = 3
9
+
10
+
11
+ def _rand_bits_int(rng: random.Random, l: int) -> int:
12
+ if l == 1:
13
+ return 1
14
+ return (1 << (l - 1)) | rng.getrandbits(l - 1)
15
+
16
+
17
+ def sample_modulus(rng: random.Random, n: int) -> int:
18
+ lmax = n - PAD_HEAD
19
+ r = rng.random()
20
+ if r < 0.50:
21
+ l = lmax
22
+ elif r < 0.80:
23
+ l = rng.randint(2, lmax)
24
+ else:
25
+ l = min(lmax, 1 + int(2 ** (rng.random() * 4)))
26
+ l = max(2, l)
27
+ if l <= 3 and rng.random() < 0.7:
28
+ return rng.choice([2, 3, 5, 7][: 2 if l == 2 else 4])
29
+ if l >= 5 and rng.random() < 0.15:
30
+ c = rng.choice([1, 3, 5, 7, 9, 15, 17, 31, 33, 63, rng.randint(1, 99)])
31
+ if rng.random() < 0.7:
32
+ m = (1 << l) - c
33
+ else:
34
+ m = (1 << (l - 1)) + c
35
+ if rng.random() < 0.9:
36
+ m |= 1
37
+ if 2 <= m and m.bit_length() <= l:
38
+ return m
39
+ m = _rand_bits_int(rng, l)
40
+ if rng.random() < 0.75:
41
+ m |= 1
42
+ return max(2, m)
43
+
44
+
45
+ def _carry_stress(rng: random.Random, hi: int) -> int:
46
+ nbits = max(2, hi.bit_length())
47
+ j = rng.randint(1, nbits)
48
+ i = rng.randint(0, j - 1)
49
+ v = (1 << j) - (1 << i)
50
+ if rng.random() < 0.5:
51
+ v |= rng.getrandbits(max(1, i))
52
+ return v % hi
53
+
54
+
55
+ def _sample_x(rng: random.Random, m: int, hi_mult: int, w: int) -> int:
56
+ hi = hi_mult * m
57
+ r = rng.random()
58
+ if r < 0.40:
59
+ for _ in range(8):
60
+ q = rng.randint(0, hi_mult)
61
+ lo_s = max(q * m, w)
62
+ hi_s = min((q + 1) * m, hi + w)
63
+ if lo_s < hi_s:
64
+ x = rng.randrange(lo_s, hi_s) - w
65
+ if 0 <= x < hi:
66
+ return x
67
+ return rng.randrange(hi)
68
+ if r < 0.50:
69
+ return rng.randrange(hi)
70
+ if r < 0.58:
71
+ u = rng.randrange(m)
72
+ d = rng.randrange(hi_mult)
73
+ return min(hi - 1, hi_mult * u + d)
74
+ if r < 0.64:
75
+ return rng.randrange(m)
76
+ if r < 0.78:
77
+ k = rng.randint(1, hi_mult)
78
+ delta = rng.choice([0, 1, 2, 3, rng.randint(0, 8)])
79
+ s_t = k * m + (delta if rng.random() < 0.5 else -delta)
80
+ x = s_t - w
81
+ return x if 0 <= x < hi else rng.randrange(hi)
82
+ if r < 0.96:
83
+ if rng.random() < 0.5:
84
+ x = _carry_stress(rng, hi)
85
+ else:
86
+ k = rng.randint(1, hi_mult)
87
+ x = k * m - w + (1 << rng.randint(0, max(1, hi.bit_length() - 2))) \
88
+ - rng.randint(0, 3)
89
+ if not (0 <= x < hi):
90
+ x = _carry_stress(rng, hi)
91
+ return x
92
+ return rng.choice([0, 1, 2, 3])
93
+
94
+
95
+ def sample_reduce(rng: random.Random, n: int) -> tuple[int, int]:
96
+ m = sample_modulus(rng, n)
97
+ return m, _sample_x(rng, m, 4, 0)
98
+
99
+
100
+
101
+
102
+ def _pack_bits(vals: list[int], n: int) -> np.ndarray:
103
+ out = np.empty((len(vals), n), dtype=np.uint8)
104
+ for i, v in enumerate(vals):
105
+ s = np.frombuffer(format(v, f"0{n}b").encode(), dtype=np.uint8)
106
+ out[i] = s - 48
107
+ return out
108
+
109
+
110
+ def _T(vals, n):
111
+ return torch.from_numpy(_pack_bits(vals, n)).float()
112
+
113
+
114
+ def make_reduce_batch(rng, n, bsz, instances=None):
115
+ mask = (1 << n) - 1
116
+ ms, xs, zs, qs, p3s = [], [], [], [], []
117
+ borrows = [[], [], []]
118
+ for j in range(bsz):
119
+ if instances is not None:
120
+ m, x = instances[j % len(instances)]
121
+ else:
122
+ m, x = sample_reduce(rng, n)
123
+ q = x // m
124
+ zs.append(x - q * m)
125
+ qs.append(q)
126
+ for k in (1, 2, 3):
127
+ km = k * m
128
+ diff = (x - km) & mask
129
+ borrows[k - 1].append((x ^ km ^ diff) & mask)
130
+ ms.append(m); xs.append(x); p3s.append(3 * m)
131
+ batch = {
132
+ "x": _T(xs, n), "p": _T(ms, n), "p3": _T(p3s, n),
133
+ "z": _T(zs, n),
134
+ "borrow": torch.stack([_T(borrows[k], n) for k in range(3)], dim=-1),
135
+ "q": torch.tensor(qs, dtype=torch.long),
136
+ "raw": list(zip(ms, xs)),
137
+ }
138
+ return batch
139
+
140
+
141
+ def sample_add(rng: random.Random, n: int) -> tuple[int, int, int]:
142
+ r = rng.random()
143
+ if r < 0.45:
144
+ x = rng.getrandbits(rng.randint(1, n - 2)) if rng.random() < 0.5 \
145
+ else rng.randrange(1 << (n - 2))
146
+ elif r < 0.85:
147
+ x = _carry_stress(rng, 1 << (n - 2))
148
+ elif r < 0.95:
149
+ x = rng.choice([0, 1, 2, 3])
150
+ else:
151
+ x = (1 << (n - 2)) - rng.randint(1, 4)
152
+ if rng.random() < 0.7:
153
+ x &= ~1
154
+ r = rng.random()
155
+ if r < 0.5:
156
+ y = rng.getrandbits(rng.randint(1, n - 3)) if rng.random() < 0.5 \
157
+ else rng.randrange(1 << (n - 3))
158
+ elif r < 0.9:
159
+ y = _carry_stress(rng, 1 << (n - 3))
160
+ else:
161
+ y = rng.choice([0, 1, (1 << (n - 3)) - 1])
162
+ g = rng.randint(0, 1)
163
+ return x, y, g
164
+
165
+
166
+ def make_add_batch(rng, n, bsz, instances=None):
167
+ mask = (1 << n) - 1
168
+ xs, ys, gs, ss, cs = [], [], [], [], []
169
+ for j in range(bsz):
170
+ if instances is not None:
171
+ x, y, g = instances[j % len(instances)]
172
+ else:
173
+ x, y, g = sample_add(rng, n)
174
+ w = g * y
175
+ s = x + w
176
+ ss.append(s & mask)
177
+ cs.append((x ^ w ^ s) & mask)
178
+ xs.append(x); ys.append(y); gs.append(g)
179
+ batch = {
180
+ "x": _T(xs, n), "y": _T(ys, n),
181
+ "g": torch.tensor(gs, dtype=torch.float32),
182
+ "z": _T(ss, n), "carry": _T(cs, n),
183
+ "raw": list(zip(xs, ys, gs)),
184
+ }
185
+ return batch
manifest.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "entry_class": "model.BitStreamModel",
3
+ "output_base": 2,
4
+ "framework": "pytorch",
5
+ "model_description": "BitStream Modular Machine (46,128 parameters: ReduceCell 26,826 + AddCell 19,302): two trained recurrent cells applied over bit vector state registers by a fixed, feedback free streaming schedule. ReduceCell (3 blocks) computes z = x mod p for x < 4p; AddCell (2 blocks) computes s = x + g*y. Each cell is a position shared stack of bidirectional scan blocks: gated linear scans (hard {0,1} gates at inference) with pointwise MLPs, over per position embeddings of the operand and modulus bits (p, 2p, 3p wires for the reduction). The schedule streams the raw bits of a then b, two per step, through ReduceCell (X <- (4X + d) mod p), then streams the bits of the learned residue of a through AddCell + ReduceCell (Z <- (2Z + g*Rb) mod p). All arithmetic content carries, the comparisons against p, 2p, 3p, quotient selection, borrow chains lives in trained parameters; the forward pass performs only bit routing (shifts and concatenations). Emits the answer as base 2 digits, MSB first. Problems whose p exceeds the trained width fall back to [0].",
6
+ "training_description": "Both cells trained from random initialization on synthetic instances of their per step contracts (x mod m for x < 4m; x + g*y), following the per step residue supervision paradigm of the organizers' dlp_grokking example: cross entropy on the output bits plus auxiliary supervision of the internal automaton signals (carry bits, borrow chains against k*m, quotient class). Random moduli of every bit length in scope, padded to every inference width (no length extrapolation is used); operand mixtures include uniform quotient sampling, quotient boundary aiming (s near k*m +/- delta), and long carry and borrow run stress patterns. AdamW with a width curriculum, straight through hard gate training, scan output noise injection, output margin hinge, hard example replay mined from every batch, EMA weight averaging, and best checkpoint selection on the minimum exact match rate across all widths. No weights are hand set; randomizing the weights collapses accuracy to chance (perturb_test.py). Full training code included (train.py, data.py, verify.py)."
7
+ }
miner.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import random
6
+ import sys
7
+ import time
8
+ from pathlib import Path
9
+
10
+ import torch
11
+
12
+
13
+ def main():
14
+ ap = argparse.ArgumentParser()
15
+ ap.add_argument("ckpt_dir")
16
+ ap.add_argument("--widths", type=int, nargs="*", default=[35, 67])
17
+ ap.add_argument("--sub", default="submission_a")
18
+ ap.add_argument("--problems-per-round", type=int, default=40)
19
+ args = ap.parse_args()
20
+
21
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
22
+ from model import (make_reduce_cell, make_add_cell, reduce_features,
23
+ add_features, shift_bits, _bits_of, PAD_HEAD)
24
+
25
+ torch.set_num_threads(4)
26
+ rng = random.Random()
27
+ ck_path = Path(args.ckpt_dir) / "latest.pt"
28
+ out_r = Path(args.ckpt_dir) / "mined_reduce.jsonl"
29
+ out_a = Path(args.ckpt_dir) / "mined_add.jsonl"
30
+
31
+ def is_pp(n):
32
+ if n < 2:
33
+ return False
34
+ for sp in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31):
35
+ if n % sp == 0:
36
+ return n == sp
37
+ d, r = n - 1, 0
38
+ while d % 2 == 0:
39
+ d //= 2
40
+ r += 1
41
+ for _ in range(20):
42
+ a = rng.randrange(2, n - 1)
43
+ x = pow(a, d, n)
44
+ if x in (1, n - 1):
45
+ continue
46
+ for _ in range(r - 1):
47
+ x = x * x % n
48
+ if x == n - 1:
49
+ break
50
+ else:
51
+ return False
52
+ return True
53
+
54
+ def to_bits(v, w):
55
+ t = torch.zeros(1, w)
56
+ b = _bits_of(v)
57
+ t[0, w - len(b):] = torch.tensor(b, dtype=torch.float32)
58
+ return t
59
+
60
+ def val(t):
61
+ return int("".join(str(int(x)) for x in t[0].tolist()), 2)
62
+
63
+ R = make_reduce_cell()
64
+ A = make_add_cell()
65
+ last_load = 0.0
66
+ n_mined = 0
67
+
68
+ while True:
69
+ if time.time() - last_load > 180:
70
+ try:
71
+ ck = torch.load(ck_path, map_location="cpu",
72
+ weights_only=True)
73
+ R.load_state_dict(ck.get("reduce_ema_state_dict",
74
+ ck["reduce_state_dict"]))
75
+ A.load_state_dict(ck.get("add_ema_state_dict",
76
+ ck["add_state_dict"]))
77
+ R.eval()
78
+ A.eval()
79
+ last_load = time.time()
80
+ except Exception:
81
+ time.sleep(10)
82
+ continue
83
+
84
+ N = rng.choice(args.widths)
85
+ pb_hi = N - PAD_HEAD
86
+ pb_lo = max(2, pb_hi // 2 + 1)
87
+ def draw_pb():
88
+ r = rng.random()
89
+ if r < 0.45:
90
+ return pb_hi
91
+ if r < 0.70:
92
+ return max(pb_lo, pb_hi - 1)
93
+ return rng.randint(pb_lo, pb_hi)
94
+ L = 3 * pb_hi
95
+ mr, ma = [], []
96
+ with torch.no_grad():
97
+ for _ in range(args.problems_per_round):
98
+ pb = draw_pb()
99
+ if rng.random() < 0.35 and pb >= 9:
100
+ p = 0
101
+ for c in range(1, 400, 2):
102
+ cand = (1 << pb) - c
103
+ if cand > 2 and is_pp(cand):
104
+ p = cand
105
+ break
106
+ if not p:
107
+ p = (1 << (pb - 1)) | 1
108
+ while not is_pp(p):
109
+ p += 2
110
+ else:
111
+ while True:
112
+ p = rng.getrandbits(pb - 1) | (1 << (pb - 1)) | 1
113
+ if p > 2 and is_pp(p):
114
+ break
115
+ a = rng.getrandbits(rng.randint(1, L))
116
+ b = rng.getrandbits(rng.randint(1, L))
117
+ pt, p3t = to_bits(p, N), to_bits(3 * p, N)
118
+ residues = []
119
+ for op in (a, b):
120
+ ob = _bits_of(op)
121
+ if len(ob) % 2:
122
+ ob = [0] + ob
123
+ Xv = 0
124
+ for t in range(0, len(ob), 2):
125
+ xv = 4 * Xv + 2 * ob[t] + ob[t + 1]
126
+ x = torch.cat(
127
+ [to_bits(Xv, N)[:, 2:],
128
+ torch.tensor([[float(ob[t]),
129
+ float(ob[t + 1])]])], dim=1)
130
+ got = val((R(reduce_features(x, pt, p3t)) > 0).float())
131
+ want = xv % p
132
+ if got != want:
133
+ mr.append({"n": N, "m": p, "x": xv})
134
+ Xv = want
135
+ residues.append(Xv)
136
+ ra, rb = residues
137
+ rab = _bits_of(ra)
138
+ rab = [0] * (N - PAD_HEAD - len(rab)) + rab
139
+ yt = to_bits(rb, N)
140
+ Zv = 0
141
+ for g in rab:
142
+ sv = 2 * Zv + g * rb
143
+ got = val((A(add_features(
144
+ shift_bits(to_bits(Zv, N), 1), yt,
145
+ torch.tensor([float(g)]))) > 0).float())
146
+ if got != sv:
147
+ ma.append({"n": N, "x": 2 * Zv, "y": rb, "g": g})
148
+ got2 = val((R(reduce_features(
149
+ to_bits(sv, N), pt, p3t)) > 0).float())
150
+ want = sv % p
151
+ if got2 != want:
152
+ mr.append({"n": N, "m": p, "x": sv})
153
+ Zv = want
154
+ if mr:
155
+ with open(out_r, "a") as f:
156
+ for row in mr:
157
+ f.write(json.dumps(row) + "\n")
158
+ if ma:
159
+ with open(out_a, "a") as f:
160
+ for row in ma:
161
+ f.write(json.dumps(row) + "\n")
162
+ n_mined += len(mr) + len(ma)
163
+ print(f"mined so far: {n_mined} (+{len(mr)}r +{len(ma)}a @N={N})",
164
+ flush=True)
165
+
166
+
167
+ if __name__ == "__main__":
168
+ main()
model.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.nn.functional as F
8
+
9
+ from modchallenge.interface.base_model import ModularMultiplicationModel
10
+
11
+
12
+ MAX_P_BITS = 32
13
+ PAD_HEAD = 3
14
+
15
+ REDUCE_FEATURES = 6
16
+ ADD_FEATURES = 5
17
+
18
+
19
+ def _bits_of(n: int) -> list[int]:
20
+ return [int(c) for c in bin(n)[2:]]
21
+
22
+ def linear_scan(alpha: torch.Tensor, beta: torch.Tensor) -> torch.Tensor:
23
+
24
+ A, B = alpha, beta
25
+ n = A.shape[1]
26
+ off = 1
27
+ while off < n:
28
+ a_prev = F.pad(A, (0, 0, off, 0), value=1.0)[:, :n]
29
+ b_prev = F.pad(B, (0, 0, off, 0), value=0.0)[:, :n]
30
+ B = A * b_prev + B
31
+ A = A * a_prev
32
+ off <<= 1
33
+ return B
34
+
35
+
36
+ class GateFn(nn.Module):
37
+
38
+ def __init__(self, mode: str = "hard"):
39
+ super().__init__()
40
+ self.mode = mode
41
+
42
+ def forward(self, z: torch.Tensor) -> torch.Tensor:
43
+ if self.mode == "soft":
44
+ return torch.sigmoid(z)
45
+ hard = (z > 0).to(z.dtype)
46
+ if self.mode == "ste" and self.training:
47
+ soft = torch.sigmoid(z)
48
+ return hard + soft - soft.detach()
49
+ return hard
50
+
51
+
52
+ class BiScanBlock(nn.Module):
53
+
54
+ def __init__(self, d_model: int, d_scan: int, gate: GateFn):
55
+ super().__init__()
56
+ self.gate = gate
57
+ self.proj_f = nn.Linear(d_model, 2 * d_scan)
58
+ self.proj_b = nn.Linear(d_model, 2 * d_scan)
59
+ self.out = nn.Linear(2 * d_scan, d_model)
60
+ self.mlp = nn.Sequential(
61
+ nn.Linear(d_model, 2 * d_model),
62
+ nn.ReLU(),
63
+ nn.Linear(2 * d_model, d_model),
64
+ )
65
+ self.scan_noise = 0.0
66
+
67
+ def forward(self, u: torch.Tensor) -> torch.Tensor:
68
+ zf = self.proj_f(u)
69
+ zb = self.proj_b(u)
70
+ af, bf = zf.chunk(2, dim=-1)
71
+ ab, bb = zb.chunk(2, dim=-1)
72
+ hf = linear_scan(self.gate(af), bf)
73
+ hb = linear_scan(self.gate(ab.flip(1)), bb.flip(1)).flip(1)
74
+ h = torch.cat([hf, hb], dim=-1)
75
+ if self.training:
76
+ self.last_h_l1 = h.abs().mean()
77
+ if self.training and self.scan_noise > 0:
78
+ h = h + torch.randn_like(h) * self.scan_noise
79
+ u = u + self.out(h)
80
+ u = u + self.mlp(u)
81
+ return u
82
+
83
+
84
+ class BitCell(nn.Module):
85
+
86
+ def __init__(self, n_features: int, n_borrow: int, n_q: int,
87
+ d_model: int = 32, d_scan: int = 16, n_blocks: int = 3,
88
+ gate_mode: str = "hard"):
89
+ super().__init__()
90
+ self.gate = GateFn(gate_mode)
91
+ self.embed = nn.Linear(n_features, d_model)
92
+ self.pre_mlp = nn.Sequential(
93
+ nn.Linear(d_model, 2 * d_model),
94
+ nn.ReLU(),
95
+ nn.Linear(2 * d_model, d_model),
96
+ )
97
+ self.blocks = nn.ModuleList(
98
+ BiScanBlock(d_model, d_scan, self.gate) for _ in range(n_blocks)
99
+ )
100
+ self.head = nn.Linear(d_model, 1)
101
+ self.head_carry = nn.Linear(d_model, 1)
102
+ self.head_sum = nn.Linear(d_model, 1)
103
+ self.head_borrow = nn.Linear(d_model, n_borrow)
104
+ self.head_q = nn.Linear(d_model, n_q)
105
+ self.config = dict(n_features=n_features, n_borrow=n_borrow, n_q=n_q,
106
+ d_model=d_model, d_scan=d_scan, n_blocks=n_blocks)
107
+
108
+ def trunk(self, feats: torch.Tensor):
109
+ u = self.embed(feats)
110
+ u = u + self.pre_mlp(u)
111
+ taps = []
112
+ for blk in self.blocks:
113
+ u = blk(u)
114
+ taps.append(u)
115
+ return u, taps
116
+
117
+ def forward(self, feats: torch.Tensor) -> torch.Tensor:
118
+ u, _ = self.trunk(feats)
119
+ return self.head(u).squeeze(-1)
120
+
121
+ def forward_train(self, feats: torch.Tensor):
122
+ u, taps = self.trunk(feats)
123
+ return {
124
+ "bits": self.head(u).squeeze(-1),
125
+ "carry": self.head_carry(taps[0]).squeeze(-1),
126
+ "sum": self.head_sum(taps[0]).squeeze(-1),
127
+ "borrow": self.head_borrow(taps[1]),
128
+ "q": self.head_q(taps[-1].mean(dim=1)),
129
+ }
130
+
131
+
132
+ def make_reduce_cell(gate_mode: str = "hard", **kw) -> BitCell:
133
+ return BitCell(REDUCE_FEATURES, n_borrow=3, n_q=4,
134
+ gate_mode=gate_mode, **kw)
135
+
136
+
137
+ def make_add_cell(gate_mode: str = "hard", **kw) -> BitCell:
138
+ kw.setdefault("n_blocks", 2)
139
+ return BitCell(ADD_FEATURES, n_borrow=1, n_q=2, gate_mode=gate_mode, **kw)
140
+
141
+ def shift_bits(t: torch.Tensor, k: int) -> torch.Tensor:
142
+
143
+ if k == 0:
144
+ return t
145
+ return torch.cat([t[:, k:], t.new_zeros(t.shape[0], k)], dim=1)
146
+
147
+
148
+ def _flags(B: int, N: int, dev) -> tuple[torch.Tensor, torch.Tensor]:
149
+ is_msb = torch.zeros(B, N, device=dev)
150
+ is_msb[:, 0] = 1.0
151
+ is_lsb = torch.zeros(B, N, device=dev)
152
+ is_lsb[:, -1] = 1.0
153
+ return is_msb, is_lsb
154
+
155
+
156
+ def reduce_features(x, p, p3):
157
+ B, N = x.shape
158
+ is_msb, is_lsb = _flags(B, N, x.device)
159
+ return torch.stack([x, p, shift_bits(p, 1), p3, is_msb, is_lsb], dim=-1)
160
+
161
+
162
+ def add_features(x, y, g):
163
+ B, N = x.shape
164
+ is_msb, is_lsb = _flags(B, N, x.device)
165
+ return torch.stack([x, y, g.unsqueeze(1).expand(B, N),
166
+ is_msb, is_lsb], dim=-1)
167
+
168
+
169
+ class BitStreamMachine:
170
+
171
+ def __init__(self, reduce_cell: BitCell, add_cell: BitCell,
172
+ device: torch.device):
173
+ self.reduce_cell = reduce_cell
174
+ self.add_cell = add_cell
175
+ self.device = device
176
+
177
+ @torch.no_grad()
178
+ def _rstep(self, x, p, p3):
179
+ logits = self.reduce_cell(reduce_features(x, p, p3))
180
+ return (logits > 0).to(x.dtype)
181
+
182
+ @torch.no_grad()
183
+ def _astep(self, x, y, g):
184
+ logits = self.add_cell(add_features(x, y, g))
185
+ return (logits > 0).to(x.dtype)
186
+
187
+ @torch.no_grad()
188
+ def run(self, a_bits, b_bits, p_bits, p3_bits):
189
+
190
+ B, N = p_bits.shape
191
+ L = a_bits.shape[1]
192
+
193
+ ops = torch.cat([a_bits, b_bits], dim=0)
194
+ p2r = torch.cat([p_bits, p_bits], dim=0)
195
+ p32r = torch.cat([p3_bits, p3_bits], dim=0)
196
+ X = p2r.new_zeros(2 * B, N)
197
+ for t in range(0, L, 2):
198
+ x = torch.cat([X[:, 2:], ops[:, t: t + 2]], dim=1)
199
+ X = self._rstep(x, p2r, p32r)
200
+ ra, rb = X[:B], X[B:]
201
+
202
+ Z = p_bits.new_zeros(B, N)
203
+ for t in range(PAD_HEAD, N):
204
+ s = self._astep(shift_bits(Z, 1), rb, ra[:, t])
205
+ Z = self._rstep(s, p_bits, p3_bits)
206
+ return Z
207
+
208
+ class BitStreamModel(ModularMultiplicationModel):
209
+ def __init__(self):
210
+ self.machine: BitStreamMachine | None = None
211
+ self.device = torch.device("cpu")
212
+
213
+ def load(self, model_dir: str) -> None:
214
+ torch.set_grad_enabled(False)
215
+ ckpt = torch.load(
216
+ Path(model_dir) / "weights.pt",
217
+ map_location="cpu",
218
+ weights_only=True,
219
+ )
220
+ rcell = make_reduce_cell()
221
+ rcell.load_state_dict(ckpt["reduce_state_dict"], strict=True)
222
+ rcell.eval()
223
+ acell = make_add_cell()
224
+ acell.load_state_dict(ckpt["add_state_dict"], strict=True)
225
+ acell.eval()
226
+ self.machine = BitStreamMachine(rcell, acell, self.device)
227
+
228
+
229
+ def preprocess_a(self, a: str):
230
+ return _bits_of(int(a))
231
+
232
+ def preprocess_b(self, b: str):
233
+ return _bits_of(int(b))
234
+
235
+ def preprocess_p(self, p: str):
236
+ v = int(p)
237
+ return {"p": _bits_of(v), "p3": _bits_of((v << 1) + v)}
238
+
239
+
240
+ @torch.no_grad()
241
+ def predict_digits(self, a_enc, b_enc, p_enc) -> list[int]:
242
+ return self.predict_digits_batch([(a_enc, b_enc, p_enc)])[0]
243
+
244
+ @torch.no_grad()
245
+ def predict_digits_batch(self, inputs) -> list[list[int]]:
246
+ out: list[list[int] | None] = [None] * len(inputs)
247
+
248
+ idx = [i for i, (_, _, pe) in enumerate(inputs)
249
+ if len(pe["p"]) <= MAX_P_BITS]
250
+ keep = set(idx)
251
+ for i in range(len(inputs)):
252
+ if i not in keep:
253
+ out[i] = [0]
254
+ if not idx:
255
+ return [o if o is not None else [0] for o in out]
256
+
257
+ sub = [inputs[i] for i in idx]
258
+ n_p = max(len(pe["p"]) for _, _, pe in sub) + PAD_HEAD
259
+ L = max(2, max(max(len(ae), len(be)) for ae, be, _ in sub))
260
+ L += L % 2
261
+
262
+ def pack(rows: list[list[int]], width: int) -> torch.Tensor:
263
+ t = torch.zeros(len(rows), width)
264
+ for r, bits in enumerate(rows):
265
+ if bits:
266
+ t[r, width - len(bits):] = torch.tensor(
267
+ bits, dtype=torch.float32)
268
+ return t
269
+
270
+ a_t = pack([ae for ae, _, _ in sub], L)
271
+ b_t = pack([be for _, be, _ in sub], L)
272
+ p_t = pack([pe["p"] for _, _, pe in sub], n_p)
273
+ p3_t = pack([pe["p3"] for _, _, pe in sub], n_p)
274
+
275
+ z = self.machine.run(a_t, b_t, p_t, p3_t)
276
+ z_int = z.to(torch.int64).tolist()
277
+ for row, i in enumerate(idx):
278
+ out[i] = [int(v) for v in z_int[row]]
279
+ return [o if o is not None else [0] for o in out]
280
+
281
+ def max_batch_size(self) -> int:
282
+ return 128
perturb_test.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+ import random
5
+ import sys
6
+
7
+ import torch
8
+
9
+ from model import (make_reduce_cell, make_add_cell,
10
+ BitStreamMachine, _bits_of, PAD_HEAD)
11
+
12
+
13
+ def probable_prime(rng: random.Random, bits: int) -> int:
14
+ def is_pp(n):
15
+ if n < 2:
16
+ return False
17
+ for sp in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31):
18
+ if n % sp == 0:
19
+ return n == sp
20
+ d, r = n - 1, 0
21
+ while d % 2 == 0:
22
+ d //= 2
23
+ r += 1
24
+ for _ in range(20):
25
+ a = rng.randrange(2, n - 1)
26
+ x = pow(a, d, n)
27
+ if x in (1, n - 1):
28
+ continue
29
+ for _ in range(r - 1):
30
+ x = x * x % n
31
+ if x == n - 1:
32
+ break
33
+ else:
34
+ return False
35
+ return True
36
+
37
+ while True:
38
+ p = rng.getrandbits(bits - 1) | (1 << (bits - 1)) | 1
39
+ if is_pp(p):
40
+ return p
41
+
42
+
43
+ @torch.no_grad()
44
+ def accuracy(cells, rng: random.Random, p_bits: int,
45
+ op_bits: int, n_problems: int = 50) -> float:
46
+ mach = BitStreamMachine(cells[0], cells[1], torch.device("cpu"))
47
+ probs = []
48
+ for _ in range(n_problems):
49
+ p = probable_prime(rng, p_bits)
50
+ a = rng.getrandbits(rng.randint(1, op_bits))
51
+ b = rng.getrandbits(rng.randint(1, op_bits))
52
+ probs.append((a, b, p))
53
+ n_p = max(p.bit_length() for _, _, p in probs) + PAD_HEAD
54
+ L = max(2, max(max(a.bit_length(), b.bit_length()) for a, b, _ in probs))
55
+ L += L % 2
56
+
57
+ def pack(vals, w):
58
+ m = torch.zeros(len(vals), w)
59
+ for r, v in enumerate(vals):
60
+ bits = _bits_of(v)
61
+ m[r, w - len(bits):] = torch.tensor(bits, dtype=torch.float32)
62
+ return m
63
+
64
+ z = mach.run(pack([a for a, _, _ in probs], L),
65
+ pack([b for _, b, _ in probs], L),
66
+ pack([p for _, _, p in probs], n_p),
67
+ pack([3 * p for _, _, p in probs], n_p))
68
+ good = 0
69
+ for r, (a, b, p) in enumerate(probs):
70
+ got = int("".join(str(int(v)) for v in z[r].tolist()), 2)
71
+ good += (got == (a * b) % p)
72
+ return good / n_problems
73
+
74
+
75
+ def main():
76
+ ckpt_path = sys.argv[1] if len(sys.argv) > 1 else "weights.pt"
77
+ ck = torch.load(ckpt_path, map_location="cpu", weights_only=True)
78
+ rcell = make_reduce_cell()
79
+ rcell.load_state_dict(ck["reduce_state_dict"])
80
+ rcell.eval()
81
+ acell = make_add_cell()
82
+ acell.load_state_dict(ck["add_state_dict"])
83
+ acell.eval()
84
+ cells = (rcell, acell)
85
+
86
+ rng = random.Random(42)
87
+ print("trained weights:")
88
+ for pb, ob in ((14, 64), (28, 96)):
89
+ print(f" p ~ {pb} bits, ops {ob} bits: "
90
+ f"accuracy {accuracy(cells, rng, pb, ob):.2f}")
91
+
92
+ for scale in (0.02, 0.1):
93
+ pert = tuple(copy.deepcopy(c) for c in cells)
94
+ torch.manual_seed(0)
95
+ with torch.no_grad():
96
+ for c in pert:
97
+ for prm in c.parameters():
98
+ prm.add_(torch.randn_like(prm) * scale
99
+ * (prm.abs().mean() + 1e-8))
100
+ print(f"weights + {scale:.0%} relative noise:")
101
+ for pb, ob in ((14, 64), (28, 96)):
102
+ print(f" p ~ {pb} bits, ops {ob} bits: "
103
+ f"accuracy {accuracy(pert, rng, pb, ob):.2f}")
104
+
105
+ torch.manual_seed(1)
106
+ fresh = (make_reduce_cell().eval(), make_add_cell().eval())
107
+ print("reinitialized (untrained) weights:")
108
+ for pb, ob in ((14, 64), (28, 96)):
109
+ print(f" p ~ {pb} bits, ops {ob} bits: "
110
+ f"accuracy {accuracy(fresh, rng, pb, ob):.2f}")
111
+
112
+
113
+ if __name__ == "__main__":
114
+ main()
train.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import queue
6
+ import random
7
+ import sys
8
+ import threading
9
+ import time
10
+ from pathlib import Path
11
+
12
+ import torch
13
+ import torch.nn.functional as F
14
+
15
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
16
+ from model import (
17
+ make_reduce_cell, make_add_cell, reduce_features, add_features,
18
+ )
19
+ from data import make_reduce_batch, make_add_batch
20
+
21
+ STAGES = [8, 12, 20, 36, 68, 132, 260, 516, 1027]
22
+ TOKEN_BUDGET = 40_000
23
+ EVAL_EVERY = 500
24
+ ADVANCE_THRESHOLD = 0.9995
25
+ SOFT_STEPS = 1_500
26
+ NOISE = 0.01
27
+ MARGIN = 3.0
28
+ MARGIN_W = 0.1
29
+ AUX_W = 0.3
30
+ PLATEAU_STEPS = 12_000
31
+ KINDS = ("reduce", "add")
32
+
33
+
34
+ def features_for(kind, b):
35
+ if kind == "reduce":
36
+ return reduce_features(b["x"], b["p"], b["p3"])
37
+ return add_features(b["x"], b["y"], b["g"])
38
+
39
+
40
+ def forward_loss(kind, cell, batch):
41
+ outs = cell.forward_train(features_for(kind, batch))
42
+ tgt = batch["z"]
43
+ loss_bits = F.binary_cross_entropy_with_logits(outs["bits"], tgt)
44
+ sign = 2 * tgt - 1
45
+ loss_margin = F.relu(MARGIN - outs["bits"] * sign).mean()
46
+ if kind == "reduce":
47
+ loss_aux = (
48
+ F.binary_cross_entropy_with_logits(outs["borrow"], batch["borrow"])
49
+ + F.cross_entropy(outs["q"], batch["q"])
50
+ )
51
+ else:
52
+ loss_aux = F.binary_cross_entropy_with_logits(
53
+ outs["carry"], batch["carry"])
54
+ loss = loss_bits + MARGIN_W * loss_margin + AUX_W * loss_aux
55
+ loss = loss + 1e-4 * sum(blk.last_h_l1 for blk in cell.blocks)
56
+ ok_rows = ((outs["bits"] > 0) == (tgt > 0.5)).all(dim=1)
57
+ return loss, {
58
+ "loss": loss.item(), "bits": loss_bits.item(),
59
+ "exact": ok_rows.float().mean().item(),
60
+ }, ok_rows
61
+
62
+
63
+ def bsz_for(n):
64
+ return min(1024, max(8, TOKEN_BUDGET // n))
65
+
66
+
67
+ def fresh_batch(kind, rng, n, bsz, instances=None):
68
+ if kind == "reduce":
69
+ return make_reduce_batch(rng, n, bsz, instances)
70
+ return make_add_batch(rng, n, bsz, instances)
71
+
72
+
73
+ @torch.no_grad()
74
+ def evaluate(kind, cell, rng, n, device, n_batches=4):
75
+ cell.eval()
76
+ total, good = 0, 0
77
+ for _ in range(n_batches):
78
+ b = fresh_batch(kind, rng, n, bsz_for(n))
79
+ b.pop("raw")
80
+ b = {k: v.to(device) for k, v in b.items()}
81
+ logits = cell(features_for(kind, b))
82
+ ok = ((logits > 0) == (b["z"] > 0.5)).all(dim=1)
83
+ good += int(ok.sum())
84
+ total += ok.numel()
85
+ cell.train()
86
+ return good / total
87
+
88
+
89
+ def set_mode(cell, mode, noise):
90
+ cell.gate.mode = mode
91
+ for blk in cell.blocks:
92
+ blk.scan_noise = noise
93
+
94
+
95
+ def main():
96
+ ap = argparse.ArgumentParser()
97
+ ap.add_argument("--resume", default=None)
98
+ ap.add_argument("--steps", type=int, default=600_000)
99
+ ap.add_argument("--lr", type=float, default=1e-3)
100
+ ap.add_argument("--out", default="ckpt2")
101
+ ap.add_argument("--seed", type=int, default=0)
102
+ ap.add_argument("--max-stage", type=int, default=None)
103
+ ap.add_argument("--stages", type=int, nargs="*", default=None)
104
+ ap.add_argument("--force-stage", type=int, default=None)
105
+ ap.add_argument("--eval-window", type=int, default=0,
106
+ help="0 = min over all widths <= stage; K>0 = min over last K stages only")
107
+ args = ap.parse_args()
108
+ global STAGES
109
+ if args.stages:
110
+ STAGES = args.stages
111
+ if args.max_stage is None:
112
+ args.max_stage = len(STAGES) - 1
113
+
114
+ device = torch.device("mps" if torch.backends.mps.is_available() else "cpu")
115
+ rng = random.Random(args.seed)
116
+ torch.manual_seed(args.seed)
117
+
118
+ cells = {"reduce": make_reduce_cell("soft").to(device),
119
+ "add": make_add_cell("soft").to(device)}
120
+ opts = {k: torch.optim.AdamW(c.parameters(), lr=args.lr, weight_decay=0.0)
121
+ for k, c in cells.items()}
122
+
123
+ import copy as _copy
124
+ ema_cells = {k: _copy.deepcopy(c) for k, c in cells.items()}
125
+ EMA_DECAY = 0.999
126
+
127
+ @torch.no_grad()
128
+ def ema_update(kind):
129
+ for pe, pr in zip(ema_cells[kind].parameters(),
130
+ cells[kind].parameters()):
131
+ pe.lerp_(pr, 1.0 - EMA_DECAY)
132
+
133
+ stage, step, last_advance_step = 0, 0, 0
134
+ streak = 0
135
+ best_box: dict[int, float] = {}
136
+ out_dir = Path(args.out)
137
+ out_dir.mkdir(exist_ok=True)
138
+ metrics_f = open(out_dir / "metrics.jsonl", "a")
139
+
140
+ if args.resume:
141
+ ck = torch.load(args.resume, map_location=device, weights_only=True)
142
+ cells["reduce"].load_state_dict(ck["reduce_state_dict"], strict=False)
143
+ if "add_state_dict" in ck:
144
+ cells["add"].load_state_dict(ck["add_state_dict"], strict=False)
145
+ for k in KINDS:
146
+ if f"{k}_state_dict" in ck:
147
+ sdk = ck.get(f"{k}_ema_state_dict", ck[f"{k}_state_dict"])
148
+ ema_cells[k].load_state_dict(sdk, strict=False)
149
+ for k in KINDS:
150
+ try:
151
+ opts[k].load_state_dict(ck[f"{k}_opt"])
152
+ except Exception:
153
+ print(f"{k}: fresh optimizer", flush=True)
154
+ stage, step = ck["stage"], ck["step"]
155
+ if args.force_stage is not None:
156
+ stage = args.force_stage
157
+ last_advance_step = step
158
+ print(f"resumed at step {step}, stage {stage}", flush=True)
159
+
160
+ def set_lr(v):
161
+ for o in opts.values():
162
+ for g in o.param_groups:
163
+ g["lr"] = v
164
+
165
+ def get_lr():
166
+ return opts["reduce"].param_groups[0]["lr"]
167
+
168
+ set_lr(args.lr)
169
+
170
+ def pick_width(stage_now):
171
+ if stage_now == 0 or rng.random() < 0.5:
172
+ n = STAGES[stage_now]
173
+ else:
174
+ n = STAGES[rng.randint(0, stage_now - 1)]
175
+ if rng.random() < 0.3:
176
+ n = max(5, n - rng.randint(0, max(1, n // 8)))
177
+ return n
178
+
179
+ q: queue.Queue = queue.Queue(maxsize=4)
180
+ stage_box = {"stage": stage}
181
+ hard_buf: dict[tuple, list] = {}
182
+ buf_lock = threading.Lock()
183
+
184
+ def load_mined(kind):
185
+ import json as _json
186
+ path = out_dir / f"mined_{kind}.jsonl"
187
+ if not path.exists():
188
+ return
189
+ try:
190
+ lines = path.read_text().splitlines()[-40000:]
191
+ except Exception:
192
+ return
193
+ per_width: dict[int, list] = {}
194
+ for ln in lines:
195
+ try:
196
+ row = _json.loads(ln)
197
+ except Exception:
198
+ continue
199
+ if kind == "reduce":
200
+ inst = (row["m"], row["x"])
201
+ else:
202
+ inst = (row["x"], row["y"], row["g"])
203
+ per_width.setdefault(row["n"], []).append(inst)
204
+ with buf_lock:
205
+ for n, insts in per_width.items():
206
+ buf = hard_buf.setdefault((kind, n), [])
207
+ buf.extend(insts)
208
+ if len(buf) > 20_000:
209
+ del buf[: len(buf) - 20_000]
210
+
211
+ def producer():
212
+ prng = random.Random(args.seed + 1)
213
+ last_mined = 0.0
214
+ while True:
215
+ if time.time() - last_mined > 120:
216
+ for k in KINDS:
217
+ load_mined(k)
218
+ last_mined = time.time()
219
+ kind = "reduce" if prng.random() < 0.5 else "add"
220
+ cur_w = STAGES[min(stage_box["stage"], len(STAGES) - 1)] + 8
221
+ with buf_lock:
222
+ widths = [w for (k, w), v in hard_buf.items()
223
+ if k == kind and len(v) >= 64 and w <= cur_w]
224
+ if widths and prng.random() < 0.30:
225
+ n = prng.choice(widths)
226
+ bsz = bsz_for(n)
227
+ with buf_lock:
228
+ pool = hard_buf[(kind, n)]
229
+ replay = [pool[prng.randrange(len(pool))]
230
+ for _ in range(bsz // 2)]
231
+ b = fresh_batch(kind, prng, n, bsz - len(replay))
232
+ br = fresh_batch(kind, prng, n, len(replay), instances=replay)
233
+ merged = {k: torch.cat([b[k], br[k]])
234
+ for k in b if k != "raw"}
235
+ merged["raw"] = b["raw"] + br["raw"]
236
+ q.put((kind, n, merged))
237
+ else:
238
+ n = pick_width(stage_box["stage"])
239
+ q.put((kind, n, fresh_batch(kind, prng, n, bsz_for(n))))
240
+
241
+ threading.Thread(target=producer, daemon=True).start()
242
+
243
+ for c in cells.values():
244
+ c.train()
245
+ t0 = time.time()
246
+ while step < args.steps:
247
+ step += 1
248
+ mode = "soft" if step <= SOFT_STEPS else "ste"
249
+ noise = 0.0 if step <= SOFT_STEPS else NOISE
250
+ for c in cells.values():
251
+ set_mode(c, mode, noise)
252
+
253
+ stage_box["stage"] = stage
254
+ kind, n, batch = q.get()
255
+ raw = batch.pop("raw")
256
+ batch = {k: v.to(device) for k, v in batch.items()}
257
+ cell, opt = cells[kind], opts[kind]
258
+ loss, stats, ok_rows = forward_loss(kind, cell, batch)
259
+ opt.zero_grad(set_to_none=True)
260
+ loss.backward()
261
+ torch.nn.utils.clip_grad_norm_(cell.parameters(), 1.0)
262
+ opt.step()
263
+ ema_update(kind)
264
+
265
+ if step > SOFT_STEPS:
266
+ bad = (~ok_rows).nonzero().flatten().tolist()
267
+ if bad:
268
+ with buf_lock:
269
+ buf = hard_buf.setdefault((kind, n), [])
270
+ buf.extend(raw[i] for i in bad)
271
+ if len(buf) > 20_000:
272
+ del buf[: len(buf) - 20_000]
273
+
274
+ if step % 100 == 0:
275
+ stats.update(step=step, stage=stage, n=n, kind=kind,
276
+ lr=get_lr(),
277
+ sps=round(step / (time.time() - t0), 2))
278
+ print(json.dumps(stats), flush=True)
279
+ metrics_f.write(json.dumps(stats) + "\n")
280
+ metrics_f.flush()
281
+
282
+ if step % EVAL_EVERY == 0 and step > SOFT_STEPS:
283
+ accs = {}
284
+ for k in KINDS:
285
+ set_mode(ema_cells[k], "hard", 0.0)
286
+ ema_cells[k].eval()
287
+ lo = 0 if args.eval_window == 0 else max(0, stage + 1 - args.eval_window)
288
+ accs[k] = min(
289
+ evaluate(k, ema_cells[k], rng, STAGES[s], device,
290
+ n_batches=2 if s < stage else 4)
291
+ for s in range(lo, stage + 1))
292
+ print(json.dumps({"eval": accs, "stage": stage,
293
+ "n": STAGES[stage], "step": step}), flush=True)
294
+ metrics_f.write(json.dumps(
295
+ {"eval": accs, "stage": stage, "step": step}) + "\n")
296
+ metrics_f.flush()
297
+ score = min(accs.values())
298
+ if score > best_box.get(stage, 0.0):
299
+ best_box[stage] = score
300
+ torch.save(
301
+ {"reduce_state_dict": cells["reduce"].state_dict(),
302
+ "add_state_dict": cells["add"].state_dict(),
303
+ "reduce_ema_state_dict":
304
+ ema_cells["reduce"].state_dict(),
305
+ "add_ema_state_dict": ema_cells["add"].state_dict(),
306
+ "stage": stage, "step": step, "score": score},
307
+ out_dir / f"best_stage{stage}.pt",
308
+ )
309
+ ok = score >= ADVANCE_THRESHOLD
310
+ streak = streak + 1 if ok else 0
311
+ if streak >= 2 and stage < min(args.max_stage, len(STAGES) - 1):
312
+ stage += 1
313
+ streak = 0
314
+ last_advance_step = step
315
+ set_lr(args.lr)
316
+ print(f"=== ADVANCE to stage {stage} (N={STAGES[stage]}) ===",
317
+ flush=True)
318
+ elif step - last_advance_step >= PLATEAU_STEPS and get_lr() > 5.1e-5:
319
+ set_lr(max(5e-5, get_lr() * 0.5))
320
+ last_advance_step = step
321
+ print(f"=== LR DECAY to {get_lr():.2e} (plateau) ===",
322
+ flush=True)
323
+ torch.save(
324
+ {"reduce_state_dict": cells["reduce"].state_dict(),
325
+ "add_state_dict": cells["add"].state_dict(),
326
+ "reduce_ema_state_dict": ema_cells["reduce"].state_dict(),
327
+ "add_ema_state_dict": ema_cells["add"].state_dict(),
328
+ "reduce_opt": opts["reduce"].state_dict(),
329
+ "add_opt": opts["add"].state_dict(),
330
+ "stage": stage, "step": step},
331
+ out_dir / "latest.pt",
332
+ )
333
+ if step % 5000 == 0:
334
+ import shutil
335
+ shutil.copy(out_dir / "latest.pt",
336
+ out_dir / f"snap_{step}.pt")
337
+ snaps = sorted(out_dir.glob("snap_*.pt"),
338
+ key=lambda p: int(p.stem.split("_")[1]))
339
+ for old in snaps[:-6]:
340
+ old.unlink()
341
+
342
+ metrics_f.close()
343
+
344
+
345
+ if __name__ == "__main__":
346
+ main()
verify.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import random
5
+ import sys
6
+ import time
7
+ from pathlib import Path
8
+
9
+ import torch
10
+
11
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
12
+ from model import (
13
+ make_reduce_cell, make_add_cell, reduce_features, add_features,
14
+ BitStreamMachine, _bits_of, PAD_HEAD,
15
+ )
16
+ from data import make_reduce_batch, make_add_batch
17
+
18
+
19
+ def is_probable_prime(n: int, rng: random.Random, rounds: int = 24) -> bool:
20
+ if n < 2:
21
+ return False
22
+ for sp in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37):
23
+ if n % sp == 0:
24
+ return n == sp
25
+ d, r = n - 1, 0
26
+ while d % 2 == 0:
27
+ d //= 2
28
+ r += 1
29
+ for _ in range(rounds):
30
+ a = rng.randrange(2, n - 1)
31
+ x = pow(a, d, n)
32
+ if x in (1, n - 1):
33
+ continue
34
+ for _ in range(r - 1):
35
+ x = x * x % n
36
+ if x == n - 1:
37
+ break
38
+ else:
39
+ return False
40
+ return True
41
+
42
+
43
+ def random_prime(rng: random.Random, lo_bits: int, hi_bits: int) -> int:
44
+ while True:
45
+ l = rng.randint(lo_bits, hi_bits)
46
+ if l == 1:
47
+ return 2
48
+ p = rng.getrandbits(l - 1) | (1 << (l - 1)) | 1
49
+ if p == 1:
50
+ continue
51
+ if is_probable_prime(p, rng):
52
+ return p
53
+
54
+
55
+ def load_cells(path: str):
56
+ ck = torch.load(path, map_location="cpu", weights_only=True)
57
+ rcell = make_reduce_cell()
58
+ rcell.load_state_dict(ck.get("reduce_ema_state_dict", ck["reduce_state_dict"]))
59
+ rcell.eval()
60
+ acell = make_add_cell()
61
+ acell.load_state_dict(ck.get("add_ema_state_dict", ck["add_state_dict"]))
62
+ acell.eval()
63
+ return rcell, acell
64
+
65
+
66
+ @torch.no_grad()
67
+ def cell_stress(rcell, acell, rng, widths, per_width):
68
+ print("== cell-level stress (hard gates, CPU) ==")
69
+ worst = 1.0
70
+ for n in widths:
71
+ bsz = max(8, 20000 // n)
72
+ for kind, cell in (("reduce", rcell), ("add", acell)):
73
+ total, good = 0, 0
74
+ while total < per_width:
75
+ if kind == "reduce":
76
+ b = make_reduce_batch(rng, n, bsz)
77
+ feats = reduce_features(b["x"], b["p"], b["p3"])
78
+ else:
79
+ b = make_add_batch(rng, n, bsz)
80
+ feats = add_features(b["x"], b["y"], b["g"])
81
+ ok = ((cell(feats) > 0) == (b["z"] > 0.5)).all(dim=1)
82
+ good += int(ok.sum())
83
+ total += ok.numel()
84
+ rate = good / total
85
+ worst = min(worst, rate)
86
+ print(f" n={n:5d} {kind:6s}: {good}/{total} ({rate:.6f})"
87
+ + (" <-- FAILURES" if rate < 1 else ""))
88
+ return worst
89
+
90
+
91
+ def _pack(vals, w):
92
+ m = torch.zeros(len(vals), w)
93
+ for r, v in enumerate(vals):
94
+ bits = _bits_of(v)
95
+ m[r, w - len(bits):] = torch.tensor(bits, dtype=torch.float32)
96
+ return m
97
+
98
+
99
+ @torch.no_grad()
100
+ def machine_tier_check(rcell, acell, rng, per_tier, tiers=None):
101
+ print("== machine-level end-to-end vs ground truth ==")
102
+ mach = BitStreamMachine(rcell, acell, torch.device("cpu"))
103
+ geo = {1: (1, 3, 32), 2: (4, 8, 48), 3: (9, 16, 64), 4: (17, 32, 96),
104
+ 5: (33, 64, 128), 6: (65, 128, 256), 7: (129, 256, 512),
105
+ 8: (257, 512, 1024), 9: (513, 1024, 2048)}
106
+ if tiers:
107
+ geo = {t: geo[t] for t in tiers}
108
+ results = {}
109
+ for t, (lo, hi, ob) in geo.items():
110
+ primes = [random_prime(rng, lo, hi) for _ in range(5)]
111
+ probs = []
112
+ for i in range(per_tier):
113
+ p = primes[i % 5]
114
+ if i < 4:
115
+ a, b = [(0, rng.getrandbits(ob)), (rng.getrandbits(ob), 0),
116
+ (1, rng.getrandbits(ob)), (rng.getrandbits(ob), 1)][i]
117
+ else:
118
+ a = rng.getrandbits(rng.randint(1, ob))
119
+ b = rng.getrandbits(rng.randint(1, ob))
120
+ probs.append((a, b, p))
121
+ n_p = max(p.bit_length() for _, _, p in probs) + PAD_HEAD
122
+ L = max(2, max(max(a.bit_length(), b.bit_length())
123
+ for a, b, _ in probs))
124
+ L += L % 2
125
+ t0 = time.time()
126
+ z = mach.run(_pack([a for a, _, _ in probs], L),
127
+ _pack([b for _, b, _ in probs], L),
128
+ _pack([p for _, _, p in probs], n_p),
129
+ _pack([3 * p for _, _, p in probs], n_p))
130
+ dt = time.time() - t0
131
+ good = 0
132
+ for r, (a, b, p) in enumerate(probs):
133
+ got = int("".join(str(int(v)) for v in z[r].tolist()), 2)
134
+ good += (got == (a * b) % p)
135
+ results[t] = (good, per_tier, dt)
136
+ print(f" tier {t}: {good}/{per_tier} exact ({dt:.1f}s for batch)")
137
+ return results
138
+
139
+
140
+ @torch.no_grad()
141
+ def batch_invariance(rcell, acell, rng):
142
+ print("== batch-composition invariance ==")
143
+ mach = BitStreamMachine(rcell, acell, torch.device("cpu"))
144
+ p = random_prime(rng, 60, 64)
145
+ a, b = rng.getrandbits(128), rng.getrandbits(128)
146
+
147
+ def run_with(width_pad, extra_p_bits):
148
+ n_p = p.bit_length() + PAD_HEAD + extra_p_bits
149
+ L = 128 + width_pad
150
+ L += L % 2
151
+ z = mach.run(_pack([a], L), _pack([b], L),
152
+ _pack([p], n_p), _pack([3 * p], n_p))
153
+ return int("".join(str(int(v)) for v in z[0].tolist()), 2)
154
+
155
+ vals = {run_with(wp, ep) for wp in (0, 8, 32) for ep in (0, 5, 40)}
156
+ ok = len(vals) == 1 and vals == {(a * b) % p}
157
+ print(f" distinct outputs across paddings: {len(vals)} (want 1), "
158
+ f"correct={ok}")
159
+ return ok
160
+
161
+
162
+ @torch.no_grad()
163
+ def perturbation(rcell, acell, rng):
164
+ print("== weight-perturbation collapse (compliance evidence) ==")
165
+ import copy
166
+ for scale in (0.0, 0.02, 0.1):
167
+ r2, m2 = copy.deepcopy(rcell), copy.deepcopy(acell)
168
+ if scale:
169
+ for c in (r2, m2):
170
+ for prm in c.parameters():
171
+ prm.add_(torch.randn_like(prm) * scale
172
+ * (prm.abs().mean() + 1e-8))
173
+ res = machine_tier_check(r2, m2, random.Random(7), 20, tiers=[3])
174
+ g, n, _ = res[3]
175
+ print(f" noise scale {scale}: tier-3 accuracy {g}/{n}")
176
+
177
+
178
+ def main():
179
+ ap = argparse.ArgumentParser()
180
+ ap.add_argument("ckpt")
181
+ ap.add_argument("--quick", action="store_true")
182
+ ap.add_argument("--tiers", type=int, nargs="*", default=None)
183
+ ap.add_argument("--per-tier", type=int, default=100)
184
+ ap.add_argument("--per-width", type=int, default=200_000)
185
+ ap.add_argument("--seed", type=int, default=123)
186
+ ap.add_argument("--skip-stress", action="store_true")
187
+ args = ap.parse_args()
188
+
189
+ torch.set_num_threads(8)
190
+ rng = random.Random(args.seed)
191
+ rcell, acell = load_cells(args.ckpt)
192
+
193
+ widths = [5, 6, 8, 11, 15, 19, 23, 27, 31, 35, 36,
194
+ ]
195
+ per_width = 20_000 if args.quick else args.per_width
196
+ per_tier = 30 if args.quick else args.per_tier
197
+
198
+ worst = 1.0
199
+ if not args.skip_stress:
200
+ worst = cell_stress(rcell, acell, rng, widths, per_width)
201
+ machine_tier_check(rcell, acell, rng, per_tier, tiers=args.tiers)
202
+ inv = batch_invariance(rcell, acell, rng)
203
+ if not args.quick:
204
+ perturbation(rcell, acell, rng)
205
+ print(f"\nworst cell width rate: {worst:.6f}; batch-invariant: {inv}")
206
+
207
+
208
+ if __name__ == "__main__":
209
+ main()
weights.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8d127056acf311a229b07657a63509994adc4615105afb5e1f5f20b2450c039a
3
+ size 210797