omega-helix
This project has not described itself yet.
Brought by drakestapleton
omega-helix / tests / test_sp_closed_form.py
| 1 | #!/usr/bin/env python3 |
| 2 | # SPDX-License-Identifier: AGPL-3.0-only |
| 3 | """Pillar 7 Verification: Closed-Form Specialist Solver (Ridge / Woodbury / 1-Step Gauss-Newton). |
| 4 | |
| 5 | Verifies native/sp_solve.om: |
| 6 | 1. Compiles cleanly with math..spec for BOTH `target a64macos` and `gb10` (`om2`). |
| 7 | 2. Exact f64 linear-algebra oracle (< 1e-10 max abs error): |
| 8 | - Primal Cholesky (D <= N): (H^T H + lambda I) W = H^T Y |
| 9 | - Dual Woodbury (N < D): W = H^T (H H^T + lambda I)^{-1} Y (auto regime switch) |
| 10 | - Primal vs Dual Woodbury cross-parity (< 1e-12) |
| 11 | - 1-Step Gauss-Newton softmax CE refinement (`sp_gauss_newton_step`) for both D <= N and N < D |
| 12 | 3. End-to-end fcache / fcachem -> spforge -> OLLMSP01 .sp -> ollm spapp & ollm spchainapp: |
| 13 | - Both Primal (F <= N) and Dual Woodbury (N < F) specialist forging regimes |
| 14 | - Sleep-consolidation entrypoint (`spforge_consolidate_traces`) |
| 15 | - ollm eval(SPEC.ck) == ollm speval(BASE.ck, OUT.sp) bit-identical, CE loss strictly reduced |
| 16 | - Multi-link Merkle specialist chain (P1.sp -> P2.sp via ollm spchainapp) |
| 17 | 4. Speed vs iterative backprop (`trainfc`). |
| 18 | 5. Negative controls: |
| 19 | - 1-bit tampered .sp -> ollm spapp exits rc=61 |
| 20 | - Truncated .sp -> ollm spapp exits rc=60 |
| 21 | - Mismatched base checkpoint -> ollm spapp / spforge exits rc=62 |
| 22 | """ |
| 23 | import math |
| 24 | import os |
| 25 | import platform |
| 26 | import random |
| 27 | import re |
| 28 | import shutil |
| 29 | import struct |
| 30 | import subprocess |
| 31 | import sys |
| 32 | import tempfile |
| 33 | import time |
| 34 | |
| 35 | HERE = os.path.dirname(os.path.abspath(__file__)) |
| 36 | REPO = os.path.dirname(HERE) |
| 37 | SRC = os.path.join(REPO, "native") |
| 38 | |
| 39 | PASSES = [] |
| 40 | FAILS = [] |
| 41 | |
| 42 | |
| 43 | def check(cond, name, detail=""): |
| 44 | if cond: |
| 45 | PASSES.append(name) |
| 46 | print(f"PASS {name}" + (f" ({detail})" if detail else "")) |
| 47 | else: |
| 48 | FAILS.append(name) |
| 49 | print(f"FAIL {name}" + (f": {detail}" if detail else "")) |
| 50 | |
| 51 | |
| 52 | def read_text(path): |
| 53 | with open(path, "r", encoding="utf-8") as f: |
| 54 | return f.read() |
| 55 | |
| 56 | |
| 57 | def read_bytes(path): |
| 58 | with open(path, "rb") as f: |
| 59 | return f.read() |
| 60 | |
| 61 | |
| 62 | def find_omc(): |
| 63 | omc = os.environ.get("OMC") or shutil.which("omc") or os.path.expanduser("~/.local/bin/omc") |
| 64 | if not os.path.isfile(omc): |
| 65 | raise RuntimeError(f"omc not found at {omc}") |
| 66 | return omc |
| 67 | |
| 68 | |
| 69 | def run(args, cwd=None, env=None, ok=(0,)): |
| 70 | p = subprocess.run(args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 71 | out = p.stdout.decode("latin-1") |
| 72 | err = p.stderr.decode("latin-1") |
| 73 | if ok is not None and p.returncode not in ok: |
| 74 | raise RuntimeError(f"{' '.join(args)} -> rc={p.returncode}\nstdout:\n{out}\nstderr:\n{err}") |
| 75 | return p.returncode, out, err |
| 76 | |
| 77 | |
| 78 | def compile_om(om_text, bin_path): |
| 79 | omc = find_omc() |
| 80 | tmp = bin_path + ".tmp" |
| 81 | p = subprocess.run([omc], input=om_text.encode("utf-8"), stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 82 | if p.returncode != 0: |
| 83 | raise RuntimeError(f"omc failed rc={p.returncode}: {p.stderr.decode('latin-1')}") |
| 84 | with open(tmp, "wb") as f: |
| 85 | f.write(p.stdout) |
| 86 | os.chmod(tmp, 0o755) |
| 87 | os.replace(tmp, bin_path) |
| 88 | if platform.system() == "Darwin" and shutil.which("codesign"): |
| 89 | subprocess.run(["codesign", "-s", "-", "-f", bin_path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) |
| 90 | |
| 91 | |
| 92 | def build_stock_ollm(out_dir): |
| 93 | target = "macos" if platform.system() == "Darwin" else ("x86linux" if platform.machine().lower() in ("x86_64", "amd64") else "aarch64") |
| 94 | bin_name = {"macos": "ollm-macos", "x86linux": "ollm-x86linux", "aarch64": "ollm"}[target] |
| 95 | env = dict(os.environ, TARGET=target, OUT=out_dir) |
| 96 | run(["sh", os.path.join(REPO, "scripts", "build.sh")], env=env) |
| 97 | return os.path.join(out_dir, bin_name) |
| 98 | |
| 99 | |
| 100 | # ---------------- Pure-Python IEEE-754 f64 Linear Algebra Oracle ---------------- |
| 101 | |
| 102 | def py_cholesky_solve(A, B): |
| 103 | """Exact f64 Cholesky LL^T solve A X = B where A is m x m SPD and B is m x k.""" |
| 104 | m = len(A) |
| 105 | k = len(B[0]) if m > 0 else 0 |
| 106 | L = [[0.0] * m for _ in range(m)] |
| 107 | for j in range(m): |
| 108 | s = A[j][j] - sum(L[j][p] * L[j][p] for p in range(j)) |
| 109 | if s <= 0.0: |
| 110 | raise ValueError(f"Non-SPD pivot at {j}: {s}") |
| 111 | L[j][j] = math.sqrt(s) |
| 112 | invd = 1.0 / L[j][j] |
| 113 | for i in range(j + 1, m): |
| 114 | t = A[i][j] - sum(L[i][p] * L[j][p] for p in range(j)) |
| 115 | L[i][j] = t * invd |
| 116 | X = [[0.0] * k for _ in range(m)] |
| 117 | for col in range(k): |
| 118 | z = [0.0] * m |
| 119 | for i in range(m): |
| 120 | s = B[i][col] - sum(L[i][j] * z[j] for j in range(i)) |
| 121 | z[i] = s / L[i][i] |
| 122 | for i in range(m - 1, -1, -1): |
| 123 | s = z[i] - sum(L[j][i] * X[j][col] for j in range(i + 1, m)) |
| 124 | X[i][col] = s / L[i][i] |
| 125 | return X |
| 126 | |
| 127 | |
| 128 | def py_ridge_oracle(H, Y, lam): |
| 129 | """Exact f64 Ridge regression (H^T H + lam I)^{-1} H^T Y.""" |
| 130 | n = len(H) |
| 131 | d = len(H[0]) |
| 132 | c = len(Y[0]) |
| 133 | if d <= n: |
| 134 | G = [[0.0] * d for _ in range(d)] |
| 135 | for a in range(d): |
| 136 | for b in range(a + 1): |
| 137 | v = sum(H[i][a] * H[i][b] for i in range(n)) |
| 138 | if a == b: |
| 139 | v += lam |
| 140 | G[a][b] = G[b][a] = v |
| 141 | R = [[sum(H[i][a] * Y[i][col] for i in range(n)) for col in range(c)] for a in range(d)] |
| 142 | return py_cholesky_solve(G, R) |
| 143 | K = [[0.0] * n for _ in range(n)] |
| 144 | for i in range(n): |
| 145 | for j in range(i + 1): |
| 146 | v = sum(H[i][a] * H[j][a] for a in range(d)) |
| 147 | if i == j: |
| 148 | v += lam |
| 149 | K[i][j] = K[j][i] = v |
| 150 | A = py_cholesky_solve(K, Y) |
| 151 | return [[sum(H[i][a] * A[i][col] for i in range(n)) for col in range(c)] for a in range(d)] |
| 152 | |
| 153 | |
| 154 | def py_softmax_ce(H, W, targets): |
| 155 | n = len(H) |
| 156 | d = len(H[0]) |
| 157 | c = len(W[0]) |
| 158 | P = [[0.0] * c for _ in range(n)] |
| 159 | loss = 0.0 |
| 160 | for i in range(n): |
| 161 | logits = [sum(H[i][a] * W[a][col] for a in range(d)) for col in range(c)] |
| 162 | mx = max(logits) |
| 163 | exps = [math.exp(v - mx) for v in logits] |
| 164 | sm = sum(exps) |
| 165 | P[i] = [e / sm for e in exps] |
| 166 | loss += mx + math.log(sm) - logits[targets[i]] |
| 167 | return P, loss / n |
| 168 | |
| 169 | |
| 170 | def py_gauss_newton_oracle(H, W, targets, lam, eta): |
| 171 | """Exact f64 1-step Gauss-Newton: (H^T diag(p*(1-p)) H + lam I) dW = H^T (y_onehot - p).""" |
| 172 | n = len(H) |
| 173 | d = len(H[0]) |
| 174 | c = len(W[0]) |
| 175 | P, l0 = py_softmax_ce(H, W, targets) |
| 176 | dW = [[0.0] * c for _ in range(d)] |
| 177 | for col in range(c): |
| 178 | w = [P[i][col] * (1.0 - P[i][col]) for i in range(n)] |
| 179 | r = [(1.0 if targets[i] == col else 0.0) - P[i][col] for i in range(n)] |
| 180 | G = [[0.0] * d for _ in range(d)] |
| 181 | for a in range(d): |
| 182 | for b in range(a + 1): |
| 183 | v = sum(w[i] * H[i][a] * H[i][b] for i in range(n)) |
| 184 | if a == b: |
| 185 | v += lam |
| 186 | G[a][b] = G[b][a] = v |
| 187 | rhs = [[sum(H[i][a] * r[i] for i in range(n))] for a in range(d)] |
| 188 | sol = py_cholesky_solve(G, rhs) |
| 189 | for a in range(d): |
| 190 | dW[a][col] = sol[a][0] |
| 191 | W_new = [[W[a][col] + eta * dW[a][col] for col in range(c)] for a in range(d)] |
| 192 | _, l1 = py_softmax_ce(H, W_new, targets) |
| 193 | return l0, l1, W_new |
| 194 | |
| 195 | |
| 196 | # ---------------- OM Test Harness Generator ---------------- |
| 197 | |
| 198 | HARNESS_OM = r""" |
| 199 | note Minimal test harness for sp_solve.om unit & integration tests (not part of production build) |
| 200 | fn th_rd_f64 off ulong to f64 |
| 201 | ret bitcast f64 opw8 mul off 8 |
| 202 | end |
| 203 | |
| 204 | fn th_rd_u64 off ulong to ulong |
| 205 | ret opw8 mul off 8 |
| 206 | end |
| 207 | |
| 208 | fn th_load_f64 dst ulong src_off ulong n ulong to void |
| 209 | for i ulong n |
| 210 | ocsp add dst i th_rd_f64 add src_off i |
| 211 | end |
| 212 | end |
| 213 | |
| 214 | fn th_load_tgt src_off ulong n ulong to void |
| 215 | for t ulong n |
| 216 | put osp_tgt t th_rd_u64 add src_off t |
| 217 | end |
| 218 | end |
| 219 | |
| 220 | fn th_wr_f64 src ulong n ulong out_off ulong to void |
| 221 | for k ulong n |
| 222 | ocput8 mul add out_off k 8 bitcast ulong ocsg add src k |
| 223 | end |
| 224 | end |
| 225 | |
| 226 | fn th_ridge_run mode ulong n ulong d ulong c ulong lam f64 to ulong |
| 227 | if eq mode 0 |
| 228 | ret sp_ridge_solve n d c lam |
| 229 | end |
| 230 | if eq mode 1 |
| 231 | put osp_st 9 0 |
| 232 | ret sp_ridge_primal n d c lam |
| 233 | end |
| 234 | put osp_st 9 1 |
| 235 | ret sp_ridge_woodbury n d c lam |
| 236 | end |
| 237 | |
| 238 | fn th_cmd_ridge to void |
| 239 | c_ocs = ocsinit |
| 240 | sz = ofsz 2 |
| 241 | if ne oprd 2 0 0 sz sz |
| 242 | exit 70 |
| 243 | end |
| 244 | n = th_rd_u64 0 |
| 245 | d = th_rd_u64 1 |
| 246 | c = th_rd_u64 2 |
| 247 | lam = th_rd_f64 3 |
| 248 | put osp_st 0 n |
| 249 | put osp_st 1 d |
| 250 | put osp_st 2 c |
| 251 | put osp_st 3 0 |
| 252 | yo = mul n d |
| 253 | put osp_st 4 yo |
| 254 | wo = add yo mul n c |
| 255 | put osp_st 5 wo |
| 256 | ao = add wo mul d c |
| 257 | put osp_st 6 ao |
| 258 | msz = d |
| 259 | if gt n d |
| 260 | msz = n |
| 261 | end |
| 262 | put osp_st 7 add ao mul msz msz |
| 263 | th_load_f64 0 5 yo |
| 264 | th_load_f64 yo add 5 yo mul n c |
| 265 | rc = th_ridge_run th_rd_u64 4 n d c lam |
| 266 | ocwopen 3 |
| 267 | ocput8 0 get osp_st 9 |
| 268 | ocput8 8 rc |
| 269 | dc = mul d c |
| 270 | th_wr_f64 wo dc 2 |
| 271 | ocwput 0 mul add 2 dc 8 |
| 272 | ocwend 3 |
| 273 | end |
| 274 | |
| 275 | fn th_gn_layout n ulong d ulong c ulong to void |
| 276 | wo = mul n d |
| 277 | msz = d |
| 278 | if gt n d |
| 279 | msz = n |
| 280 | end |
| 281 | ao = add wo mul d c |
| 282 | bo = add ao mul msz msz |
| 283 | put osp_st 3 0 |
| 284 | put osp_st 5 wo |
| 285 | put osp_st 6 ao |
| 286 | put osp_st 7 bo |
| 287 | put osp_st 8 add bo msz |
| 288 | end |
| 289 | |
| 290 | fn th_cmd_gn to void |
| 291 | c_ocs = ocsinit |
| 292 | sz = ofsz 2 |
| 293 | if ne oprd 2 0 0 sz sz |
| 294 | exit 70 |
| 295 | end |
| 296 | n = th_rd_u64 0 |
| 297 | d = th_rd_u64 1 |
| 298 | c = th_rd_u64 2 |
| 299 | th_gn_layout n d c |
| 300 | nd = mul n d |
| 301 | dc = mul d c |
| 302 | th_load_f64 0 5 nd |
| 303 | th_load_f64 nd add 5 nd dc |
| 304 | th_load_tgt add add 5 nd dc n |
| 305 | rc = sp_gauss_newton_step n d c th_rd_f64 3 th_rd_f64 4 |
| 306 | ocwopen 3 |
| 307 | ocput8 0 get osp_st 9 |
| 308 | ocput8 8 rc |
| 309 | ocput8 16 bitcast ulong get osp_fl 2 |
| 310 | ocput8 24 bitcast ulong get osp_fl 3 |
| 311 | th_wr_f64 nd dc 4 |
| 312 | ocwput 0 mul add 4 dc 8 |
| 313 | ocwend 3 |
| 314 | end |
| 315 | |
| 316 | fn th_cmd_sleep to void |
| 317 | c_ocs = ocsinit |
| 318 | ockloop 2 |
| 319 | sz = ofsz 3 |
| 320 | if ne oprd 3 0 0 sz sz |
| 321 | exit 70 |
| 322 | end |
| 323 | n = th_rd_u64 0 |
| 324 | dd = get og 2 |
| 325 | nd = mul n dd |
| 326 | th_load_f64 0 3 nd |
| 327 | th_load_tgt add 3 nd n |
| 328 | rc = spforge_consolidate_traces 4 n th_rd_f64 1 th_rd_u64 2 |
| 329 | if ne rc 0 |
| 330 | exit int rc |
| 331 | end |
| 332 | oputc 83 |
| 333 | oputc 80 |
| 334 | oputc 67 |
| 335 | oputc 79 |
| 336 | oputc 78 |
| 337 | oputc 83 |
| 338 | oputc 79 |
| 339 | oputc 76 |
| 340 | oputc 32 |
| 341 | oputu get osp_st 9 |
| 342 | oputc 32 |
| 343 | oputl rmic get osp_fl 2 |
| 344 | oputc 32 |
| 345 | oputl rmic get osp_fl 3 |
| 346 | oputc 10 |
| 347 | oflush |
| 348 | end |
| 349 | |
| 350 | fn th_cmd_ocs to void |
| 351 | c_ocs = ocsinit |
| 352 | mode = oargu 2 |
| 353 | if eq mode 1 |
| 354 | x = ocsg c_ocs |
| 355 | exit 0 |
| 356 | end |
| 357 | if eq mode 2 |
| 358 | ocsp c_ocs 1.0f64 |
| 359 | exit 0 |
| 360 | end |
| 361 | if ne ocsg 100000 0.0f64 |
| 362 | exit 71 |
| 363 | end |
| 364 | ocsp 0 1.5f64 |
| 365 | ocsp 100000 42.25f64 |
| 366 | if ne ocsg 0 1.5f64 |
| 367 | exit 72 |
| 368 | end |
| 369 | if ne ocsg 100000 42.25f64 |
| 370 | exit 73 |
| 371 | end |
| 372 | end |
| 373 | |
| 374 | fn ocmd to int |
| 375 | w = ocmdw |
| 376 | if eq w __SPFORGE__ |
| 377 | cmdspforge |
| 378 | ret 0 |
| 379 | end |
| 380 | if eq w __TRIDGE__ |
| 381 | th_cmd_ridge |
| 382 | ret 0 |
| 383 | end |
| 384 | if eq w __TGN__ |
| 385 | th_cmd_gn |
| 386 | ret 0 |
| 387 | end |
| 388 | if eq w __TSLEEP__ |
| 389 | th_cmd_sleep |
| 390 | ret 0 |
| 391 | end |
| 392 | if eq w __TOCS__ |
| 393 | th_cmd_ocs |
| 394 | ret 0 |
| 395 | end |
| 396 | ret ocmd_orig |
| 397 | end |
| 398 | """ |
| 399 | |
| 400 | |
| 401 | def u64_pack_word(word): |
| 402 | v = 0 |
| 403 | for i, ch in enumerate(word.encode("ascii")): |
| 404 | v |= ch << (8 * i) |
| 405 | return v |
| 406 | |
| 407 | |
| 408 | def build_solver_harness(out_dir): |
| 409 | harness_om = ( |
| 410 | HARNESS_OM |
| 411 | .replace("__SPFORGE__", str(u64_pack_word("spforge"))) |
| 412 | .replace("__TRIDGE__", str(u64_pack_word("tridge"))) |
| 413 | .replace("__TGN__", str(u64_pack_word("tgn"))) |
| 414 | .replace("__TSLEEP__", str(u64_pack_word("tsleep"))) |
| 415 | .replace("__TOCS__", str(u64_pack_word("tocs"))) |
| 416 | ) |
| 417 | is_mac = platform.system() == "Darwin" |
| 418 | is_x86 = platform.system() == "Linux" and platform.machine().lower() in ("x86_64", "amd64") |
| 419 | plat = "mio.om" if is_mac else "lio.om" |
| 420 | rev_unit = "norev.om" if is_x86 else "rev.om" |
| 421 | units = ["math.om", "data.om", "lpool.om", "model.om", "adam.om", "ckpt.om", "bpe.om", "spec.om", rev_unit, "arboris.om", "sp_solve.om", "spiral.om", "apu_weave.om", "omg.om", "pillars_cli.om"] |
| 422 | apu_fab = ["apu_fabric_macos.om"] if is_mac else ["apu_fabric_linux.om", "apu_fabric_nogpu.om"] |
| 423 | cli_txt = read_text(os.path.join(SRC, "cli.om")).replace("fn ocmd to int", "fn ocmd_orig to int", 1) |
| 424 | src_text = "target a64macos\nom2\n" if is_mac else ("target x86linux\nom2\n" if is_x86 else "om2\n") |
| 425 | src_text += "\n".join(read_text(os.path.join(SRC, u)) for u in units) |
| 426 | src_text += "\n" + cli_txt + "\n" + harness_om + "\n" + read_text(os.path.join(SRC, plat)) |
| 427 | src_text += "\n" + read_text(os.path.join(SRC, "noserve.om")) + "\n" + read_text(os.path.join(SRC, "nogpu.om")) |
| 428 | src_text += "\n" + "\n".join(read_text(os.path.join(SRC, u)) for u in apu_fab) |
| 429 | harness_bin = os.path.join(out_dir, "sp_harness") |
| 430 | compile_om(src_text, harness_bin) |
| 431 | return harness_bin |
| 432 | |
| 433 | |
| 434 | def test_cross_target_compile(): |
| 435 | """Verify sp_solve.om compiles cleanly with math..spec for host target and gb10 (om2).""" |
| 436 | with tempfile.TemporaryDirectory() as td: |
| 437 | units = ["math.om", "data.om", "lpool.om", "model.om", "adam.om", "ckpt.om", "bpe.om", "spec.om", "rev.om", "arboris.om", "sp_solve.om", "spiral.om", "apu_weave.om", "omg.om", "pillars_cli.om", "cli.om"] |
| 438 | if platform.system() == "Darwin": |
| 439 | mac_text = "target a64macos\nom2\n" + "\n".join(read_text(os.path.join(SRC, u)) for u in units + ["mio.om", "noserve.om", "nogpu.om", "apu_fabric_macos.om"]) |
| 440 | mac_bin = os.path.join(td, "ollm-macos") |
| 441 | compile_om(mac_text, mac_bin) |
| 442 | check(os.path.getsize(mac_bin) > 0, "compile_target_a64macos", f"{os.path.getsize(mac_bin)} B") |
| 443 | |
| 444 | gb_units = ["net/http.om", "net/json.om", "net/jsonw.om"] + units + [ |
| 445 | "lio.om", "serve.om", |
| 446 | "gpu/context.om", "gpu/vector.om", "gpu/launch.om", "gpu/batch.om", |
| 447 | "gpu/gk.om", "gpu/gr.om", "gpu/gb.om", "gpu/gg.om", |
| 448 | "gpu/gt.om", "gpu/gm.om", "gpu/ring.om", "gpu/ejit.om", |
| 449 | "apu_fabric_linux.om", "apu_fabric_gb10.om", |
| 450 | ] |
| 451 | gb_text = "om2\n" + "\n".join(read_text(os.path.join(SRC, u)) for u in gb_units) |
| 452 | gb_bin = os.path.join(td, "ollm-gb10") |
| 453 | compile_om(gb_text, gb_bin) |
| 454 | check(os.path.getsize(gb_bin) > 0, "compile_target_gb10_om2", f"{os.path.getsize(gb_bin)} B") |
| 455 | |
| 456 | |
| 457 | def run_ridge_case(harness, td, tag, H, Y, lam, mode=0): |
| 458 | n, d, c = len(H), len(H[0]), len(Y[0]) |
| 459 | inp = os.path.join(td, f"{tag}_in.bin") |
| 460 | outp = os.path.join(td, f"{tag}_out.bin") |
| 461 | with open(inp, "wb") as f: |
| 462 | f.write(struct.pack("<QQQdQ", n, d, c, lam, mode)) |
| 463 | for row in H: |
| 464 | f.write(struct.pack(f"<{d}d", *row)) |
| 465 | for row in Y: |
| 466 | f.write(struct.pack(f"<{c}d", *row)) |
| 467 | run([harness, "tridge", inp, outp]) |
| 468 | data = read_bytes(outp) |
| 469 | regime, rc = struct.unpack("<QQ", data[:16]) |
| 470 | flat = struct.unpack(f"<{d * c}d", data[16:]) |
| 471 | W = [list(flat[a * c:(a + 1) * c]) for a in range(d)] |
| 472 | return regime, rc, W |
| 473 | |
| 474 | |
| 475 | def run_gn_case(harness, td, tag, H, W, targets, lam, eta): |
| 476 | n, d, c = len(H), len(H[0]), len(W[0]) |
| 477 | inp = os.path.join(td, f"{tag}_in.bin") |
| 478 | outp = os.path.join(td, f"{tag}_out.bin") |
| 479 | with open(inp, "wb") as f: |
| 480 | f.write(struct.pack("<QQQdd", n, d, c, lam, eta)) |
| 481 | for row in H: |
| 482 | f.write(struct.pack(f"<{d}d", *row)) |
| 483 | for row in W: |
| 484 | f.write(struct.pack(f"<{c}d", *row)) |
| 485 | f.write(struct.pack(f"<{n}Q", *targets)) |
| 486 | run([harness, "tgn", inp, outp]) |
| 487 | data = read_bytes(outp) |
| 488 | regime, rc, l0, l1 = struct.unpack("<QQdd", data[:32]) |
| 489 | flat = struct.unpack(f"<{d * c}d", data[32:]) |
| 490 | W_new = [list(flat[a * c:(a + 1) * c]) for a in range(d)] |
| 491 | return regime, rc, l0, l1, W_new |
| 492 | |
| 493 | |
| 494 | def max_abs_diff(A, B): |
| 495 | return max(abs(A[i][j] - B[i][j]) for i in range(len(A)) for j in range(len(A[0]))) |
| 496 | |
| 497 | |
| 498 | def test_linear_algebra_oracle(harness): |
| 499 | rng = random.Random(20261125) |
| 500 | with tempfile.TemporaryDirectory() as td: |
| 501 | # 1. Primal Ridge (D <= N): N=24, D=8, C=4 |
| 502 | H1 = [[rng.gauss(0.0, 1.0) for _ in range(8)] for _ in range(24)] |
| 503 | Y1 = [[rng.gauss(0.0, 1.0) for _ in range(4)] for _ in range(24)] |
| 504 | reg1, rc1, W1 = run_ridge_case(harness, td, "primal", H1, Y1, 0.25, mode=0) |
| 505 | W1_ref = py_ridge_oracle(H1, Y1, 0.25) |
| 506 | err1 = max_abs_diff(W1, W1_ref) |
| 507 | check(rc1 == 0 and reg1 == 0 and err1 < 1e-10, "ridge_primal_d_le_n", f"regime={reg1}, max_err={err1:.3e}") |
| 508 | |
| 509 | # 2. Dual Woodbury (N < D): N=10, D=28, C=5 |
| 510 | H2 = [[rng.gauss(0.0, 1.0) for _ in range(28)] for _ in range(10)] |
| 511 | Y2 = [[rng.gauss(0.0, 1.0) for _ in range(5)] for _ in range(10)] |
| 512 | reg2, rc2, W2 = run_ridge_case(harness, td, "woodbury", H2, Y2, 0.15, mode=0) |
| 513 | W2_ref = py_ridge_oracle(H2, Y2, 0.15) |
| 514 | err2 = max_abs_diff(W2, W2_ref) |
| 515 | check(rc2 == 0 and reg2 == 1 and err2 < 1e-10, "ridge_woodbury_n_lt_d", f"regime={reg2}, max_err={err2:.3e}") |
| 516 | |
| 517 | # 3. Primal vs Dual Woodbury cross-parity on same N < D problem |
| 518 | _, rc2p, W2p = run_ridge_case(harness, td, "wood_vs_pri", H2, Y2, 0.15, mode=1) |
| 519 | err_pw = max_abs_diff(W2, W2p) |
| 520 | check(rc2p == 0 and err_pw < 1e-12, "ridge_primal_woodbury_parity", f"max_err={err_pw:.3e}") |
| 521 | |
| 522 | # 4. 1-Step Gauss-Newton (Primal D <= N): N=20, D=6, C=5 |
| 523 | H3 = [[rng.gauss(0.0, 0.8) for _ in range(6)] for _ in range(20)] |
| 524 | W3 = [[rng.gauss(0.0, 0.3) for _ in range(5)] for _ in range(6)] |
| 525 | tgt3 = [rng.randrange(5) for _ in range(20)] |
| 526 | g_reg3, g_rc3, l0_3, l1_3, W3_new = run_gn_case(harness, td, "gn_primal", H3, W3, tgt3, 0.1, 1.0) |
| 527 | l0_3_ref, l1_3_ref, W3_ref = py_gauss_newton_oracle(H3, W3, tgt3, 0.1, 1.0) |
| 528 | err3 = max_abs_diff(W3_new, W3_ref) |
| 529 | check( |
| 530 | g_rc3 == 0 and g_reg3 == 0 and err3 < 1e-10 and abs(l0_3 - l0_3_ref) < 1e-12 and abs(l1_3 - l1_3_ref) < 1e-12 and l1_3 < l0_3, |
| 531 | "gauss_newton_primal", |
| 532 | f"regime={g_reg3}, max_err={err3:.3e}, ce={l0_3:.6f}->{l1_3:.6f}", |
| 533 | ) |
| 534 | |
| 535 | # 5. 1-Step Gauss-Newton (Dual Weighted Woodbury N < D): N=8, D=20, C=4 |
| 536 | H4 = [[rng.gauss(0.0, 0.7) for _ in range(20)] for _ in range(8)] |
| 537 | W4 = [[rng.gauss(0.0, 0.2) for _ in range(4)] for _ in range(20)] |
| 538 | tgt4 = [rng.randrange(4) for _ in range(8)] |
| 539 | g_reg4, g_rc4, l0_4, l1_4, W4_new = run_gn_case(harness, td, "gn_wood", H4, W4, tgt4, 0.2, 1.0) |
| 540 | l0_4_ref, l1_4_ref, W4_ref = py_gauss_newton_oracle(H4, W4, tgt4, 0.2, 1.0) |
| 541 | err4 = max_abs_diff(W4_new, W4_ref) |
| 542 | check( |
| 543 | g_rc4 == 0 and g_reg4 == 1 and err4 < 1e-10 and abs(l0_4 - l0_4_ref) < 1e-12 and abs(l1_4 - l1_4_ref) < 1e-12 and l1_4 < l0_4, |
| 544 | "gauss_newton_woodbury", |
| 545 | f"regime={g_reg4}, max_err={err4:.3e}, ce={l0_4:.6f}->{l1_4:.6f}", |
| 546 | ) |
| 547 | |
| 548 | |
| 549 | def parse_eval(out): |
| 550 | m = re.search(r"E\s+(\d+)\s+(\d+)\s+(-?\d+)\s+(-?\d+)", out) |
| 551 | if not m: |
| 552 | raise RuntimeError(f"Cannot parse eval output:\n{out}") |
| 553 | return int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4)) |
| 554 | |
| 555 | |
| 556 | def parse_spforge(out): |
| 557 | m = re.search(r"SPFORGE\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(-?\d+)\s+(-?\d+)\s+(\d+)", out) |
| 558 | if not m: |
| 559 | raise RuntimeError(f"Cannot parse SPFORGE output:\n{out}") |
| 560 | return tuple(int(m.group(i)) for i in range(1, 8)) |
| 561 | |
| 562 | |
| 563 | def write_pattern_tokens_and_mask(tok_path, mask_path, n_bytes, T, mask_every=4): |
| 564 | """Deterministic pattern tokens so a frozen base has meaningful learnable structure.""" |
| 565 | pattern = bytes([(32 + (i % 13) * 3) & 0xFF for i in range(n_bytes)]) |
| 566 | with open(tok_path, "wb") as f: |
| 567 | f.write(pattern) |
| 568 | # Mask: 1 for target prediction, 0 periodically (masked out by fcachem!) |
| 569 | mask = bytes([0 if (i % mask_every == 0) else 1 for i in range(n_bytes)]) |
| 570 | with open(mask_path, "wb") as f: |
| 571 | f.write(mask) |
| 572 | return pattern, mask |
| 573 | |
| 574 | |
| 575 | def test_end_to_end_spforge_and_negative_controls(ollm, harness): |
| 576 | with tempfile.TemporaryDirectory() as td: |
| 577 | # Model: V=256, T=8, D=16, H=2, F=32, L=1, B=1 |
| 578 | base_ck = os.path.join(td, "base.ck") |
| 579 | run([ollm, "init", base_ck, "256", "8", "16", "2", "32", "1", "1", "77", "20", "5000"]) |
| 580 | |
| 581 | toks = os.path.join(td, "train.tok") |
| 582 | mask = os.path.join(td, "train.msk") |
| 583 | # 12 windows * 8 = 96 + 1 = 97 bytes; with mask_every=4 -> 72 unmasked tokens (> F=32 -> Primal!) |
| 584 | write_pattern_tokens_and_mask(toks, mask, 97, 8, mask_every=4) |
| 585 | |
| 586 | # Warm up both binaries once (macOS codesign first-launch cache) before timing |
| 587 | run([harness], ok=None) |
| 588 | run([ollm], ok=None) |
| 589 | |
| 590 | # ---- Regime A: fcachem -> spforge Primal (F=32 <= N=72) ---- |
| 591 | hc_primal = os.path.join(td, "primal.hc") |
| 592 | run([ollm, "fcachem", base_ck, toks, mask, "12", hc_primal]) |
| 593 | |
| 594 | sp_primal = os.path.join(td, "primal.sp") |
| 595 | t0 = time.perf_counter() |
| 596 | _, out_pf, _ = run([harness, "spforge", base_ck, hc_primal, sp_primal, "100000", "1"]) |
| 597 | forge_s = time.perf_counter() - t0 |
| 598 | bl, sl, n_act, reg_p, l0_m, l1_m, nspec = parse_spforge(out_pf) |
| 599 | check( |
| 600 | bl == 1 and sl == 2 and n_act == 72 and reg_p == 0 and l1_m < l0_m, |
| 601 | "spforge_fcachem_primal", |
| 602 | f"N={n_act}, regime={reg_p}, loss={l0_m}->{l1_m} unats, {forge_s*1000:.2f}ms", |
| 603 | ) |
| 604 | |
| 605 | # Apply via stock ollm spapp and verify eval == speval bit-for-bit & loss reduction |
| 606 | spec_ck = os.path.join(td, "spec_primal.ck") |
| 607 | run([ollm, "spapp", base_ck, sp_primal, spec_ck]) |
| 608 | _, ev_base, _ = run([ollm, "eval", base_ck, toks, "12"]) |
| 609 | _, ev_spec, _ = run([ollm, "eval", spec_ck, toks, "12"]) |
| 610 | _, ev_sp, _ = run([ollm, "speval", base_ck, sp_primal, toks, "12"]) |
| 611 | b_loss = parse_eval(ev_base)[2] |
| 612 | s_loss = parse_eval(ev_spec)[2] |
| 613 | sp_loss = parse_eval(ev_sp)[2] |
| 614 | check( |
| 615 | s_loss == sp_loss and s_loss < b_loss, |
| 616 | "ollm_spapp_eval_speval_parity", |
| 617 | f"base={b_loss} -> spec={s_loss} (speval={sp_loss})", |
| 618 | ) |
| 619 | |
| 620 | # ---- Speed vs iterative backprop (full-batch B=12 trainfc, 30 steps) ---- |
| 621 | grow_ck = os.path.join(td, "grow_fc.ck") |
| 622 | run([ollm, "growpro", base_ck, grow_ck, "2", "30", "50000"]) |
| 623 | t1 = time.perf_counter() |
| 624 | run([ollm, "trainfc", grow_ck, hc_primal, "30", "30", "1", "12"]) |
| 625 | trainfc_s = time.perf_counter() - t1 |
| 626 | _, ev_fc, _ = run([ollm, "eval", grow_ck, toks, "12"]) |
| 627 | fc_loss = parse_eval(ev_fc)[2] |
| 628 | check( |
| 629 | forge_s < trainfc_s and s_loss < b_loss and fc_loss < b_loss, |
| 630 | "spforge_vs_backprop_speed_and_loss", |
| 631 | f"spforge={forge_s*1000:.2f}ms (loss={s_loss}) vs trainfc_B12_30steps={trainfc_s*1000:.2f}ms (loss={fc_loss})", |
| 632 | ) |
| 633 | |
| 634 | # ---- Regime B: fcachem -> spforge Dual Woodbury (N=18 < F=32) ---- |
| 635 | # 3 windows * 8 = 24 tokens -> mask_every=4 leaves 18 active tokens (< F=32 -> Woodbury!) |
| 636 | hc_wood = os.path.join(td, "wood.hc") |
| 637 | run([ollm, "fcachem", base_ck, toks, mask, "3", hc_wood]) |
| 638 | sp_wood = os.path.join(td, "wood.sp") |
| 639 | _, out_pw, _ = run([harness, "spforge", base_ck, hc_wood, sp_wood, "100000", "1"]) |
| 640 | _, _, n_w, reg_w, l0_w, l1_w, _ = parse_spforge(out_pw) |
| 641 | spec_wood = os.path.join(td, "spec_wood.ck") |
| 642 | run([ollm, "spapp", base_ck, sp_wood, spec_wood]) |
| 643 | check( |
| 644 | n_w == 18 and reg_w == 1 and l1_w < l0_w, |
| 645 | "spforge_fcachem_woodbury", |
| 646 | f"N={n_w}, regime={reg_w}, loss={l0_w}->{l1_w} unats", |
| 647 | ) |
| 648 | |
| 649 | # ---- Multi-link Merkle specialist chain: P1.sp -> P2.sp via ollm spchainapp ---- |
| 650 | hc_link2 = os.path.join(td, "link2.hc") |
| 651 | run([ollm, "fcache", spec_ck, toks, "8", hc_link2]) |
| 652 | sp_link2 = os.path.join(td, "link2.sp") |
| 653 | _, out_l2, _ = run([harness, "spforge", spec_ck, hc_link2, sp_link2, "100000", "1"]) |
| 654 | bl2, sl2, _, _, l2_0, l2_1, _ = parse_spforge(out_l2) |
| 655 | chain_ck = os.path.join(td, "chain.ck") |
| 656 | run([ollm, "spchainapp", base_ck, chain_ck, "2", sp_primal, sp_link2]) |
| 657 | _, ev_ch, _ = run([ollm, "eval", chain_ck, toks, "8"]) |
| 658 | ch_loss = parse_eval(ev_ch)[2] |
| 659 | check( |
| 660 | bl2 == 2 and sl2 == 3 and l2_1 < l2_0 and ch_loss < s_loss, |
| 661 | "spforge_spchainapp_multilink", |
| 662 | f"L1->L2={s_loss} -> L2->L3={ch_loss}", |
| 663 | ) |
| 664 | |
| 665 | # ---- Sleep-consolidation entrypoint (`spforge_consolidate_traces`) ---- |
| 666 | # Extract H_raw (N=24) directly from wood.hc (3 windows * 8) and feed to tsleep |
| 667 | raw = read_bytes(hc_wood) |
| 668 | T, D = 8, 16 |
| 669 | rec_bytes = (T + T * D) * 8 |
| 670 | H_sleep = [] |
| 671 | tgt_sleep = [] |
| 672 | for w in range(3): |
| 673 | rec = raw[48 + w * rec_bytes: 48 + (w + 1) * rec_bytes] |
| 674 | ys = struct.unpack(f"<{T}Q", rec[:T * 8]) |
| 675 | hs = struct.unpack(f"<{T * D}d", rec[T * 8:]) |
| 676 | for t in range(T): |
| 677 | if ys[t] < 65536: |
| 678 | tgt_sleep.append(ys[t]) |
| 679 | H_sleep.extend(hs[t * D:(t + 1) * D]) |
| 680 | sleep_in = os.path.join(td, "sleep.bin") |
| 681 | with open(sleep_in, "wb") as f: |
| 682 | f.write(struct.pack("<QdQ", len(tgt_sleep), 0.1, 1)) |
| 683 | f.write(struct.pack(f"<{len(H_sleep)}d", *H_sleep)) |
| 684 | f.write(struct.pack(f"<{len(tgt_sleep)}Q", *tgt_sleep)) |
| 685 | sp_sleep = os.path.join(td, "sleep.sp") |
| 686 | _, out_sl, _ = run([harness, "tsleep", base_ck, sleep_in, sp_sleep]) |
| 687 | check( |
| 688 | out_sl.startswith("SPCONSOL 1 ") and read_bytes(sp_sleep) == read_bytes(sp_wood), |
| 689 | "spforge_consolidate_traces_bit_identical", |
| 690 | out_sl.strip(), |
| 691 | ) |
| 692 | |
| 693 | # ---- Negative controls on forged OLLMSP01 .sp ---- |
| 694 | # 1. Flip 1 bit in payload -> ollm spapp MUST exit 61 |
| 695 | bad_sp = os.path.join(td, "tampered.sp") |
| 696 | sp_bytes = bytearray(read_bytes(sp_primal)) |
| 697 | sp_bytes[-1] ^= 0x01 |
| 698 | with open(bad_sp, "wb") as f: |
| 699 | f.write(sp_bytes) |
| 700 | rc_tamper, _, _ = run([ollm, "spapp", base_ck, bad_sp, os.path.join(td, "nope.ck")], ok=None) |
| 701 | check(rc_tamper == 61, "neg_control_tampered_sp_rc61", f"rc={rc_tamper}") |
| 702 | |
| 703 | # 2. Truncated .sp -> ollm spapp exits 60 |
| 704 | trunc_sp = os.path.join(td, "trunc.sp") |
| 705 | with open(trunc_sp, "wb") as f: |
| 706 | f.write(sp_bytes[:32]) |
| 707 | rc_trunc, _, _ = run([ollm, "spapp", base_ck, trunc_sp, os.path.join(td, "nope2.ck")], ok=None) |
| 708 | check(rc_trunc == 60, "neg_control_truncated_sp_rc60", f"rc={rc_trunc}") |
| 709 | |
| 710 | # 3. Mismatched base checkpoint -> ollm spapp exits 62 & spforge exits 62 |
| 711 | other_ck = os.path.join(td, "other.ck") |
| 712 | run([ollm, "init", other_ck, "256", "8", "16", "2", "32", "1", "1", "99", "20", "5000"]) |
| 713 | rc_mis_app, _, _ = run([ollm, "spapp", other_ck, sp_primal, os.path.join(td, "nope3.ck")], ok=None) |
| 714 | rc_mis_fge, _, _ = run([harness, "spforge", other_ck, hc_primal, os.path.join(td, "nope.sp")], ok=None) |
| 715 | check(rc_mis_app == 62 and rc_mis_fge == 62, "neg_control_mismatch_base_rc62", f"spapp={rc_mis_app}, spforge={rc_mis_fge}") |
| 716 | |
| 717 | |
| 718 | def test_cold_store_growth_and_bounds(harness): |
| 719 | """Verify cold store works when og[8]==0, grows past initial floor preserving data, and traps at OCSN.""" |
| 720 | rc0, _, _ = run([harness, "tocs", "0"], ok=None) |
| 721 | check(rc0 == 0, "cold_store_zero_model_and_dynamic_grow", f"rc={rc0}") |
| 722 | rc1, _, _ = run([harness, "tocs", "1"], ok=None) |
| 723 | check(rc1 == 103, "cold_store_oob_read_traps_103", f"rc={rc1}") |
| 724 | rc2, _, _ = run([harness, "tocs", "2"], ok=None) |
| 725 | check(rc2 == 103, "cold_store_oob_write_traps_103", f"rc={rc2}") |
| 726 | |
| 727 | |
| 728 | def main(): |
| 729 | test_cross_target_compile() |
| 730 | with tempfile.TemporaryDirectory() as td: |
| 731 | ollm = build_stock_ollm(td) |
| 732 | harness = build_solver_harness(td) |
| 733 | test_cold_store_growth_and_bounds(harness) |
| 734 | test_linear_algebra_oracle(harness) |
| 735 | test_end_to_end_spforge_and_negative_controls(ollm, harness) |
| 736 | print(f"\nSUMMARY: {len(PASSES)} passed, {len(FAILS)} failed") |
| 737 | if FAILS: |
| 738 | sys.exit(1) |
| 739 | |
| 740 | |
| 741 | if __name__ == "__main__": |
| 742 | main() |