Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-helix/blob/main/tests/test_reversible.py # omega-helix This project has not described itself yet. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omega-helix / tests / test_reversible.py` 972 lines ยท 37801 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Pillar 2 (Reversible Residual Blocks) pure-Python-stdlib f64 oracle & test suite. 3 4 Verifies `native/rev.om` across: 5 1. Compilation with `native/{math,data,lpool,model,adam,ckpt,bpe,mio/lio,nogpu}.om` 6 for both `target a64macos` (OM-1 & OM-2) and `gb10` (Linux AArch64 OM-2). 7 2. Built-in `rev_selftest` and `mode0` (model.om pool integration). 8 3. Algebraic inverse reconstruction error < 1e-12 across L layers & looped cores. 9 4. Analytical vs central finite-difference gradient check < 1e-8 across all tensor kinds. 10 5. Zero-activation-buffer (`rev_act_bytes_used == 0`) training equivalence vs 11 cached-activation Python `f64` reference across multi-step Adam / AdamW runs. 12 6. `OLLMCK04` checkpoint & `arch_flags` (`FL_REV = 128` + RoPE/SwiGLU/GQA/QKNorm/ 13 Untied/GELU/GeGLU/LoopedCore) compatibility. 14 15 Run with: 16 python3 -W error::ResourceWarning tests/test_reversible.py 17 """ 18 19 import math 20 import os 21 import platform 22 import shutil 23 import struct 24 import subprocess 25 import sys 26 import tempfile 27 28 M64 = (1 << 64) - 1 29 GOLDEN = 0x9E3779B97F4A7C15 30 FNV_OFFSET = 0xCBF29CE484222325 31 FNV_PRIME = 0x100000001B3 32 SQRT_2_OVER_PI = 0.`79788456080286536` 33 MAGIC_CK4 = b"OLLMCK04" 34 CKHDR = 208 35 36 FL_ROPE = 1 37 FL_SWIGLU = 2 38 FL_UNTIED = 4 39 FL_QKNORM = 8 40 FL_ADAMW = 16 41 FL_GELU = 32 42 FL_GEGLU = 64 43 FL_REV = 128 44 FL_Q32 = 256 45 Q32_SCALE = `1073741824`.0 46 47 48 def find_repo_root(): 49 here = os.path.dirname(os.path.abspath(__file__)) 50 return os.path.dirname(here) 51 52 53 def find_omc(): 54 cands = [ 55 os.environ.get("OMC", ""), 56 shutil.which("omc") or "", 57 os.path.expanduser("~/.local/bin/omc"), 58 ] 59 for c in cands: 60 if c and os.path.isfile(c) and os.access(c, os.X_OK): 61 return c 62 raise RuntimeError("omc compiler not found") 63 64 65 def splitmix64(x): 66 z = (x + GOLDEN) & M64 67 z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & M64 68 z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & M64 69 return z ^ (z >> 31) 70 71 72 def fnv1a64(data): 73 h = FNV_OFFSET 74 for b in data: 75 h = ((h ^ b) * FNV_PRIME) & M64 76 return h 77 78 79 def bits2f(u): 80 return struct.unpack("= 0.0: 89 return 1.0 / (1.0 + math.exp(-x)) 90 e = math.exp(x) 91 return e / (1.0 + e) 92 93 94 def gelu(x): 95 c = SQRT_2_OVER_PI * (x + 0.044715 * x * x * x) 96 return 0.5 * x * (1.0 + math.tanh(c)) 97 98 99 def gelu_d(x): 100 x2 = x * x 101 c = SQRT_2_OVER_PI * (x + 0.044715 * x2 * x) 102 th = math.tanh(c) 103 sech2 = 1.0 - th * th 104 dc = SQRT_2_OVER_PI * (1.0 + 0.134145 * x2) 105 return 0.5 * (1.0 + th) + 0.5 * x * sech2 * dc 106 107 108 # ---------------------------------------------------------------- geometry & CK04 109 110 def phys_layer(cfg, l): 111 np_ = cfg.get("NP", 0) 112 if np_ <= 1: 113 return l 114 lp, lc = cfg["LP"], cfg["LC"] 115 if l < lp: 116 return l 117 j = l - lp 118 if j < lc * np_: 119 return lp + (j % lc) 120 return l - lc * (np_ - 1) 121 122 123 def enrich_cfg(cfg): 124 out = dict(cfg) 125 D, H, H_kv = cfg["D"], cfg["H"], cfg["H_kv"] 126 assert D % H == 0 and H % H_kv == 0 127 E = D // H 128 fl = cfg["arch_flags"] 129 np_ = cfg.get("NP", 0) 130 lp, lc = cfg.get("LP", 0), cfg.get("LC", 0) 131 L = cfg["L"] 132 LV = L + lc * (np_ - 1) if np_ > 1 else L 133 out["E"] = E 134 out["KVD"] = H_kv * E 135 out["LV"] = LV 136 out["has_rope"] = bool(fl & FL_ROPE) 137 out["is_gated"] = bool(fl & (FL_SWIGLU | FL_GEGLU)) 138 out["has_untied"] = bool(fl & FL_UNTIED) 139 out["has_qknorm"] = bool(fl & FL_QKNORM) 140 out["is_adamw"] = bool(fl & FL_ADAMW) 141 out["has_gelu"] = bool(fl & FL_GELU) 142 out["has_swiglu"] = bool(fl & FL_SWIGLU) 143 out["has_geglu"] = bool(fl & FL_GEGLU) 144 out["has_rev"] = bool(fl & FL_REV) 145 return out 146 147 148 def tensor_specs(g): 149 V, T, D, F, L = g["V"], g["T"], g["D"], g["F"], g["L"] 150 E, KVD = g["E"], g["KVD"] 151 specs = [("wte", V, D)] 152 if not g["has_rope"]: 153 specs.append(("wpe", T, D)) 154 for l in range(L): 155 specs.append((f"g1.{l}", 1, D)) 156 specs.append((f"wq.{l}", D, D)) 157 specs.append((f"wk.{l}", D, KVD)) 158 specs.append((f"wv.{l}", D, KVD)) 159 specs.append((f"wo.{l}", D, D)) 160 if g["has_qknorm"]: 161 specs.append((f"qn.{l}", 1, E)) 162 specs.append((f"kn.{l}", 1, E)) 163 specs.append((f"g2.{l}", 1, D)) 164 specs.append((f"w1.{l}", D, F)) 165 if g["is_gated"]: 166 specs.append((f"wup.{l}", D, F)) 167 specs.append((f"w2.{l}", F, D)) 168 specs.append(("gf", 1, D)) 169 if g["has_untied"]: 170 specs.append(("lmh", V, D)) 171 out, off = [], 0 172 for name, r, c in specs: 173 out.append((name, off, r, c)) 174 off += r * c 175 return out, off 176 177 178 def is_gain_name(name): 179 return name.split(".")[0] in ("g1", "g2", "qn", "kn", "gf") 180 181 182 def unpack_params(g, flat): 183 specs, _ = tensor_specs(g) 184 out = {} 185 for name, off, r, c in specs: 186 if r == 1 and is_gain_name(name): 187 out[name] = list(flat[off:off + c]) 188 else: 189 out[name] = [list(flat[off + i * c:off + (i + 1) * c]) for i in range(r)] 190 return out 191 192 193 def pack_params(g, tdict): 194 specs, _ = tensor_specs(g) 195 flat = [] 196 for name, _, r, _ in specs: 197 v = tdict[name] 198 if r == 1 and is_gain_name(name): 199 flat.extend(v) 200 else: 201 for row in v: 202 flat.extend(row) 203 return flat 204 205 206 def zeros_like(g): 207 specs, _ = tensor_specs(g) 208 out = {} 209 for name, _, r, c in specs: 210 out[name] = [0.0] * c if (r == 1 and is_gain_name(name)) else [[0.0] * c for _ in range(r)] 211 return out 212 213 214 def read_ck4(path): 215 with open(path, "rb") as f: 216 raw = f.read() 217 assert len(raw) >= CKHDR 218 assert raw[:8] == MAGIC_CK4, f"bad magic {raw[:8]!r}" 219 V, T, D, H, H_kv, F, L, B = struct.unpack("<8Q", raw[8:72]) 220 seed, step, total, lr_bits, P = struct.unpack("<5Q", raw[72:112]) 221 fl, rope_milli, eps_bits, wd_bits, warmup = struct.unpack("<5Q", raw[112:152]) 222 LP, LC, NP = struct.unpack("<3Q", raw[152:176]) 223 (fnv_got,) = struct.unpack(" 0.0 else 0.0 for v in row] for row in fp] 463 gout = mm_fwd(rl, P[f"w2.{pl}"]) 464 return gout, dict(b=b, s2=s2, fp=fp, up=up, rl=rl) 465 466 467 def G_bwd(g, P, G, pl, y1, dy2, cache): 468 T, D, F = g["T"], g["D"], g["F"] 469 b, s2, fp, up, rl = cache["b"], cache["s2"], cache["fp"], cache["up"], cache["rl"] 470 mm_dw(rl, dy2, G[f"w2.{pl}"]) 471 df1 = mm_dx(dy2, P[f"w2.{pl}"]) 472 df2 = None 473 if g["has_swiglu"]: 474 df2 = [[0.0] * F for _ in range(T)] 475 for t in range(T): 476 for i in range(F): 477 dy, gv, uv = df1[t][i], fp[t][i], up[t][i] 478 sig = sigmoid(gv) 479 df2[t][i] = dy * gv * sig 480 ds = sig * (1.0 + gv * (1.0 - sig)) 481 df1[t][i] = dy * uv * ds 482 elif g["has_geglu"]: 483 df2 = [[0.0] * F for _ in range(T)] 484 for t in range(T): 485 for i in range(F): 486 dy, gv, uv = df1[t][i], fp[t][i], up[t][i] 487 df2[t][i] = dy * gelu(gv) 488 df1[t][i] = dy * uv * gelu_d(gv) 489 elif g["has_gelu"]: 490 df1 = [[df1[t][i] * gelu_d(fp[t][i]) for i in range(F)] for t in range(T)] 491 else: 492 df1 = [[df1[t][i] if fp[t][i] > 0.0 else 0.0 for i in range(F)] for t in range(T)] 493 mm_dw(b, df1, G[f"w1.{pl}"]) 494 db = mm_dx(df1, P[f"w1.{pl}"]) 495 if g["is_gated"]: 496 mm_dw(b, df2, G[f"wup.{pl}"]) 497 db_up = mm_dx(df2, P[f"wup.{pl}"]) 498 db = [[db[t][j] + db_up[t][j] for j in range(D)] for t in range(T)] 499 return rms_bwd_mat(y1, P[f"g2.{pl}"], s2, db, G[f"g2.{pl}"]) 500 501 502 def rev_seq_loss_grad(g, P, G, xs, ys, scale, rope_tab, zero_act_cache=True): 503 T, D, V, LV = g["T"], g["D"], g["V"], g["LV"] 504 wte = P["wte"] 505 if g["has_rope"]: 506 h0 = [[wte[xs[t]][j] for j in range(D)] for t in range(T)] 507 else: 508 wpe = P["wpe"] 509 h0 = [[wte[xs[t]][j] + wpe[t][j] for j in range(D)] for t in range(T)] 510 x1 = [list(r) for r in h0] 511 x2 = [list(r) for r in h0] 512 layer_caches = [] if not zero_act_cache else None 513 for l in range(LV): 514 pl = phys_layer(g, l) 515 fout, fcache = F_fwd(g, P, pl, x2, rope_tab) 516 y1 = [[x1[t][j] + fout[t][j] for j in range(D)] for t in range(T)] 517 gout, gcache = G_fwd(g, P, pl, y1) 518 y2 = [[x2[t][j] + gout[t][j] for j in range(D)] for t in range(T)] 519 if not zero_act_cache: 520 layer_caches.append((x1, x2, y1, y2, fcache, gcache)) 521 x1, x2 = y1, y2 522 hf = [[0.5 * (x1[t][j] + x2[t][j]) for j in range(D)] for t in range(T)] 523 gf = P["gf"] 524 z, sf = rms_fwd_mat(hf, gf, g["rms_eps"]) 525 lmw = P["lmh"] if g["has_untied"] else P["wte"] 526 dlmw = G["lmh"] if g["has_untied"] else G["wte"] 527 lsum = 0.0 528 dz = [[0.0] * D for _ in range(T)] 529 for t in range(T): 530 lg = [sum(z[t][j] * lmw[c][j] for j in range(D)) for c in range(V)] 531 mx = max(lg) 532 ew = [math.exp(v - mx) for v in lg] 533 sm = sum(ew) 534 pr = [v / sm for v in ew] 535 lsum += -(lg[ys[t]] - mx - math.log(sm)) 536 for c in range(V): 537 dl = (pr[c] - (1.0 if c == ys[t] else 0.0)) * scale 538 for j in range(D): 539 dlmw[c][j] += dl * z[t][j] 540 dz[t][j] += dl * lmw[c][j] 541 dhf = rms_bwd_mat(hf, gf, sf, dz, G["gf"]) 542 dy1 = [[0.5 * dhf[t][j] for j in range(D)] for t in range(T)] 543 dy2 = [[0.5 * dhf[t][j] for j in range(D)] for t in range(T)] 544 y1, y2 = x1, x2 545 for l in range(LV - 1, -1, -1): 546 pl = phys_layer(g, l) 547 if zero_act_cache: 548 gout, gcache = G_fwd(g, P, pl, y1) 549 x2_rec = [[y2[t][j] - gout[t][j] for j in range(D)] for t in range(T)] 550 dy1_g = G_bwd(g, P, G, pl, y1, dy2, gcache) 551 dy1 = [[dy1[t][j] + dy1_g[t][j] for j in range(D)] for t in range(T)] 552 fout, fcache = F_fwd(g, P, pl, x2_rec, rope_tab) 553 x1_rec = [[y1[t][j] - fout[t][j] for j in range(D)] for t in range(T)] 554 dx2_f = F_bwd(g, P, G, pl, x2_rec, dy1, fcache, rope_tab) 555 dy2 = [[dy2[t][j] + dx2_f[t][j] for j in range(D)] for t in range(T)] 556 y1, y2 = x1_rec, x2_rec 557 else: 558 x1_c, x2_c, y1_c, y2_c, fcache, gcache = layer_caches[l] 559 dy1_g = G_bwd(g, P, G, pl, y1_c, dy2, gcache) 560 dy1 = [[dy1[t][j] + dy1_g[t][j] for j in range(D)] for t in range(T)] 561 dx2_f = F_bwd(g, P, G, pl, x2_c, dy1, fcache, rope_tab) 562 dy2 = [[dy2[t][j] + dx2_f[t][j] for j in range(D)] for t in range(T)] 563 for t in range(T): 564 dh0 = [dy1[t][j] + dy2[t][j] for j in range(D)] 565 for j in range(D): 566 G["wte"][xs[t]][j] += dh0[j] 567 if not g["has_rope"]: 568 G["wpe"][t][j] += dh0[j] 569 return lsum / T 570 571 572 def rev_loss_and_grad(g, flat, batch_seqs, zero_act_cache=True): 573 P = unpack_params(g, flat) 574 G = zeros_like(g) 575 rope_tab = build_rope_tables(g) if g["has_rope"] else None 576 B, T = g["B"], g["T"] 577 sc = 1.0 / (B * T) 578 tot = 0.0 579 for xs, ys in batch_seqs: 580 tot += rev_seq_loss_grad(g, P, G, xs, ys, sc, rope_tab, zero_act_cache=zero_act_cache) 581 return tot / B, pack_params(g, G) 582 583 584 def rev_inv_error(g, flat, xs): 585 T, D, LV = g["T"], g["D"], g["LV"] 586 P = unpack_params(g, flat) 587 rope_tab = build_rope_tables(g) if g["has_rope"] else None 588 if g["has_rope"]: 589 h0 = [[P["wte"][xs[t]][j] for j in range(D)] for t in range(T)] 590 else: 591 h0 = [[P["wte"][xs[t]][j] + P["wpe"][t][j] for j in range(D)] for t in range(T)] 592 x1_init = [list(r) for r in h0] 593 x2_init = [list(r) for r in h0] 594 x1, x2 = [list(r) for r in h0], [list(r) for r in h0] 595 for l in range(LV): 596 pl = phys_layer(g, l) 597 fout, _ = F_fwd(g, P, pl, x2, rope_tab) 598 y1 = [[x1[t][j] + fout[t][j] for j in range(D)] for t in range(T)] 599 gout, _ = G_fwd(g, P, pl, y1) 600 y2 = [[x2[t][j] + gout[t][j] for j in range(D)] for t in range(T)] 601 x1, x2 = y1, y2 602 for l in range(LV - 1, -1, -1): 603 pl = phys_layer(g, l) 604 gout, _ = G_fwd(g, P, pl, x1) 605 x2_rec = [[x2[t][j] - gout[t][j] for j in range(D)] for t in range(T)] 606 fout, _ = F_fwd(g, P, pl, x2_rec, rope_tab) 607 x1_rec = [[x1[t][j] - fout[t][j] for j in range(D)] for t in range(T)] 608 x1, x2 = x1_rec, x2_rec 609 mx = 0.0 610 for t in range(T): 611 for j in range(D): 612 mx = max(mx, abs(x1[t][j] - x1_init[t][j]), abs(x2[t][j] - x2_init[t][j])) 613 return mx 614 615 616 def adam_step(g, params, m, v, grad, step): 617 lr = g["lr"] 618 wu = g["warmup"] 619 tot = g["total"] 620 if wu > 0 and step < wu: 621 lrs = lr * (step + 1) / wu 622 else: 623 rt = max(1, tot - wu) 624 prog = min(1.0, (step - wu) / rt) 625 if g["is_adamw"]: 626 lrs = lr * (0.1 + 0.45 * (1.0 + math.cos(math.pi * prog))) 627 else: 628 lrs = lr * (1.0 - 0.9 * prog) 629 gn = math.sqrt(sum(gv * gv for gv in grad)) 630 if gn > 1.0: 631 sc = 1.0 / gn 632 grad = [gv * sc for gv in grad] 633 b1 = 0.9 634 b2 = 0.95 if g["is_adamw"] else 0.99 635 bc1 = 1.0 / (1.0 - b1 ** (step + 1)) 636 bc2 = 1.0 / (1.0 - b2 ** (step + 1)) 637 wd = g["wd"] if g["is_adamw"] else 0.0 638 specs, _ = tensor_specs(g) 639 gain_mask = [] 640 for name, _, r, c in specs: 641 gain_mask.extend([is_gain_name(name)] * (r * c)) 642 p_new, m_new, v_new = [], [], [] 643 for i, (w, mi, vi, gi) in enumerate(zip(params, m, v, grad)): 644 m2 = b1 * mi + (1.0 - b1) * gi 645 v2 = b2 * vi + (1.0 - b2) * gi * gi 646 if wd > 0.0 and not gain_mask[i]: 647 w = w - lrs * wd * w 648 upd = (lrs * m2 * bc1) / (math.sqrt(v2 * bc2) + 1e-8) 649 p_new.append(w - upd) 650 m_new.append(m2) 651 v_new.append(v2) 652 return p_new, m_new, v_new 653 654 655 # ---------------------------------------------------------------- compiler & test runner 656 657 def compile_target(omc, root, out_path, mode): 658 nat = os.path.join(root, "native") 659 units = ["math.om", "data.om", "lpool.om", "model.om", "adam.om", "ckpt.om", "bpe.om"] 660 if mode in ("mac_om1", "mac_om2"): 661 units.append("mio.om") 662 hdr = "target a64macos\n" + ("om2\n" if mode == "mac_om2" else "") 663 elif mode == "gb10_om2": 664 units.append("lio.om") 665 hdr = "om2\n" 666 else: 667 raise ValueError(mode) 668 units.extend(["nogpu.om", "rev.om"]) 669 parts = [hdr] 670 for u in units: 671 with open(os.path.join(nat, u), "r", encoding="utf-8") as f: 672 parts.append(f.read()) 673 parts.append("\nfn olast to void\nend\nfn ocmd to int\nret rev_cli\nend\n") 674 src = "\n".join(parts) 675 res = subprocess.run([omc], input=src.encode("utf-8"), capture_output=True) 676 if res.returncode != 0: 677 raise RuntimeError(f"omc failed for {mode}: {res.stderr.decode('utf-8', 'replace')}") 678 with open(out_path, "wb") as f: 679 f.write(res.stdout) 680 os.chmod(out_path, 0o755) 681 if mode in ("mac_om1", "mac_om2") and shutil.which("codesign"): 682 cs = subprocess.run(["codesign", "-s", "-", "-f", out_path], capture_output=True) 683 if cs.returncode != 0: 684 raise RuntimeError(f"codesign failed: {cs.stderr.decode('utf-8', 'replace')}") 685 686 687 def run_oracle_case(bin_path, tmpdir, label, cfg): 688 g = enrich_cfg(cfg) 689 out_bin = os.path.join(tmpdir, f"{label}.bin") 690 ck4_path = os.path.join(tmpdir, f"{label}.ck4") 691 steps = 5 692 argv = [ 693 bin_path, "oracle", 694 str(g["arch_flags"]), str(g["V"]), str(g["T"]), str(g["D"]), 695 str(g["H"]), str(g["H_kv"]), str(g["F"]), str(g["L"]), str(g["B"]), 696 str(g.get("LP", 0)), str(g.get("LC", 0)), str(g.get("NP", 0)), 697 str(g["seed"]), str(steps), out_bin, ck4_path, 698 ] 699 res = subprocess.run(argv, capture_output=True, text=True) 700 assert res.returncode == 0, f"{label} oracle failed: rc={res.returncode} {res.stderr}" 701 702 with open(out_bin, "rb") as f: 703 raw = f.read() 704 P, inv_err_om, ls_om, act_bytes, pair_bytes = struct.unpack("= 1e-12" 710 711 pos = 40 712 params0 = list(struct.unpack(f"<{P}d", raw[pos:pos + 8 * P])); pos += 8 * P 713 grads_om = list(struct.unpack(f"<{P}d", raw[pos:pos + 8 * P])); pos += 8 * P 714 step_losses_om = list(struct.unpack(f"<{steps}d", raw[pos:pos + 8 * steps])); pos += 8 * steps 715 params_final_om = list(struct.unpack(f"<{P}d", raw[pos:pos + 8 * P])); pos += 8 * P 716 assert pos == len(raw) 717 718 batch_seqs = [ 719 ([splitmix64(101 + b * 31 + t) % g["V"] for t in range(g["T"])], 720 [splitmix64(701 + b * 31 + t) % g["V"] for t in range(g["T"])]) 721 for b in range(g["B"]) 722 ] 723 724 # 1. Python algebraic inverse reconstruction check 725 py_inv_err = rev_inv_error(g, params0, batch_seqs[0][0]) 726 assert py_inv_err < 1e-12, f"{label}: Python inverse error {py_inv_err:.3e}" 727 728 # 2. Zero-activation vs cached-activation equivalence in Python + vs rev.om 729 py_loss_z, py_grad_z = rev_loss_and_grad(g, params0, batch_seqs, zero_act_cache=True) 730 py_loss_c, py_grad_c = rev_loss_and_grad(g, params0, batch_seqs, zero_act_cache=False) 731 assert abs(py_loss_z - ls_om) < 1e-10, f"{label}: loss diff {abs(py_loss_z - ls_om):.3e}" 732 assert abs(py_loss_z - py_loss_c) < 1e-12 733 734 max_g_om_vs_cached = 0.0 735 max_g_z_vs_c = 0.0 736 g_scale = max(1.0, max(abs(x) for x in py_grad_c)) 737 for a, b, c in zip(grads_om, py_grad_z, py_grad_c): 738 max_g_om_vs_cached = max(max_g_om_vs_cached, abs(a - c) / g_scale) 739 max_g_z_vs_c = max(max_g_z_vs_c, abs(b - c) / g_scale) 740 assert max_g_om_vs_cached < 1e-10, f"{label}: grad OM vs cached err {max_g_om_vs_cached:.3e}" 741 assert max_g_z_vs_c < 1e-12, f"{label}: grad zero vs cached err {max_g_z_vs_c:.3e}" 742 743 # 3. Central finite-difference check across every tensor type (4-point O(h^4) central FD) 744 h = 1e-4 745 specs, _ = tensor_specs(g) 746 p_work = list(params0) 747 worst_fd = 0.0 748 for name, off, r, cc in specs: 749 n = r * cc 750 idxs = [off, off + n // 2, off + n - 1] 751 for idx in idxs: 752 orig = p_work[idx] 753 p_work[idx] = orig + 2.0 * h 754 lp2, _ = rev_loss_and_grad(g, p_work, batch_seqs, zero_act_cache=True) 755 p_work[idx] = orig + h 756 lp1, _ = rev_loss_and_grad(g, p_work, batch_seqs, zero_act_cache=True) 757 p_work[idx] = orig - h 758 lm1, _ = rev_loss_and_grad(g, p_work, batch_seqs, zero_act_cache=True) 759 p_work[idx] = orig - 2.0 * h 760 lm2, _ = rev_loss_and_grad(g, p_work, batch_seqs, zero_act_cache=True) 761 p_work[idx] = orig 762 gn = (-lp2 + 8.0 * lp1 - 8.0 * lm1 + lm2) / (12.0 * h) 763 ga = grads_om[idx] 764 rel = abs(gn - ga) / max(abs(ga), abs(gn), 1e-2) 765 worst_fd = max(worst_fd, rel) 766 assert rel < 1e-8, f"{label} {name}[{idx - off}]: FD rel={rel:.3e} ga={ga:.10e} gn={gn:.10e}" 767 768 # 4. Multi-step Adam/AdamW training equivalence vs cached-activation Python reference 769 p_cur = list(params0) 770 m_cur = [0.0] * P 771 v_cur = [0.0] * P 772 for stp in range(steps): 773 l_ref, g_ref = rev_loss_and_grad(g, p_cur, batch_seqs, zero_act_cache=False) 774 assert abs(l_ref - step_losses_om[stp]) < 1e-10, ( 775 f"{label} step {stp}: loss {step_losses_om[stp]} != {l_ref}" 776 ) 777 p_cur, m_cur, v_cur = adam_step(g, p_cur, m_cur, v_cur, g_ref, stp) 778 assert step_losses_om[-1] < step_losses_om[0], ( 779 f"{label}: loss did not decrease ({step_losses_om[0]:.6f} -> {step_losses_om[-1]:.6f})" 780 ) 781 max_p_diff = max(abs(a - b) for a, b in zip(params_final_om, p_cur)) 782 assert max_p_diff < 1e-10, f"{label}: final params diff {max_p_diff:.3e}" 783 784 # 5. OLLMCK04 checkpoint & flag compatibility check 785 ck = read_ck4(ck4_path) 786 assert ck["arch_flags"] == g["arch_flags"], f"{label}: CK04 flags {ck['arch_flags']} != {g['arch_flags']}" 787 assert ck["arch_flags"] & FL_REV, f"{label}: FL_REV bit missing in CK04" 788 assert ck["step"] == steps and ck["P"] == P 789 assert ck["LP"] == g.get("LP", 0) and ck["LC"] == g.get("LC", 0) and ck["NP"] == g.get("NP", 0) 790 assert max(abs(a - b) for a, b in zip(ck["params"], params_final_om)) == 0.0 791 ck_res = subprocess.run([bin_path, "ck4load", ck4_path], capture_output=True, text=True) 792 assert ck_res.returncode == 0, f"{label}: ck4load failed: {ck_res.stderr}" 793 ck_toks = ck_res.stdout.strip().split() 794 assert ck_toks == ["C4", str(P), str(g["arch_flags"]), str(g["LV"])], f"unexpected ck4load: {ck_toks}" 795 796 print( 797 f"PASS {label:18s} inv={inv_err_om:.2e} py_inv={py_inv_err:.2e} " 798 f"grad_eq={max_g_om_vs_cached:.2e} fd={worst_fd:.2e} " 799 f"loss={step_losses_om[0]:.4f}->{step_losses_om[-1]:.4f} act_bytes={act_bytes} ck4_flags={ck['arch_flags']}" 800 ) 801 802 803 def f32_round(x): 804 return struct.unpack("= 0.0 else int(s - 0.5) 815 816 817 def run_q32_contrast_test(oracle_bin, tmpdir): 818 # 1. Demonstrate FP32 & BF16 bit-loss at 1e5 / 1e-4 ratio (1e9 dynamic range) 819 n = 64 820 nl = 8 821 x_init = [ 822 (100000.0 + ((splitmix64(5000 + i) >> 11) * (2.0 ** -53)) * 1000.0) * (-1.0 if (i & 1) else 1.0) 823 for i in range(n) 824 ] 825 perts = [] 826 for l in range(nl): 827 layer_p = [] 828 for i in range(n): 829 r = (splitmix64(l * 1009 + i * 17 + 31337) >> 11) * (2.0 ** -53) 830 v = (2.0 * r - 1.0) * 1.5e-4 831 if abs(v) < 5.0e-5: 832 v = v + 5.0e-5 if v >= 0.0 else v - 5.0e-5 833 layer_p.append(bf16_sim(v)) 834 perts.append(layer_p) 835 836 # In FP32, adding 1e-4 perturbations onto ~1e5 magnitudes loses bits completely 837 x_f32 = [f32_round(v) for v in x_init] 838 for l in range(nl): 839 for i in range(n): 840 x_f32[i] = f32_round(x_f32[i] + perts[l][i]) 841 assert x_f32 == [f32_round(v) for v in x_init], "expected FP32 to drop 1e-4 updates on 1e5 residuals" 842 843 # Even with slightly larger BF16-scale perturbations, float addition+subtraction fails bit-reversibility 844 x_bf = bf16_sim(100000.0) 845 f_bf = bf16_sim(512.0 * 0.25) 846 assert bf16_sim(bf16_sim(x_bf + f_bf) - f_bf) != x_bf, "expected BF16 (x+F)-F != x" 847 848 # Q30 i64 integer stream preserves every bit of the 1e-4 updates and reverses to 0 bit diff 849 x_q = [q32_quant(v) for v in x_init] 850 x_q_orig = list(x_q) 851 for l in range(nl): 852 for i in range(n): 853 x_q[i] += q32_quant(perts[l][i]) 854 assert x_q != x_q_orig, "Q30 stream failed to accumulate 1e-4 updates" 855 for l in range(nl - 1, -1, -1): 856 for i in range(n): 857 x_q[i] -= q32_quant(perts[l][i]) 858 assert x_q == x_q_orig, "Q30 inverse stream failed bit-exact reconstruction" 859 860 # 2. Full transformer oracle check with FL_REV | FL_Q32 (flag 256) enabled 861 out_bin = os.path.join(tmpdir, "q32_rev.bin") 862 ck4_path = os.path.join(tmpdir, "q32_rev.ck4") 863 fl = FL_REV | FL_Q32 | FL_ROPE | FL_SWIGLU | FL_ADAMW 864 argv = [ 865 oracle_bin, "oracle", 866 str(fl), "32", "4", "8", "2", "1", "16", "2", "2", 867 "0", "0", "0", "77", "2", out_bin, ck4_path, 868 ] 869 res = subprocess.run(argv, capture_output=True, text=True) 870 assert res.returncode == 0, f"q32_rev oracle failed: rc={res.returncode} {res.stderr}" 871 with open(out_bin, "rb") as f: 872 raw = f.read() 873 P, inv_err_om, ls_om, act_bytes, pair_bytes = struct.unpack(" 0 893 894 if is_mac: 895 mac_om1 = os.path.join(tmpdir, "rev-mac-om1") 896 mac_om2 = os.path.join(tmpdir, "rev-mac-om2") 897 compile_target(omc, root, mac_om1, "mac_om1") 898 compile_target(omc, root, mac_om2, "mac_om2") 899 print( 900 f"PASS compile mac_om1={os.path.getsize(mac_om1)}B " 901 f"mac_om2={os.path.getsize(mac_om2)}B gb10_om2={os.path.getsize(gb10_om2)}B" 902 ) 903 run_pairs = [("mac_om1", mac_om1), ("mac_om2", mac_om2)] 904 oracle_bin = mac_om2 905 elif is_a64_linux: 906 print(f"PASS compile gb10_om2={os.path.getsize(gb10_om2)}B") 907 run_pairs = [("gb10_om2", gb10_om2)] 908 oracle_bin = gb10_om2 909 else: 910 print(f"PASS compile gb10_om2={os.path.getsize(gb10_om2)}B (non-arm64 runtime skipped)") 911 return 912 913 for label, bin_p in run_pairs: 914 st = subprocess.run([bin_p, "selftest"], capture_output=True, text=True) 915 assert st.returncode == 0, f"{label} selftest failed:\n{st.stdout}\n{st.stderr}" 916 for tok in ("PASS I1 ", "PASS G1 ", "PASS I2 ", "PASS G2 ", "PASS TR ", "PASS Q32 0 ", "PASS DETBWD 0 "): 917 assert tok in st.stdout, f"{label} selftest missing {tok!r} in:\n{st.stdout}" 918 m0 = subprocess.run([bin_p, "mode0"], capture_output=True, text=True) 919 assert m0.returncode == 0, f"{label} mode0 failed:\n{m0.stdout}\n{m0.stderr}" 920 q32 = subprocess.run([bin_p, "q32"], capture_output=True, text=True) 921 assert q32.returncode == 0 and "PASS Q32 0 8" in q32.stdout, ( 922 f"{label} q32 failed:\n{q32.stdout}\n{q32.stderr}" 923 ) 924 det = subprocess.run([bin_p, "detbwd"], capture_output=True, text=True) 925 assert det.returncode == 0 and "PASS DETBWD 0 " in det.stdout, ( 926 f"{label} detbwd failed:\n{det.stdout}\n{det.stderr}" 927 ) 928 print(f"PASS selftest+mode0 {[lbl for lbl, _ in run_pairs]} passed built-in self-tests (incl. Q32 & DETBWD)") 929 930 # Verify Lock 4 contrast: FP32/BF16 stream drops/corrupts 1e-4 updates on 1e5 residuals, 931 # whereas Q30 i64 fixed-point stream preserves every bit across 8 layers and reverses to 0 bit diff. 932 run_q32_contrast_test(oracle_bin, tmpdir) 933 934 cases = [ 935 ("gpt_relu_rev", dict( 936 arch_flags=FL_REV, V=32, T=4, D=8, H=2, H_kv=2, F=16, L=2, B=2, 937 LP=0, LC=0, NP=0, seed=42, total=50, lr=0.01, 938 rope_theta_milli=10_000_000, rms_eps=1e-5, wd=0.05, warmup=10, 939 )), 940 ("llama_rope_gqa", dict( 941 arch_flags=FL_REV | FL_ROPE | FL_SWIGLU | FL_ADAMW, 942 V=32, T=4, D=8, H=2, H_kv=1, F=16, L=2, B=2, 943 LP=0, LC=0, NP=0, seed=101, total=50, lr=0.01, 944 rope_theta_milli=10_000_000, rms_eps=1e-5, wd=0.05, warmup=10, 945 )), 946 ("qwen3_looped_np3", dict( 947 arch_flags=FL_REV | FL_ROPE | FL_SWIGLU | FL_UNTIED | FL_QKNORM | FL_ADAMW, 948 V=32, T=4, D=8, H=2, H_kv=1, F=16, L=3, B=2, 949 LP=1, LC=1, NP=3, seed=202, total=50, lr=0.01, 950 rope_theta_milli=10_000_000, rms_eps=1e-5, wd=0.05, warmup=10, 951 )), 952 ("gelu_rev", dict( 953 arch_flags=FL_REV | FL_GELU, 954 V=24, T=4, D=8, H=2, H_kv=2, F=16, L=2, B=2, 955 LP=0, LC=0, NP=0, seed=303, total=50, lr=0.01, 956 rope_theta_milli=10_000_000, rms_eps=1e-5, wd=0.05, warmup=10, 957 )), 958 ("geglu_rope_rev", dict( 959 arch_flags=FL_REV | FL_ROPE | FL_GEGLU | FL_ADAMW, 960 V=24, T=4, D=8, H=2, H_kv=1, F=16, L=2, B=2, 961 LP=0, LC=0, NP=0, seed=404, total=50, lr=0.01, 962 rope_theta_milli=10_000_000, rms_eps=1e-5, wd=0.05, warmup=10, 963 )), 964 ] 965 for label, cfg in cases: 966 run_oracle_case(oracle_bin, tmpdir, label, cfg) 967 968 print("ALL PILLAR 2 REVERSIBLE CHECKS PASSED") 969 970 971 if __name__ == "__main__": 972 main()