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_gpu_metal_macos.py

604 lines · 28798 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Verification tests for Apple Silicon Metal GPU backend (native/gpu/metal_macos.om).
3
4Safe on all CI runners (Linux x86_64, Linux aarch64, headless macOS VMs, Apple Silicon):
5 - Test 1 (all platforms): pure-Omega source audit under native/gpu/ (zero C/ObjC/Xcode).
6 - Test 2 (macOS arm64): Mach-O 64-bit arm64 linkage (libSystem.B.dylib only) & codesign.
7 - Test 3 (Apple Silicon live Metal GPU; skips cleanly on headless VMs with rc=75):
8 mdev device + 17 pipeline compilation, mops (GEMM0/1/2, RMSNORM, ATTN, ADAMW),
9 mgemm throughput & accuracy + OLLM_METAL_MUTANT=2 negative control (rc=45).
10 - Test 4 (Apple Silicon live Metal GPU): end-to-end transformer parity against CPU
11 ollm-macos across small, medium, and looped OLLMCK03 geometries (gforward, gcmp,
12 gacmp, geval vs eval, gsample vs sample) + kernel mutant (rc=45) and tampered-weight
13 (rc=14 corrupted FNV & recomputed-FNV diverged loss) negative controls.
14 - Test 5 (Apple Silicon live Metal GPU): 10-step resident Metal gtrain vs CPU train
15 convergence parity + live Metal GPU vs CPU throughput benchmark printout.
16"""
17
18from __future__ import annotations
19
20import os
21import platform
22import shutil
23import struct
24import subprocess
25import tempfile
26import time
27import unittest
28from pathlib import Path
29
30ROOT = Path(__file__).resolve().parent.parent
31
32
33def _fnv1a64(data: bytes) -> int:
34 h = 14695981039346656037
35 for b in data:
36 h = ((h ^ b) * 1099511628211) & 0xFFFFFFFFFFFFFFFF
37 return h
38
39
40def _resolve_cpu_bin() -> Path:
41 env_bin = os.environ.get("OLLM_BIN")
42 if env_bin:
43 p = Path(env_bin)
44 if p.is_file() and os.access(p, os.X_OK):
45 return p
46 sys_name = platform.system()
47 mach = platform.machine()
48 if sys_name == "Darwin":
49 cands = [ROOT / "build" / "verify-om" / "ollm-macos", ROOT / "build" / "ollm-macos"]
50 target = "macos"
51 elif mach in ("x86_64", "amd64"):
52 cands = [ROOT / "build" / "verify-om" / "ollm-x86linux", ROOT / "build" / "ollm-x86linux"]
53 target = "x86linux"
54 else:
55 cands = [ROOT / "build" / "verify-om" / "ollm", ROOT / "build" / "ollm"]
56 target = "aarch64"
57 for c in cands:
58 if c.is_file() and os.access(c, os.X_OK):
59 return c
60 subprocess.run(
61 ["sh", str(ROOT / "scripts" / "build.sh")],
62 cwd=str(ROOT),
63 env={**os.environ, "TARGET": target},
64 check=True,
65 )
66 return cands[-1]
67
68
69def _resolve_metal_bin() -> Path | None:
70 if platform.system() != "Darwin" or platform.machine() != "arm64":
71 return None
72 env_bin = os.environ.get("OLLM_METAL_BIN")
73 if env_bin:
74 p = Path(env_bin)
75 if p.is_file() and os.access(p, os.X_OK):
76 return p
77 for c in (
78 ROOT / "build" / "ollm-metal",
79 ROOT / "build" / "verify-om" / "ollm-metal",
80 ROOT / "build" / "verify" / "ollm-metal",
81 ):
82 if c.is_file() and os.access(c, os.X_OK):
83 return c
84 return None
85
86
87class TestGpuMetalMacOS(unittest.TestCase):
88 def setUp(self) -> None:
89 self.tmp = Path(tempfile.mkdtemp(prefix="omega-gpu-metal-"))
90 self.corp = self.tmp / "corp.txt"
91 parts = []
92 for rel in ("README.md", "docs/LOOP.md"):
93 p = ROOT / rel
94 if p.is_file():
95 parts.append(p.read_bytes())
96 raw = b"\n".join(parts)
97 while len(raw) < 32768:
98 raw += raw
99 self.corp.write_bytes(raw[:32768])
100
101 def tearDown(self) -> None:
102 shutil.rmtree(self.tmp, ignore_errors=True)
103
104 def _require_live_metal(self) -> tuple[Path, Path]:
105 if platform.system() != "Darwin" or platform.machine() != "arm64":
106 self.skipTest("requires Apple Silicon macOS (Darwin arm64)")
107 mtl = _resolve_metal_bin()
108 if mtl is None:
109 self.skipTest("ollm-metal binary not built (requires ng / OMEGA_MV)")
110 assert mtl is not None
111 probe = subprocess.run([str(mtl), "mdev"], capture_output=True, text=True)
112 if probe.returncode == 75:
113 self.skipTest(f"no Metal GPU device on this macOS host: {probe.stderr.strip()}")
114 self.assertEqual(probe.returncode, 0, f"mdev failed ({probe.returncode}): {probe.stderr}")
115 self.assertIn("MDEV ", probe.stdout)
116 self.assertIn("PASS", probe.stdout)
117 cpu = _resolve_cpu_bin()
118 return mtl, cpu
119
120 def test_pure_omega_source_audit(self) -> None:
121 gpu_dir = ROOT / "native" / "gpu"
122 for name in ("mpool.om", "metal_io.om", "metal_msl.om", "metal_macos.om"):
123 p = gpu_dir / name
124 self.assertTrue(p.is_file(), f"missing pure-Omega Metal unit: {p}")
125 disallowed_exts = {".c", ".cc", ".cpp", ".h", ".m", ".mm", ".swift", ".xcodeproj"}
126 for p in gpu_dir.rglob("*"):
127 self.assertNotIn(p.suffix.lower(), disallowed_exts, f"disallowed non-Omega file: {p}")
128 build_sh = (ROOT / "scripts" / "build.sh").read_text(encoding="utf-8")
129 self.assertIn("macos-metal", build_sh)
130 self.assertIn("@ng a64 macho", build_sh)
131 metal_src = (gpu_dir / "metal_macos.om").read_text(encoding="utf-8")
132 self.assertIn("/System/Library/Frameworks/Metal.framework/Metal", metal_src)
133 self.assertIn("MTLCreateSystemDefaultDevice", metal_src)
134
135 def test_macho_binary_and_linkage(self) -> None:
136 if platform.system() != "Darwin" or platform.machine() != "arm64":
137 self.skipTest("requires Darwin arm64")
138 mtl = _resolve_metal_bin()
139 if mtl is None:
140 self.skipTest("ollm-metal binary not built")
141 assert mtl is not None
142
143 f_out = subprocess.run(["file", str(mtl)], capture_output=True, text=True, check=True)
144 self.assertIn("Mach-O 64-bit executable arm64", f_out.stdout)
145
146 ot = subprocess.run(["otool", "-L", str(mtl)], capture_output=True, text=True, check=True)
147 deps = [line.strip().split()[0] for line in ot.stdout.splitlines()[1:] if line.strip()]
148 self.assertEqual(deps, ["/usr/lib/libSystem.B.dylib"], f"unexpected dynamic deps: {deps}")
149
150 cs = subprocess.run(["codesign", "-v", str(mtl)], capture_output=True, text=True)
151 self.assertEqual(cs.returncode, 0, cs.stderr)
152
153 def test_live_metal_device_and_kernels(self) -> None:
154 mtl, _ = self._require_live_metal()
155
156 r_dev = subprocess.run([str(mtl), "mdev"], capture_output=True, text=True, check=True)
157 self.assertIn("unified=1", r_dev.stdout)
158 self.assertIn("pipelines=17", r_dev.stdout)
159 self.assertIn("PASS", r_dev.stdout)
160
161 r_mops = subprocess.run([str(mtl), "mops"], capture_output=True, text=True, check=True)
162 for op in ("GEMM0", "GEMM1", "GEMM2", "RMSNORM", "ATTN", "ADAMW"):
163 self.assertIn(f"MOPS {op} ", r_mops.stdout)
164 self.assertIn("MOPS PASS", r_mops.stdout)
165
166 r_gemm = subprocess.run([str(mtl), "mgemm", "512", "512", "512", "10"], capture_output=True, text=True, check=True)
167 self.assertIn("MGEMM 512 512 512 10 ", r_gemm.stdout)
168 self.assertIn(" PASS", r_gemm.stdout)
169
170 # Negative control: tampered GEMM mutant adds +1.0f to C[0] and must fail with rc=45
171 r_mut = subprocess.run(
172 [str(mtl), "mgemm", "128", "128", "128", "1"],
173 env={**os.environ, "OLLM_METAL_MUTANT": "2"},
174 capture_output=True,
175 text=True,
176 )
177 self.assertEqual(r_mut.returncode, 45, f"expected rc=45 on GEMM mutant, got {r_mut.returncode}: {r_mut.stdout}")
178 self.assertIn(" FAIL", r_mut.stdout)
179
180 def test_live_metal_transformer_parity_and_negative_controls(self) -> None:
181 mtl, cpu = self._require_live_metal()
182
183 shapes = [
184 ("small", ["256", "16", "16", "2", "32", "2", "2", "1", "10", "3000", "1"]),
185 ("medium", ["256", "64", "128", "4", "256", "2", "2", "1", "10", "3000", "1"]),
186 ("looped", ["256", "32", "64", "4", "128", "2", "2", "1", "10", "3000", "1", "0", "2", "2"]),
187 ]
188
189 for label, init_args in shapes:
190 ck = self.tmp / f"{label}.ck"
191 subprocess.run([str(mtl), "init", str(ck), *init_args], capture_output=True, text=True, check=True)
192
193 rf = subprocess.run([str(mtl), "gforward", str(ck), str(self.corp), "0"], capture_output=True, text=True, check=True)
194 self.assertIn("GFORWARD PASS", rf.stdout, f"{label} gforward failed: {rf.stdout}")
195
196 rg = subprocess.run([str(mtl), "gcmp", str(ck), str(self.corp), "0"], capture_output=True, text=True, check=True)
197 self.assertIn("GCMP PASS", rg.stdout, f"{label} gcmp failed: {rg.stdout}")
198 gc_line = [ln for ln in rg.stdout.splitlines() if ln.startswith("GC ")][0].split()
199 cos_e9 = int(gc_line[9])
200 self.assertGreaterEqual(cos_e9, 999900000, f"{label} gradient cosine too low: {gc_line}")
201
202 ra = subprocess.run([str(mtl), "gacmp", str(ck), str(self.corp), "0"], capture_output=True, text=True, check=True)
203 self.assertIn("GACMP PASS", ra.stdout, f"{label} gacmp failed: {ra.stdout}")
204
205 ev_cpu = subprocess.run([str(cpu), "eval", str(ck), str(self.corp), "4"], capture_output=True, text=True, check=True)
206 ev_mtl = subprocess.run([str(mtl), "geval", str(ck), str(self.corp), "4"], capture_output=True, text=True, check=True)
207 c_loss = int([ln for ln in ev_cpu.stdout.splitlines() if ln.startswith("E ")][0].split()[3])
208 m_loss = int([ln for ln in ev_mtl.stdout.splitlines() if ln.startswith("E ")][0].split()[3])
209 self.assertLess(abs(m_loss - c_loss), 1000, f"{label} eval loss mismatch: cpu={c_loss} mtl={m_loss}")
210
211 # Negative control A: dK sign-flip mutant in k_attn_bwd_dk_dv must fail gcmp with rc=45
212 rg_mut = subprocess.run(
213 [str(mtl), "gcmp", str(ck), str(self.corp), "0"],
214 env={**os.environ, "OLLM_METAL_MUTANT": "1"},
215 capture_output=True,
216 text=True,
217 )
218 self.assertEqual(rg_mut.returncode, 45, f"{label} mutant expected rc=45, got {rg_mut.returncode}: {rg_mut.stdout}")
219 self.assertIn("GCMP FAIL", rg_mut.stdout)
220
221 # Sample parity on small checkpoint
222 sm_ck = self.tmp / "small.ck"
223 s_cpu = subprocess.run([str(cpu), "sample", str(sm_ck), "42", "16", "0", "Once upon"], capture_output=True, check=True)
224 s_mtl = subprocess.run([str(mtl), "gsample", str(sm_ck), "42", "16", "0", "Once upon"], capture_output=True, check=True)
225 self.assertEqual(s_cpu.stdout, s_mtl.stdout)
226
227 # Negative control B1: 1-bit weight corruption without updating FNV-1a header trips rc=14
228 bad_ck = bytearray(sm_ck.read_bytes())
229 bad_ck[120] ^= 0xFF
230 bad_path = self.tmp / "bad_fnv.ck"
231 bad_path.write_bytes(bad_ck)
232 r_bad = subprocess.run([str(mtl), "geval", str(bad_path), str(self.corp), "4"], capture_output=True, text=True)
233 self.assertEqual(r_bad.returncode, 14)
234
235 # Negative control B2: tampered weights with valid recomputed FNV-1a diverge from clean oracle
236 tamp_ck = bytearray(sm_ck.read_bytes())
237 magic = bytes(tamp_ck[:8])
238 hdr_len = {b"OLLMCK01": 112, b"OLLMCK02": 120, b"OLLMCK03": 144}[magic]
239 p_count = struct.unpack_from("<Q", tamp_ck, 96)[0]
240 fnv_off = hdr_len - 8
241 for i in range(min(512, p_count)):
242 off = hdr_len + i * 8
243 val = struct.unpack_from("<d", tamp_ck, off)[0]
244 struct.pack_into("<d", tamp_ck, off, val + 2.5)
245 new_fnv = _fnv1a64(bytes(tamp_ck[hdr_len:]))
246 struct.pack_into("<Q", tamp_ck, fnv_off, new_fnv)
247 tamp_path = self.tmp / "tampered_weights.ck"
248 tamp_path.write_bytes(tamp_ck)
249
250 ev_clean = subprocess.run([str(cpu), "eval", str(sm_ck), str(self.corp), "4"], capture_output=True, text=True, check=True)
251 ev_tamp = subprocess.run([str(mtl), "geval", str(tamp_path), str(self.corp), "4"], capture_output=True, text=True, check=True)
252 clean_loss = int([ln for ln in ev_clean.stdout.splitlines() if ln.startswith("E ")][0].split()[3])
253 tamp_loss = int([ln for ln in ev_tamp.stdout.splitlines() if ln.startswith("E ")][0].split()[3])
254 self.assertGreater(abs(tamp_loss - clean_loss), 100000, f"tampered weights did not diverge: clean={clean_loss} tamp={tamp_loss}")
255
256 def test_live_metal_training_convergence_and_benchmark(self) -> None:
257 mtl, cpu = self._require_live_metal()
258
259 ck_cpu = self.tmp / "bench_cpu.ck"
260 ck_mtl = self.tmp / "bench_mtl.ck"
261 subprocess.run(
262 [str(mtl), "init", str(ck_cpu), "256", "64", "128", "4", "256", "4", "4", "1", "10", "3000", "1"],
263 capture_output=True,
264 text=True,
265 check=True,
266 )
267 shutil.copy2(ck_cpu, ck_mtl)
268
269 t0 = time.perf_counter_ns()
270 r_cpu = subprocess.run([str(cpu), "train", str(ck_cpu), str(self.corp), "10", "5"], capture_output=True, text=True, check=True)
271 cpu_ns = time.perf_counter_ns() - t0
272
273 r_mtl = subprocess.run([str(mtl), "gtrain", str(ck_mtl), str(self.corp), "10", "5"], capture_output=True, text=True, check=True)
274
275 cpu_t = [ln.split() for ln in r_cpu.stdout.splitlines() if ln.startswith("T ")]
276 mtl_t = [ln.split() for ln in r_mtl.stdout.splitlines() if ln.startswith("T ")]
277 self.assertEqual(len(cpu_t), 2)
278 self.assertEqual(len(mtl_t), 2)
279 cpu_l5, cpu_l10 = int(cpu_t[0][2]), int(cpu_t[1][2])
280 mtl_l5, mtl_l10 = int(mtl_t[0][2]), int(mtl_t[1][2])
281 self.assertLess(cpu_l10, cpu_l5, "CPU training loss failed to decrease")
282 self.assertLess(mtl_l10, mtl_l5, "Metal GPU training loss failed to decrease")
283 self.assertLess(abs(mtl_l10 - cpu_l10), 5000, f"Metal vs CPU step-10 loss diverged: mtl={mtl_l10} cpu={cpu_l10}")
284
285 ev_c = subprocess.run([str(cpu), "eval", str(ck_cpu), str(self.corp), "4"], capture_output=True, text=True, check=True)
286 ev_m = subprocess.run([str(cpu), "eval", str(ck_mtl), str(self.corp), "4"], capture_output=True, text=True, check=True)
287 el_c = int([ln for ln in ev_c.stdout.splitlines() if ln.startswith("E ")][0].split()[3])
288 el_m = int([ln for ln in ev_m.stdout.splitlines() if ln.startswith("E ")][0].split()[3])
289 self.assertLess(abs(el_m - el_c), 100, f"post-train eval diverged: mtl={el_m} cpu={el_c}")
290
291 mt_line = [ln.split() for ln in r_mtl.stdout.splitlines() if ln.startswith("MT ")][0]
292 mtl_ns = int(mt_line[2])
293 ms_step_mtl = float(mt_line[3]) / 100.0
294 tok_s_mtl = float(mt_line[4]) / 100.0
295 ms_step_cpu = cpu_ns / (10 * 1e6)
296 tok_s_cpu = (10 * 4 * 64) / (cpu_ns / 1e9)
297
298 rgemm = subprocess.run([str(mtl), "mgemm", "1024", "1024", "1024", "20"], capture_output=True, text=True, check=True)
299 gm = [ln.split() for ln in rgemm.stdout.splitlines() if ln.startswith("MGEMM ")][0]
300 gflops = float(gm[6]) / 100.0
301
302 print(
303 f"\nMETAL_BENCH P=566400 (D=128,L=4,B=4,T=64): "
304 f"Metal={ms_step_mtl:.2f} ms/step ({tok_s_mtl:.1f} tok/s) vs "
305 f"CPU={ms_step_cpu:.2f} ms/step ({tok_s_cpu:.1f} tok/s) | "
306 f"Speedup={cpu_ns / max(mtl_ns, 1):.2f}x | "
307 f"SGEMM_1024={gflops:.2f} GFLOP/s"
308 )
309
310 def test_live_metal_freeze_layers_and_spext(self) -> None:
311 mtl, cpu = self._require_live_metal()
312
313 base_ck = self.tmp / "base.ck"
314 spec_ck = self.tmp / "spec.ck"
315 pack_sp = self.tmp / "pack.sp"
316 app_ck = self.tmp / "app.ck"
317 subprocess.run(
318 [str(mtl), "init", str(base_ck), "256", "16", "16", "2", "32", "1", "2", "1", "10", "3000", "1"],
319 capture_output=True,
320 text=True,
321 check=True,
322 )
323 subprocess.run(
324 [str(mtl), "growpro", str(base_ck), str(spec_ck), "2", "10", "3000"],
325 capture_output=True,
326 text=True,
327 check=True,
328 )
329
330 rg = subprocess.run([str(mtl), "gcmp", str(spec_ck), str(self.corp), "0", "1"], capture_output=True, text=True, check=True)
331 self.assertIn("GCF 1 ", rg.stdout)
332 gcf_line = [ln for ln in rg.stdout.splitlines() if ln.startswith("GCF ")][0].split()
333 self.assertEqual(int(gcf_line[3]), 0, f"frozen gradients non-zero: {gcf_line}")
334 gc_line = [ln for ln in rg.stdout.splitlines() if ln.startswith("GC ")][0].split()
335 self.assertGreaterEqual(int(gc_line[9]), 999900000, f"frozen gcmp cos too low: {gc_line}")
336 self.assertIn("GCMP PASS", rg.stdout)
337
338 ra = subprocess.run([str(mtl), "gacmp", str(spec_ck), str(self.corp), "0", "1"], capture_output=True, text=True, check=True)
339 self.assertIn("GAF 1 ", ra.stdout)
340 gaf_line = [ln for ln in ra.stdout.splitlines() if ln.startswith("GAF ")][0].split()
341 self.assertEqual(int(gaf_line[3]), 0, f"frozen Adam weights changed: {gaf_line}")
342 self.assertIn("GACMP PASS", ra.stdout)
343
344 subprocess.run([str(mtl), "gtrain", str(spec_ck), str(self.corp), "5", "5", "1"], capture_output=True, text=True, check=True)
345 rsp = subprocess.run([str(mtl), "spext", str(base_ck), str(spec_ck), str(pack_sp)], capture_output=True, text=True, check=True)
346 self.assertIn("SPEXT 1 2 ", rsp.stdout)
347
348 subprocess.run([str(cpu), "spapp", str(base_ck), str(pack_sp), str(app_ck)], capture_output=True, text=True, check=True)
349 ev_spec = subprocess.run([str(cpu), "eval", str(spec_ck), str(self.corp), "4"], capture_output=True, text=True, check=True)
350 ev_app = subprocess.run([str(cpu), "eval", str(app_ck), str(self.corp), "4"], capture_output=True, text=True, check=True)
351 self.assertEqual(ev_spec.stdout.split()[2:], ev_app.stdout.split()[2:])
352
353 def test_live_metal_nan_fails_closed(self) -> None:
354 mtl, _ = self._require_live_metal()
355
356 ck = self.tmp / "nan_small.ck"
357 subprocess.run(
358 [str(mtl), "init", str(ck), "256", "16", "16", "2", "32", "2", "2", "1", "10", "3000", "1"],
359 capture_output=True,
360 text=True,
361 check=True,
362 )
363
364 r_mg = subprocess.run(
365 [str(mtl), "mgemm", "128", "128", "128", "1"],
366 env={**os.environ, "OLLM_METAL_MUTANT": "3"},
367 capture_output=True,
368 text=True,
369 )
370 self.assertEqual(r_mg.returncode, 45, f"mgemm NaN expected rc=45, got {r_mg.returncode}: {r_mg.stdout}")
371 self.assertIn(" FAIL", r_mg.stdout)
372
373 r_mo = subprocess.run(
374 [str(mtl), "mops"],
375 env={**os.environ, "OLLM_METAL_MUTANT": "3"},
376 capture_output=True,
377 text=True,
378 )
379 self.assertEqual(r_mo.returncode, 45, f"mops NaN gemm expected rc=45, got {r_mo.returncode}: {r_mo.stdout}")
380 self.assertIn("MOPS GEMM0 ", r_mo.stdout)
381 self.assertIn(" FAIL", r_mo.stdout)
382
383 r_gf = subprocess.run(
384 [str(mtl), "gforward", str(ck), str(self.corp), "0"],
385 env={**os.environ, "OLLM_METAL_MUTANT": "3"},
386 capture_output=True,
387 text=True,
388 )
389 self.assertEqual(r_gf.returncode, 45, f"gforward NaN expected rc=45, got {r_gf.returncode}: {r_gf.stdout}")
390 self.assertIn(" FAIL", r_gf.stdout)
391
392 r_gc = subprocess.run(
393 [str(mtl), "gcmp", str(ck), str(self.corp), "0"],
394 env={**os.environ, "OLLM_METAL_MUTANT": "4"},
395 capture_output=True,
396 text=True,
397 )
398 self.assertEqual(r_gc.returncode, 45, f"gcmp NaN grad expected rc=45, got {r_gc.returncode}: {r_gc.stdout}")
399 self.assertIn("GCMP FAIL", r_gc.stdout)
400 gc_line = [ln for ln in r_gc.stdout.splitlines() if ln.startswith("GC ")][0].split()
401 self.assertEqual(int(gc_line[9]), 0, f"expected cos_e9=0 on NaN gradient, got {gc_line}")
402 self.assertLess(abs(int(gc_line[5]) - int(gc_line[6])), 100, f"expected finite forward losses on mutant 4: {gc_line}")
403
404 r_ga = subprocess.run(
405 [str(mtl), "gacmp", str(ck), str(self.corp), "0"],
406 env={**os.environ, "OLLM_METAL_MUTANT": "5"},
407 capture_output=True,
408 text=True,
409 )
410 self.assertEqual(r_ga.returncode, 46, f"gacmp NaN weight expected rc=46, got {r_ga.returncode}: {r_ga.stdout}")
411 self.assertIn("GACMP FAIL", r_ga.stdout)
412
413 r_ma = subprocess.run(
414 [str(mtl), "mops"],
415 env={**os.environ, "OLLM_METAL_MUTANT": "5"},
416 capture_output=True,
417 text=True,
418 )
419 self.assertEqual(r_ma.returncode, 45, f"mops NaN adamw expected rc=45, got {r_ma.returncode}: {r_ma.stdout}")
420 self.assertIn("MOPS ADAMW ", r_ma.stdout)
421 self.assertIn(" FAIL", r_ma.stdout)
422
423 def test_metal_io_pool_limit_and_dir_read(self) -> None:
424 if platform.system() != "Darwin" or platform.machine() != "arm64":
425 self.skipTest("requires Darwin arm64")
426 mtl = _resolve_metal_bin()
427 if mtl is None:
428 self.skipTest("ollm-metal binary not built")
429 assert mtl is not None
430
431 big_ck = self.tmp / "big_pool.ck"
432 r_big = subprocess.run(
433 [str(mtl), "init", str(big_ck), "4096", "256", "384", "16", "1536", "8", "1", "1", "10", "3000", "1"],
434 capture_output=True,
435 text=True,
436 )
437 self.assertEqual(r_big.returncode, 12, f"expected exit 12 when P > 8388608, got {r_big.returncode}: {r_big.stderr}")
438
439 sm_ck = self.tmp / "io_small.ck"
440 subprocess.run(
441 [str(mtl), "init", str(sm_ck), "256", "16", "16", "2", "32", "2", "2", "1", "10", "3000", "1"],
442 capture_output=True,
443 text=True,
444 check=True,
445 )
446 dir_in = self.tmp / "dir_input"
447 dir_in.mkdir()
448
449 r_dir_data = subprocess.run([str(mtl), "eval", str(sm_ck), str(dir_in), "1"], capture_output=True, text=True)
450 self.assertEqual(r_dir_data.returncode, 70, f"odread on directory expected exit 70, got {r_dir_data.returncode}")
451
452 r_dir_ck = subprocess.run([str(mtl), "eval", str(dir_in), str(self.corp), "1"], capture_output=True, text=True)
453 self.assertEqual(r_dir_ck.returncode, 70, f"oprd on directory expected exit 70, got {r_dir_ck.returncode}")
454
455 def test_find_ng_ignores_fake_path_ng(self) -> None:
456 omc = os.environ.get("OMC")
457 if not omc or not Path(omc).is_file():
458 for cand in (
459 shutil.which("omc"),
460 str(Path.home() / ".local" / "bin" / "omc"),
461 str(Path.home() / "canon" / "omega-mv" / "seed" / "out" / "omc"),
462 str(ROOT.parent / "omega-mv" / "seed" / "out" / "omc"),
463 str(ROOT.parent / "omega-mv-macos" / "seed" / "out" / "omc"),
464 ):
465 if cand and Path(cand).is_file() and os.access(cand, os.X_OK):
466 omc = cand
467 break
468 if not omc or not Path(omc).is_file():
469 self.skipTest("omc not found for find_ng test")
470
471 fake_bin = self.tmp / "fake_bin"
472 fake_bin.mkdir()
473 hit = self.tmp / "fake_ng_called"
474 fake_ng = fake_bin / "ng"
475 fake_ng.write_text(
476 f"#!/bin/sh\ntouch '{hit}'\necho 'Angular CLI: 19.0.0'\nexit 0\n",
477 encoding="utf-8",
478 )
479 fake_ng.chmod(0o755)
480
481 base_env = {k: v for k, v in os.environ.items() if k not in ("NG", "OMEGA_MV")}
482 base_env["OMC"] = omc
483 base_env["TARGET"] = "macos-metal"
484 base_env["PATH"] = f"{fake_bin}:{base_env.get('PATH', '')}"
485
486 r_bad = subprocess.run(
487 ["sh", str(ROOT / "scripts" / "build.sh")],
488 cwd=str(ROOT),
489 env={**base_env, "NG": str(fake_ng), "OUT": str(self.tmp / "out_bad_ng")},
490 capture_output=True,
491 text=True,
492 )
493 self.assertNotEqual(r_bad.returncode, 0)
494 self.assertIn("not an executable Omega ng compiler", r_bad.stderr)
495 hit.unlink(missing_ok=True)
496
497 sibling_omv = (
498 (ROOT.parent / "omega-mv" / "seed" / "ng" / "src" / "ir.om").is_file()
499 or (ROOT.parent / "omega-mv-macos" / "seed" / "ng" / "src" / "ir.om").is_file()
500 )
501 if not sibling_omv:
502 empty_home = self.tmp / "empty_home"
503 empty_home.mkdir()
504 out_no_ng = self.tmp / "out_no_ng"
505 r_no_ng = subprocess.run(
506 ["sh", str(ROOT / "scripts" / "build.sh")],
507 cwd=str(ROOT),
508 env={**base_env, "HOME": str(empty_home), "OUT": str(out_no_ng)},
509 capture_output=True,
510 text=True,
511 )
512 self.assertNotEqual(r_no_ng.returncode, 0, f"fake PATH ng was accepted: {r_no_ng.stdout}\n{r_no_ng.stderr}")
513 self.assertFalse((out_no_ng / "ollm-metal").exists())
514 hit.unlink(missing_ok=True)
515
516 if platform.system() != "Darwin" or platform.machine() != "arm64":
517 return
518
519 real_ng: Path | None = None
520 for cand in (ROOT / "build" / "verify-om" / "ng", ROOT / "build" / "verify" / "ng", ROOT / "build" / "ng"):
521 if cand.is_file() and os.access(cand, os.X_OK):
522 real_ng = cand
523 break
524 if real_ng is not None:
525 out_real = self.tmp / "out_real_ng"
526 out_real.mkdir()
527 shutil.copy2(real_ng, out_real / "ng")
528 subprocess.run(
529 ["sh", str(ROOT / "scripts" / "build.sh")],
530 cwd=str(ROOT),
531 env={**base_env, "OUT": str(out_real)},
532 capture_output=True,
533 text=True,
534 check=True,
535 )
536 self.assertTrue((out_real / "ollm-metal").is_file())
537 self.assertFalse(hit.exists(), "build.sh invoked fake PATH ng despite $OUT/ng")
538
539 omv_root: Path | None = None
540 for cand_str in (
541 os.environ.get("OMEGA_MV"),
542 str(Path.home() / "workspace" / "omega-mv-macos"),
543 str(Path.home() / "canon" / "omega-mv"),
544 str(ROOT.parent / "omega-mv"),
545 str(ROOT.parent / "omega-mv-macos"),
546 ):
547 if cand_str:
548 p = Path(cand_str)
549 if (p / "seed" / "ng" / "src" / "ir.om").is_file() and (p / "seed" / "ng" / "src" / "a64.om").is_file():
550 omv_root = p
551 break
552 if omv_root is not None:
553 out_omv = self.tmp / "out_omv"
554 subprocess.run(
555 ["sh", str(ROOT / "scripts" / "build.sh")],
556 cwd=str(ROOT),
557 env={**base_env, "OMEGA_MV": str(omv_root), "OUT": str(out_omv)},
558 capture_output=True,
559 text=True,
560 check=True,
561 )
562 self.assertTrue((out_omv / "ollm-metal").is_file())
563 self.assertFalse(hit.exists(), "build.sh invoked fake PATH ng despite OMEGA_MV")
564
565 def test_mgemm_rejects_overflow_and_oversized_dims(self) -> None:
566 if platform.system() != "Darwin" or platform.machine() != "arm64":
567 self.skipTest("requires Darwin arm64")
568 mtl = _resolve_metal_bin()
569 if mtl is None:
570 self.skipTest("ollm-metal binary not built")
571 assert mtl is not None
572
573 bad_cases = [
574 ("4294967296", "4294967296", "1", "1"),
575 ("65537", "1", "1", "1"),
576 ("16384", "16384", "1", "1"),
577 ("16", "16", "16", "10001"),
578 ]
579 for dims in bad_cases:
580 r = subprocess.run([str(mtl), "mgemm", *dims], capture_output=True, text=True)
581 self.assertEqual(
582 r.returncode,
583 2,
584 f"mgemm {' '.join(dims)} expected rc=2, got {r.returncode}: {r.stdout}\n{r.stderr}",
585 )
586
587 def test_metal_exit_codes_and_io_casts(self) -> None:
588 gpu_dir = ROOT / "native" / "gpu"
589 msl_src = (gpu_dir / "metal_msl.om").read_text(encoding="utf-8")
590 self.assertNotIn("exit 75", msl_src, "metal_msl.om must not overload exit 75")
591
592 io_src = (gpu_dir / "metal_io.om").read_text(encoding="utf-8")
593 self.assertNotIn("long mio_g64", io_src, "metal_io.om must not narrow-cast mio_g64 to long (trap 5 on -1)")
594
595 mtl_src = (gpu_dir / "metal_macos.om").read_text(encoding="utf-8")
596 for fn_name in ("fn mtl_load_pso", "fn mtl_alloc_buf"):
597 start = mtl_src.index(fn_name)
598 end = mtl_src.index("\nfn ", start + 1)
599 body = mtl_src[start:end]
600 self.assertNotIn("exit 75", body, f"{fn_name} must not overload exit 75")
601
602
603if __name__ == "__main__":
604 unittest.main()