interplane.Get Omega
Read in your language

omega-helix

This project has not described itself yet.

Brought by drakestapleton

branch main Branches Tags History

omega-helix / tests / test_apu_weave.py

260 lines · 11917 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Independent verification suite for Full-APU Co-Execution Fabric (native/apu_weave.om).
3
4Verifies:
5 1. Host binary build and `apuweave` over multi-shard lists (and directory scanning on Linux).
6 2. Looped OLLMCK03 (L_phys=2 x NP=2) + both W4 (quant_bits=4) and f64 (quant_bits=64) packs.
7 3. Exact machine-readable telemetry contract (`APU_WAVE`, `APU_STRAND`, `APU_SUMMARY`, `APU_OVERLAP`).
8 4. Full OLLMSP02 interchangeability: packs produced by `apuweave` pass `ollm spweval` with real
9 loss drop vs base seed AND `ollm spwsamp` AND fail closed (`rc=61`) on 1-bit header/payload tamper.
10 5. Multi-worker parallel execution on Linux (fork + pipefds + pollfds + cpuset + MAP_SHARED ring).
11 6. Optional live GB10 silicon test (`OLLM_GB10_LIVE=1`) verifying `gpu_mode > 0` (`BF16`/`FP32`) and
12 real GPU+CPU co-execution parity against CPU `spcryst`.
13"""
14import os
15import platform
16import struct
17import subprocess
18import tempfile
19import unittest
20from pathlib import Path
21
22REPO = Path(__file__).resolve().parent.parent
23OSP2_MAG = int.from_bytes(b"OLLMSP02", "little")
24
25
26def select_target_and_bin():
27 os_name = platform.system()
28 arch = platform.machine().lower()
29 if os_name == "Darwin":
30 return "macos", "ollm-macos"
31 if arch in ("x86_64", "amd64"):
32 return "x86linux", "ollm-x86linux"
33 return "aarch64", "ollm"
34
35
36def build_target(out_dir: Path, target: str) -> Path:
37 env = os.environ.copy()
38 env["TARGET"] = target
39 env["OUT"] = str(out_dir)
40 r = subprocess.run(
41 ["sh", str(REPO / "scripts" / "build.sh")],
42 cwd=str(REPO),
43 env=env,
44 capture_output=True,
45 text=True,
46 )
47 if r.returncode != 0:
48 raise RuntimeError(f"build TARGET={target} failed ({r.returncode}): {r.stderr}\n{r.stdout}")
49 names = {
50 "macos": "ollm-macos",
51 "x86linux": "ollm-x86linux",
52 "aarch64": "ollm",
53 "gb10": "ollm-gb10",
54 }
55 return out_dir / names[target]
56
57
58def run_cmd(cmd, check=True):
59 r = subprocess.run(cmd, capture_output=True, text=True)
60 if check and r.returncode != 0:
61 raise AssertionError(
62 f"command failed rc={r.returncode}: {' '.join(map(str, cmd))}\n"
63 f"stdout:\n{r.stdout}\nstderr:\n{r.stderr}"
64 )
65 return r
66
67
68def parse_telemetry(stdout: str):
69 waves, strands, summary, overlap = [], [], None, None
70 for line in stdout.splitlines():
71 parts = line.strip().split()
72 if not parts:
73 continue
74 if parts[0] == "APU_WAVE":
75 waves.append([int(x) for x in parts[1:]])
76 elif parts[0] == "APU_STRAND":
77 strands.append([int(x) for x in parts[1:]])
78 elif parts[0] == "APU_SUMMARY":
79 summary = [int(x) for x in parts[1:]]
80 elif parts[0] == "APU_OVERLAP":
81 overlap = [int(x) for x in parts[1:]]
82 return waves, strands, summary, overlap
83
84
85class TestApuWeave(unittest.TestCase):
86 @classmethod
87 def setUpClass(cls):
88 cls._td = tempfile.TemporaryDirectory(prefix="omega-apu-weave-test-")
89 cls.td = Path(cls._td.name)
90 target, _ = select_target_and_bin()
91 cls.target = target
92 env_bin = os.environ.get("OLLM_BIN")
93 env_path = Path(env_bin) if env_bin else None
94 if env_path is not None and env_path.is_file() and os.access(env_path, os.X_OK):
95 cls.bin = env_path
96 else:
97 cls.bin = build_target(cls.td / "bin", target)
98
99 # Build a clean 4-shard synthetic corpus with distinct domain patterns
100 cls.shards_dir = cls.td / "shards"
101 cls.shards_dir.mkdir(parents=True)
102 patterns = [
103 "fn omega_kernel x ulong y ulong to ulong\nret add mul x 3 y\nend\n",
104 "struct RingDesc seq ulong op uint flags uint va ulong end\n",
105 "APU_WAVE 1 4 12 0 4 2 1\nAPU_STRAND 1 512 4100000 3800000\n",
106 "matrix cholesky solve lambda ridge projection vector norm\n",
107 ]
108 cls.shard_paths = []
109 for idx, pat in enumerate(patterns):
110 p = cls.shards_dir / f"s{idx:02d}_domain{idx}.tok"
111 p.write_bytes((pat * 40).encode("ascii"))
112 cls.shard_paths.append(p)
113 cls.all_corpus = cls.td / "all.tok"
114 cls.all_corpus.write_bytes(b"".join(p.read_bytes() for p in cls.shard_paths))
115
116 # Train a small looped OLLMCK03 checkpoint (L_phys=2 x NP=2 = 4 effective layers)
117 cls.ck = cls.td / "loop_base.ck"
118 run_cmd([cls.bin, "init", cls.ck, "256", "16", "16", "2", "32", "2", "4", "1", "10", "4000", "1", "0", "2", "2"])
119 run_cmd([cls.bin, "train", cls.ck, cls.all_corpus, "4", "4"])
120
121 @classmethod
122 def tearDownClass(cls):
123 cls._td.cleanup()
124
125 def test_apuweave_list_w4_interchange_and_tamper(self):
126 out_dir = self.td / "out_list_w4"
127 out_dir.mkdir(parents=True, exist_ok=True)
128 list_file = self.td / "shards.list"
129 list_file.write_text("\n".join(str(p) for p in self.shard_paths) + "\n", encoding="utf-8")
130
131 workers = "4" if platform.system() == "Linux" else "1"
132 r = run_cmd([self.bin, "apuweave", self.ck, list_file, out_dir, "24", "100", "128", "4", workers])
133 waves, strands, summary, overlap = parse_telemetry(r.stdout)
134
135 self.assertGreaterEqual(len(waves), 1)
136 self.assertEqual(len(strands), 4)
137 self.assertIsNotNone(summary)
138 self.assertIsNotNone(overlap)
139
140 # Verify APU_SUMMARY fields:
141 # n_shards, tot_w, wall_ms, gpu_ms, cpu_ms, sps_x1000, ov_x1000, w4_bytes, m_bev, m_wev, drop, tamper_ok, gpu_mode
142 self.assertEqual(summary[0], 4)
143 self.assertEqual(summary[11], 4, "Every strand must pass live 1-bit tamper rc=61 check")
144 self.assertGreater(summary[7], 4 * 80)
145
146 # Verify every strand passed live tamper check (trc == 61) and improved calibration loss
147 for st in strands:
148 self.assertEqual(st[10], 61)
149 self.assertLessEqual(st[3], st[2], f"strand {st[0]} cal loss did not improve: {st[2]} -> {st[3]}")
150
151 # Verify OLLMSP02 header & full compatibility with `ollm spweval` + `ollm spwsamp`
152 sp2_files = [out_dir / f"s{i:02d}_domain{i}.sp2" for i in range(4)]
153 for idx, sp in enumerate(sp2_files):
154 self.assertTrue(sp.is_file(), f"missing {sp}")
155 hdr = struct.unpack("<10Q", sp.read_bytes()[:80])
156 self.assertEqual(hdr[0], OSP2_MAG)
157 self.assertEqual(hdr[2], 2) # L_phys
158 self.assertEqual(hdr[3], 16) # D
159 self.assertEqual(hdr[4], 24) # F_exp
160 self.assertEqual(hdr[5], idx + 1)
161 self.assertEqual(hdr[6], 4) # W4
162
163 ev = run_cmd([self.bin, "spweval", self.ck, self.all_corpus, "2", "4", *sp2_files])
164 toks = ev.stdout.strip().split()
165 self.assertEqual(toks[0], "SPWEVAL")
166 base_u6, wov_u6 = int(toks[4]), int(toks[5])
167 self.assertLess(wov_u6, base_u6, f"spweval woven {wov_u6} must beat base {base_u6}")
168
169 samp = subprocess.run(
170 [self.bin, "spwsamp", self.ck, "42", "12", "2", "0", *sp2_files],
171 capture_output=True,
172 )
173 self.assertEqual(samp.returncode, 0, samp.stderr)
174 self.assertGreater(len(samp.stdout), 0)
175
176 # External 1-bit payload tamper negative control -> rc=61
177 bad = self.td / "tampered.sp2"
178 raw = bytearray(sp2_files[0].read_bytes())
179 raw[80] ^= 0x01
180 bad.write_bytes(bytes(raw))
181 tr = run_cmd([self.bin, "spweval", self.ck, self.all_corpus, "1", "1", bad], check=False)
182 self.assertEqual(tr.returncode, 61)
183
184 def test_apuweave_f64_and_three_col_list(self):
185 out_dir = self.td / "out_f64"
186 out_dir.mkdir(parents=True, exist_ok=True)
187 list3 = self.td / "shards3.list"
188 lines = [f"{10 + i} {p} {out_dir / (p.stem + '.sp2')}" for i, p in enumerate(self.shard_paths[:2])]
189 list3.write_text("\n".join(lines) + "\n", encoding="utf-8")
190
191 r = run_cmd([self.bin, "apuweave", self.ck, list3, out_dir, "24", "100", "128", "64", "2"])
192 _, strands, summary, _ = parse_telemetry(r.stdout)
193 self.assertEqual(len(strands), 2)
194 self.assertEqual(summary[11], 2)
195 sids = sorted(st[0] for st in strands)
196 self.assertEqual(sids, [10, 11])
197 sp0 = out_dir / "s00_domain0.sp2"
198 hdr = struct.unpack("<10Q", sp0.read_bytes()[:80])
199 self.assertEqual(hdr[6], 64)
200
201 def test_apuweave_dir_discovery_and_multiproc_linux(self):
202 if platform.system() != "Linux":
203 self.skipTest("directory scan (getdnts) + multi-proc fork pool is Linux-only")
204 # Build a dir containing real .tok shards plus DRA-1023 traps:
205 # nested.tok/ subdir (DT_DIR), dotfile ._hidden.tok, FIFO pipe.tok (DT_FIFO),
206 # symlink-to-dir, symlink-to-FIFO, and a valid symlink-to-regular .tok file.
207 mix_dir = self.td / "shards_mixed"
208 mix_dir.mkdir(parents=True)
209 for p in self.shard_paths:
210 (mix_dir / p.name).write_bytes(p.read_bytes())
211 nested = mix_dir / "nested.tok"
212 nested.mkdir()
213 (nested / "inner.tok").write_bytes(self.shard_paths[0].read_bytes())
214 (mix_dir / "._appledouble.tok").write_bytes(self.shard_paths[0].read_bytes())
215 fifo = mix_dir / "pipe.tok"
216 os.mkfifo(fifo)
217 os.symlink(nested, mix_dir / "link_to_dir.tok")
218 os.symlink(fifo, mix_dir / "link_to_fifo.tok")
219 os.symlink("/dev/null", mix_dir / "link_to_devnull.tok")
220 os.symlink(mix_dir / self.shard_paths[0].name, mix_dir / "s99_symlink.tok")
221
222 out_dir = self.td / "out_dir_linux"
223 # Do NOT pre-create out_dir to test automatic `makedir`!
224 r = run_cmd([self.bin, "apuweave", self.ck, mix_dir, out_dir, "24", "100", "128", "4", "4"])
225 waves, strands, summary, _ = parse_telemetry(r.stdout)
226 self.assertEqual(summary[0], 5, "4 regular .tok + 1 valid regular symlink; dirs/FIFOs/devices/dotfiles skipped")
227 self.assertEqual(summary[1], 8, "workers=4 + 2 pref + 2 verif = 8 Grace workers")
228 self.assertEqual(summary[11], 5)
229 self.assertEqual(len(strands), 5)
230 self.assertTrue((out_dir / "s03_domain3.sp2").is_file())
231 self.assertTrue((out_dir / "s99_symlink.sp2").is_file())
232 self.assertFalse((out_dir / "nested.sp2").exists())
233 self.assertFalse((out_dir / "pipe.sp2").exists())
234 self.assertFalse((out_dir / "link_to_dir.sp2").exists())
235 self.assertFalse((out_dir / "link_to_fifo.sp2").exists())
236 self.assertFalse((out_dir / "link_to_devnull.sp2").exists())
237 self.assertFalse((out_dir / "._appledouble.sp2").exists())
238
239 def test_apuweave_gb10_live_silicon(self):
240 if os.environ.get("OLLM_GB10_LIVE") != "1":
241 self.skipTest("set OLLM_GB10_LIVE=1 on DGX Spark to run live GB10 GPU+Grace test")
242 gb10_bin = build_target(self.td / "bin_gb10", "gb10")
243 ck_gpu = self.td / "gpu_loop.ck"
244 run_cmd([gb10_bin, "init", ck_gpu, "256", "64", "64", "2", "128", "2", "4", "1", "10", "4000", "1", "0", "2", "2"])
245 out_dir = self.td / "out_gb10"
246 r = run_cmd([gb10_bin, "apuweave", ck_gpu, self.shards_dir, out_dir, "32", "100", "128", "4", "4"])
247 _, strands, summary, _ = parse_telemetry(r.stdout)
248 self.assertEqual(summary[0], 4)
249 self.assertEqual(summary[11], 4)
250 self.assertIn(summary[12], (1, 2), f"expected GB10 GPU mode (1=BF16 or 2=FP32), got {summary[12]}")
251 self.assertEqual(len(strands), 4)
252 sp2_files = [out_dir / f"s{i:02d}_domain{i}.sp2" for i in range(4)]
253 ev = run_cmd([gb10_bin, "spweval", ck_gpu, self.all_corpus, "2", "2", *sp2_files])
254 toks = ev.stdout.strip().split()
255 self.assertEqual(toks[0], "SPWEVAL")
256 self.assertLess(int(toks[5]), int(toks[4]))
257
258
259if __name__ == "__main__":
260 unittest.main()