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

740 lines · 21699 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: AGPL-3.0-only
3"""Pillar 1: Persistent sm_121 Megakernel verification suite.
4
5Checks:
6 1. Pure-OM2 compilation with ~/.local/bin/omc for both `gb10` (`om2` + full
7 native/gpu/{context,vector,launch,batch,gk,gr,gb,gg,gm}.om stack) and
8 `macos` (`target a64macos` + `nogpu.om` + CPU-sim wrapper + `gm.om`).
9 2. Built-in `gm_selftest` pass (`rc == 0`).
10 3. SM121 SASS emitter invariants: single-slot fit (<= 16 KiB), double-buffered
11 slot parity (`gm_swap_buf`), `max_gpr <= 61`, `gkgpr >= max_gpr + 3`,
12 `nested_bssy == 0`, `+16 B` bank-padded SMEM stride (144 B/blk),
13 L2-resident weight budget (`<= 8 MB`), and Spark `nvdisasm -b SM121`
14 disassembly check (0 illegal/unknown insns + MEMBAR.SC.SYS /
15 LDG.E.MMIO.GPU / STG.E.STRONG.SYS / GPR headroom).
16 4. Launch-count = 1 invariant (`gm_launch_persistent` & `gm_sim_steps`).
17 5. Bit-exact parity between `gm_sim_steps` (persistent step loop) and
18 sequential `obatch -> ograd -> oadam` steps across weights, Adam moments,
19 and per-step losses (both synthetic and real `odopen` dataset file), plus
20 training loss decrease and boundary-error rejections.
21
22Usage:
23 python3 -W error::ResourceWarning tests/test_megakernel.py
24"""
25import hashlib
26import os
27import platform
28import re
29import shutil
30import struct
31import subprocess
32import sys
33import tempfile
34
35HERE = os.path.dirname(os.path.abspath(__file__))
36REPO = os.path.dirname(HERE)
37SRC = os.path.join(REPO, "native")
38GPU = os.path.join(SRC, "gpu")
39
40PASSES = []
41FAILS = []
42
43
44def check(cond, name, detail=""):
45 if cond:
46 PASSES.append(name)
47 print(f"PASS {name}" + (f" ({detail})" if detail else ""))
48 else:
49 FAILS.append(name)
50 print(f"FAIL {name}" + (f": {detail}" if detail else ""))
51
52
53def find_omc():
54 for cand in (
55 os.environ.get("OMC"),
56 shutil.which("omc"),
57 os.path.expanduser("~/.local/bin/omc"),
58 os.path.expanduser("~/canon/omega-mv/seed/out/omc"),
59 os.path.join(REPO, "..", "omega-mv", "seed", "out", "omc"),
60 os.path.join(REPO, "..", "omega-mv-macos", "seed", "out", "omc"),
61 ):
62 if cand and os.path.isfile(cand) and os.access(cand, os.X_OK):
63 return cand
64 raise RuntimeError("seeded omc compiler not found")
65
66
67def read_text(path):
68 with open(path, "r", encoding="utf-8") as f:
69 return f.read()
70
71
72def compile_om_bytes(omc, src_text, out_path=None):
73 p = subprocess.run(
74 [omc],
75 input=src_text.encode("utf-8"),
76 stdout=subprocess.PIPE,
77 stderr=subprocess.PIPE,
78 )
79 if out_path is not None and p.returncode == 0:
80 with open(out_path, "wb") as f:
81 f.write(p.stdout)
82 os.chmod(out_path, 0o755)
83 if platform.system() == "Darwin" and shutil.which("codesign"):
84 subprocess.run(
85 ["codesign", "-s", "-", "-f", out_path],
86 stdout=subprocess.DEVNULL,
87 stderr=subprocess.DEVNULL,
88 check=True,
89 )
90 return p.returncode, p.stderr.decode("utf-8", errors="replace"), len(p.stdout)
91
92
93MAC_SIM_SHIM = """
94global gkcode uchar 1048576
95global gkthr uint 64
96global gkgpr uint 64
97global gksm uint 64
98global gkarg uint 32
99global gkna uint 1
100global gkt long 4
101
102fn gklaunch id uint gx uint gy uint gz uint to bool
103put gkt 0 add get gkt 0 1
104ret true
105end
106"""
107
108DRIVER_MAIN = """
109fn gm_print_u tag ulong v ulong to void
110oputx tag
111oputc 32
112oputu v
113oputc 10
114oflush
115end
116
117fn gm_print_f tag ulong v f64 to void
118oputx tag
119oputc 32
120oputx bitcast ulong v
121oputc 32
122oputl rmic v
123oputc 10
124oflush
125end
126
127fn gm_init_shape to void
128put og 0 256
129put og 1 8
130put og 2 16
131put og 3 2
132put og 4 32
133put og 5 2
134put og 6 2
135put og 40 12345
136put og 41 0
137put og 42 100
138put og 43 bitcast ulong 0.001f64
139put og 44 1
140put og 59 1
141if not ogeom
142exit 11
143end
144oinit
145end
146
147fn gm_cmd_d to int
148if not gm_emit_megakernel 0
149ret 20
150end
151if not gm_emit_megakernel 1
152ret 21
153end
154oputu get gmcfg 1
155oputc 32
156oputu get gmcfg 2
157oputc 32
158oputu get gmcfg 3
159oputc 32
160oputu get gmcfg 5
161oputc 32
162oputu get gmcfg 6
163oputc 32
164oputu get gmcfg 7
165oputc 32
166oputu get gmstats 5
167oputc 10
168oflush
169ret 0
170end
171
172fn gm_cmd_b to int
173if not gm_emit_megakernel 0
174ret 20
175end
176if not gm_emit_megakernel 1
177ret 21
178end
179slot = ulong 0
180if ge oargc 3
181slot = oargu 2
182end
183base = mul slot 16384
184n = get gmcfg add 1 slot
185w = write 1 gmcode base n
186if ne w long n
187ret 22
188end
189ret 0
190end
191
192fn gm_cmd_p to int
193gm_init_shape
194use_synth = true
195if ge oargc 3
196odopen 2
197use_synth = false
198end
199nn = ulong 6
200lseq = gm_seq_steps nn use_synth
201gm_save_state
202put og 41 0
203oinit
204lmeg = gm_sim_steps nn use_synth
205diff = gm_parity_diff nn
206oputc 80
207oputc 65
208oputc 82
209oputc 32
210oputu diff
211oputc 32
212oputu get gmstats 0
213oputc 32
214oputu get gmstats 1
215oputc 32
216oputu get gmstats 2
217oputc 32
218oputu get gmstats 3
219oputc 32
220oputu get gmstats 4
221oputc 32
222oputu get gmstats 5
223oputc 32
224oputu get gmstats 6
225oputc 32
226oputx bitcast ulong lseq
227oputc 32
228oputx bitcast ulong lmeg
229oputc 32
230oputl rmic get gmlos_meg 0
231oputc 32
232oputl rmic get gmlos_meg sub nn 1
233oputc 32
234oputu get gmcfg 11
235oputc 10
236oflush
237if ne diff 0
238ret 30
239end
240ret 0
241end
242
243fn gm_cmd_l to int
244gm_init_shape
245if not gm_emit_megakernel 0
246ret 40
247end
248if not gm_emit_megakernel 1
249ret 41
250end
251sw1 = gm_swap_buf
252sl1 = get gmcfg 13
253sw2 = gm_swap_buf
254sl2 = get gmcfg 13
255ok1 = gm_launch_persistent 8
256ln1 = get gmstats 0
257oputc 76
258oputc 78
259oputc 32
260oputu ulong sw1
261oputc 32
262oputu sl1
263oputc 32
264oputu ulong sw2
265oputc 32
266oputu sl2
267oputc 32
268oputu ln1
269oputc 32
270oputu get gmstats 1
271oputc 32
272oputu get gmstats 2
273oputc 32
274oputu get gmcfg 12
275oputc 10
276oflush
277if or not ok1 ne ln1 1
278ret 42
279end
280if or gm_emit_megakernel 2 or gm_launch_persistent 0 gm_launch_persistent 65537
281ret 43
282end
283if ge gm_sim_steps 0 true 0.0f64
284ret 44
285end
286ret 0
287end
288
289fn gm_putb b bool to void
290if b
291oputc 49
292else
293oputc 48
294end
295end
296
297fn gm_cmd_r_neg a0 bool a1 bool to ulong
298saved = gm_r_at 16384
299gm_w_at 16384 0x3a8
300ok = not gm_audit_no_fp_atomics 1
301gm_w_at 16384 saved
302if ok
303ok = gm_audit_probe 0x9a8
304end
305if ok
306ok = gm_audit_probe 0x3aa
307end
308if ok
309ok = gm_audit_probe 0x9aa
310end
311if ok
312ok = gm_audit_probe 0x3a9
313end
314if ok
315ok = gm_audit_probe 0x9a9
316end
317a1p = gm_audit_no_fp_atomics 1
318gm_w_at 16384 0x3a8
319if ne gm_swap_buf 1
320gm_w_at 16384 saved
321ret 0
322end
323lb = not gm_launch_persistent 4
324gm_w_at 16384 saved
325if ne gm_swap_buf 0
326ret 0
327end
328oputc 76
329oputc 79
330oputc 67
331oputc 75
332oputc 49
333oputc 32
334gm_putb a0
335oputc 32
336gm_putb a1
337oputc 32
338gm_putb ok
339oputc 32
340gm_putb a1p
341oputc 32
342gm_putb lb
343if and ok and a1p lb
344ret 1
345end
346ret 0
347end
348
349fn gm_cmd_r to int
350if not gm_emit_megakernel 0
351ret 50
352end
353if not gm_emit_megakernel 1
354ret 51
355end
356a0 = gm_audit_no_fp_atomics 0
357a1 = gm_audit_no_fp_atomics 1
358if or not a0 not a1
359ret 52
360end
361if eq gm_cmd_r_neg a0 a1 0
362ret 53
363end
364fwd = new f64 24 0.0f64
365rev = new f64 24 0.0f64
366intl = new f64 24 0.0f64
367gm_init_cta_terms edit fwd
368for i ulong 24
369put rev i get fwd sub 23 i
370if lt i 12
371put intl i get fwd mul i 2
372else
373put intl i get fwd add mul sub i 12 2 1
374end
375end
376qf = gm_reduce_i64_fixed view fwd 24
377qr = gm_reduce_i64_fixed view rev 24
378qi = gm_reduce_i64_fixed view intl 24
379oputc 32
380oputl qf
381oputc 32
382oputl qr
383oputc 32
384oputl qi
385oputc 32
386oputx bitcast ulong gm_fixed_to_f64 qf
387oputc 32
388oputx bitcast ulong gm_fixed_to_f64 qr
389oputc 32
390oputx bitcast ulong gm_fixed_to_f64 qi
391oputc 32
392oputx bitcast ulong gm_reduce_tree_f64 view fwd 24
393oputc 32
394oputx bitcast ulong gm_reduce_tree_f64 view fwd 19
395oputc 10
396oflush
397if or ne qf qr ne qf qi
398ret 54
399end
400ret 0
401end
402
403fn main to int
404cmd = oargr 1
405if lt cmd 0
406exit 2
407end
408c0 = get oarg 0
409if eq c0 115
410rc = gm_selftest
411oputu ulong rc
412oputc 10
413oflush
414ret rc
415end
416if eq c0 100
417ret gm_cmd_d
418end
419if eq c0 98
420ret gm_cmd_b
421end
422if eq c0 112
423ret gm_cmd_p
424end
425if eq c0 108
426ret gm_cmd_l
427end
428if eq c0 114
429ret gm_cmd_r
430end
431ret 2
432end
433"""
434
435
436def build_macos_source():
437 parts = [
438 "math.om", "data.om", "lpool.om", "model.om", "adam.om",
439 "ckpt.om", "bpe.om", "spec.om", "rev.om", "arboris.om",
440 "sp_solve.om", "spiral.om", "apu_weave.om", "omg.om", "pillars_cli.om", "cli.om", "mio.om", "noserve.om", "nogpu.om", "apu_fabric_macos.om",
441 ]
442 body = []
443 for name in parts:
444 txt = read_text(os.path.join(SRC, name))
445 txt = txt.replace("fn main to int", "fn ocpumain to int")
446 body.append(txt)
447 body.append(MAC_SIM_SHIM)
448 body.append(read_text(os.path.join(GPU, "gm.om")))
449 body.append(DRIVER_MAIN)
450 return "target a64macos\nom2\n" + "".join(body)
451
452
453def build_gb10_source():
454 parts = [
455 os.path.join(SRC, "net", "http.om"),
456 os.path.join(SRC, "net", "json.om"),
457 os.path.join(SRC, "net", "jsonw.om"),
458 os.path.join(SRC, "math.om"),
459 os.path.join(SRC, "data.om"),
460 os.path.join(SRC, "lpool.om"),
461 os.path.join(SRC, "model.om"),
462 os.path.join(SRC, "adam.om"),
463 os.path.join(SRC, "ckpt.om"),
464 os.path.join(SRC, "bpe.om"),
465 os.path.join(SRC, "spec.om"),
466 os.path.join(SRC, "rev.om"),
467 os.path.join(SRC, "arboris.om"),
468 os.path.join(SRC, "sp_solve.om"),
469 os.path.join(SRC, "spiral.om"),
470 os.path.join(SRC, "apu_weave.om"),
471 os.path.join(SRC, "omg.om"),
472 os.path.join(SRC, "pillars_cli.om"),
473 os.path.join(SRC, "cli.om"),
474 os.path.join(SRC, "lio.om"),
475 os.path.join(SRC, "serve.om"),
476 os.path.join(GPU, "context.om"),
477 os.path.join(GPU, "vector.om"),
478 os.path.join(GPU, "launch.om"),
479 os.path.join(GPU, "batch.om"),
480 os.path.join(GPU, "gk.om"),
481 os.path.join(GPU, "gr.om"),
482 os.path.join(GPU, "gb.om"),
483 os.path.join(GPU, "gg.om"),
484 os.path.join(GPU, "gt.om"),
485 os.path.join(GPU, "gm.om"),
486 os.path.join(GPU, "ring.om"),
487 os.path.join(GPU, "ejit.om"),
488 os.path.join(SRC, "apu_fabric_linux.om"),
489 os.path.join(SRC, "apu_fabric_gb10.om"),
490 ]
491 return "om2\n" + "".join(read_text(p) for p in parts)
492
493
494def build_gb10_minimal_source():
495 parts = [
496 os.path.join(SRC, "math.om"),
497 os.path.join(SRC, "data.om"),
498 os.path.join(SRC, "lpool.om"),
499 os.path.join(SRC, "model.om"),
500 os.path.join(SRC, "adam.om"),
501 os.path.join(SRC, "ckpt.om"),
502 os.path.join(SRC, "bpe.om"),
503 os.path.join(SRC, "spec.om"),
504 os.path.join(SRC, "rev.om"),
505 os.path.join(SRC, "arboris.om"),
506 os.path.join(SRC, "sp_solve.om"),
507 os.path.join(SRC, "spiral.om"),
508 os.path.join(SRC, "apu_weave.om"),
509 os.path.join(SRC, "omg.om"),
510 os.path.join(SRC, "pillars_cli.om"),
511 os.path.join(SRC, "cli.om"),
512 os.path.join(SRC, "lio.om"),
513 os.path.join(SRC, "noserve.om"),
514 os.path.join(GPU, "context.om"),
515 os.path.join(GPU, "vector.om"),
516 os.path.join(GPU, "launch.om"),
517 os.path.join(GPU, "batch.om"),
518 os.path.join(GPU, "gk.om"),
519 os.path.join(GPU, "gr.om"),
520 os.path.join(GPU, "gb.om"),
521 os.path.join(GPU, "gg.om"),
522 os.path.join(GPU, "gt.om"),
523 os.path.join(GPU, "gm.om"),
524 os.path.join(GPU, "ring.om"),
525 os.path.join(GPU, "ejit.om"),
526 os.path.join(SRC, "apu_fabric_linux.om"),
527 os.path.join(SRC, "apu_fabric_gb10.om"),
528 ]
529 return "om2\n" + "".join(read_text(p) for p in parts)
530
531
532def max_gpr_in_sass(sass_text):
533 mx = -1
534 for line in sass_text.splitlines():
535 m = re.search(r"/\*[0-9a-f]+\*/\s*(.*)", line)
536 if not m:
537 continue
538 rhs = re.sub(r";.*", "", m.group(1)).strip()
539 if rhs.startswith("@"):
540 parts = rhs.split(None, 1)
541 rhs = parts[1] if len(parts) > 1 else ""
542 parts = rhs.split(None, 1)
543 op = parts[0] if parts else ""
544 rest = parts[1] if len(parts) > 1 else ""
545 w = 1
546 if ".128" in op:
547 w = 4
548 elif ".64" in op or ".WIDE" in op:
549 w = 2
550 # Bracketed address operands have width 0 extension unless .64
551 for br in re.findall(r"\[[^\]]*\]", rest):
552 for rm in re.finditer(r"(?<![A-Za-z0-9_.])R(\d+)(\.64)?", br):
553 ext = 1 if rm.group(2) else 0
554 mx = max(mx, int(rm.group(1)) + ext)
555 no_br = re.sub(r"\[[^\]]*\]", " ", rest)
556 for rm in re.finditer(r"(?<![A-Za-z0-9_.])R(\d+)(\.64)?", no_br):
557 ext = 1 if rm.group(2) else w - 1
558 mx = max(mx, int(rm.group(1)) + ext)
559 return mx
560
561
562def run_nvdisasm(code_bytes):
563 local_nv = shutil.which("nvdisasm") or "/usr/local/cuda/bin/nvdisasm"
564 if os.path.isfile(local_nv) and os.access(local_nv, os.X_OK):
565 with tempfile.NamedTemporaryFile(suffix=".bin") as tf:
566 tf.write(code_bytes)
567 tf.flush()
568 p = subprocess.run([local_nv, "-b", "SM121", tf.name],
569 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
570 return "local", p.returncode, p.stdout.decode("utf-8", errors="replace"), p.stderr.decode("utf-8", errors="replace")
571 if shutil.which("ssh"):
572 p = subprocess.run(
573 [
574 "ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=5", "spark",
575 "tmp=$(mktemp /tmp/gm_disasm.XXXXXX) && cat > \"$tmp\" && /usr/local/cuda/bin/nvdisasm -b SM121 \"$tmp\"; rc=$?; rm -f \"$tmp\"; exit $rc",
576 ],
577 input=code_bytes,
578 stdout=subprocess.PIPE,
579 stderr=subprocess.PIPE,
580 )
581 return "spark-ssh", p.returncode, p.stdout.decode("utf-8", errors="replace"), p.stderr.decode("utf-8", errors="replace")
582 return None, None, "", "nvdisasm unavailable"
583
584
585def main():
586 omc = find_omc()
587 print(f"Using omc: {omc}")
588
589 # 1. Compile gb10 full stack + gm.om and gb10 minimal stack + gm.om
590 rc, err, nbytes = compile_om_bytes(omc, build_gb10_source())
591 check(rc == 0 and nbytes > 0, "compile_gb10_full", f"rc={rc} bytes={nbytes} {err.strip()}")
592
593 rc_m, err_m, nbytes_m = compile_om_bytes(omc, build_gb10_minimal_source())
594 check(rc_m == 0 and nbytes_m > 0, "compile_gb10_noserve", f"rc={rc_m} bytes={nbytes_m} {err_m.strip()}")
595
596 # 2. Compile and run macos target on Darwin (Linux omc only supports Linux targets)
597 if platform.system() != "Darwin":
598 print("Non-macOS host: skipping target a64macos compile/execution.")
599 return 0 if not FAILS else 1
600
601 with tempfile.TemporaryDirectory() as td:
602 bin_path = os.path.join(td, "gm_test")
603 rc_mac, err_mac, nbytes_mac = compile_om_bytes(omc, build_macos_source(), bin_path)
604 check(rc_mac == 0 and nbytes_mac > 0, "compile_macos_a64", f"rc={rc_mac} bytes={nbytes_mac} {err_mac.strip()}")
605 if rc_mac != 0:
606 return 1
607
608 # 3. Built-in gm_selftest
609 p = subprocess.run([bin_path, "s"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
610 check(p.returncode == 0, "gm_selftest", f"rc={p.returncode} out={p.stdout.decode().strip()}")
611
612 # 4. Emitter metadata & double-buffer checks
613 p = subprocess.run([bin_path, "d"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
614 check(p.returncode == 0, "gm_emit_stats_run", f"rc={p.returncode}")
615 b0, b1, ins0, max_gpr, decl_gpr, smem_b, nested_bssy = [int(x) for x in p.stdout.decode().split()]
616 check(0 < b0 <= 16384 and b0 == b1, "single_slot_fit_double_buf", f"b0={b0} b1={b1} insns={ins0}")
617 check(max_gpr <= 61 and decl_gpr >= max_gpr + 3, "gpr_headroom", f"max_gpr=R{max_gpr} decl={decl_gpr}")
618 check(nested_bssy == 0, "zero_nested_bssy", f"nested_bssy={nested_bssy}")
619 check(smem_b == 4608, "smem_bank_padded_layout", f"smem_bytes={smem_b}")
620
621 # 5. Extract slot 0 and slot 1 bytes, check sha256 parity
622 p_s0 = subprocess.run([bin_path, "b", "0"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
623 p_s1 = subprocess.run([bin_path, "b", "1"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
624 check(
625 p_s0.returncode == 0 and p_s1.returncode == 0 and len(p_s0.stdout) == b0
626 and hashlib.sha256(p_s0.stdout).hexdigest() == hashlib.sha256(p_s1.stdout).hexdigest(),
627 "double_buffer_code_parity",
628 f"sha256={hashlib.sha256(p_s0.stdout).hexdigest()[:16]}",
629 )
630
631 # 6. Spark nvdisasm -b SM121 verification (CPU-only, no GPU)
632 mode, d_rc, sass, d_err = run_nvdisasm(p_s0.stdout)
633 if mode is not None and d_rc == 0:
634 has_illegal = bool(re.search(r"illegal|unknown", sass, re.IGNORECASE))
635 check(not has_illegal, f"nvdisasm_sm121_clean ({mode})", f"insns={ins0}")
636 req_insns = [
637 "LDCU.64 UR4",
638 "LDG.E.MMIO.GPU",
639 "MEMBAR.SC.SYS",
640 "STG.E.STRONG.SYS",
641 "SHFL.BFLY",
642 "MUFU.RSQ",
643 "MUFU.EX2",
644 "MUFU.LG2",
645 "BAR.SYNC.DEFER_BLOCKING",
646 "LDS R34, [R48+URZ]",
647 "LDS R35, [R48+URZ+0x90]",
648 "BRA 0x270",
649 "EXIT",
650 ]
651 missing = [tok for tok in req_insns if tok not in sass]
652 check(not missing, "nvdisasm_sm121_required_ops", f"missing={missing}")
653 has_fp_atom = bool(re.search(r"\bATOM[GS]?\b|\bRED[GS]?\b", sass))
654 check(not has_fp_atom, "nvdisasm_sm121_no_atomics", f"insns={ins0}")
655 dis_max_gpr = max_gpr_in_sass(sass)
656 check(
657 0 <= dis_max_gpr <= 61 and decl_gpr >= dis_max_gpr + 3,
658 "nvdisasm_gpr_headroom",
659 f"dis_max=R{dis_max_gpr} need<={dis_max_gpr+3} decl={decl_gpr}",
660 )
661 else:
662 print(f"SKIP nvdisasm_sm121 ({mode}: rc={d_rc} {d_err.strip()})")
663
664 # 7. Launch-count=1, double-buffer swap, and negative boundary checks
665 p_ln = subprocess.run([bin_path, "l"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
666 check(p_ln.returncode == 0, "launch_persistent_and_bounds", p_ln.stdout.decode().strip())
667 ln_toks = p_ln.stdout.decode().split()
668 check(
669 ln_toks[0] == "LN" and int(ln_toks[1]) == 1 and int(ln_toks[2]) == 61
670 and int(ln_toks[3]) == 0 and int(ln_toks[4]) == 60
671 and int(ln_toks[5]) == 1 and int(ln_toks[6]) == 8 and int(ln_toks[7]) == 16 and int(ln_toks[8]) == 2,
672 "swap_buf_and_single_launch",
673 " ".join(ln_toks),
674 )
675
676 # 8. Parity test with synthetic in-memory batch
677 p_ps = subprocess.run([bin_path, "p"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
678 check(p_ps.returncode == 0, "sim_parity_synth_run", p_ps.stdout.decode().strip())
679 pt = p_ps.stdout.decode().split()
680 check(
681 pt[0] == "PAR" and int(pt[1]) == 0 and int(pt[2]) == 1 and int(pt[3]) == 6
682 and int(pt[7]) == 0 and int(pt[8]) == 6 and pt[9] == pt[10]
683 and int(pt[12]) < int(pt[11]) and int(pt[13]) <= 8388608,
684 "sim_parity_synth_bit_exact",
685 f"diff={pt[1]} launches={pt[2]} loss0={pt[11]} loss5={pt[12]} l2_bytes={pt[13]}",
686 )
687
688 # 9. Parity test with real odopen dataset file
689 ds_path = os.path.join(td, "train.bin")
690 # Deterministic byte corpus (> T + 1 tokens, V=256)
691 corpus = bytes(((i * 37 + 13) % 256) for i in range(512))
692 with open(ds_path, "wb") as f:
693 f.write(corpus)
694 p_pf = subprocess.run([bin_path, "p", ds_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
695 check(p_pf.returncode == 0, "sim_parity_odopen_run", p_pf.stdout.decode().strip())
696 pf = p_pf.stdout.decode().split()
697 check(
698 pf[0] == "PAR" and int(pf[1]) == 0 and int(pf[2]) == 1 and int(pf[3]) == 6
699 and int(pf[8]) == 6 and pf[9] == pf[10] and int(pf[12]) < int(pf[11]),
700 "sim_parity_odopen_bit_exact",
701 f"diff={pf[1]} launches={pf[2]} loss0={pf[11]} loss5={pf[12]}",
702 )
703
704 # 10. Byte-Traceability Lock 1: FP atomic audit + negative control + fixed/tree reductions
705 p_l1 = subprocess.run([bin_path, "r"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
706 check(p_l1.returncode == 0, "lock1_audit_and_reduction_run", p_l1.stdout.decode().strip())
707 lt = p_l1.stdout.decode().split()
708 check(
709 len(lt) == 14 and lt[0] == "LOCK1"
710 and int(lt[1]) == 1 and int(lt[2]) == 1
711 and int(lt[3]) == 1 and int(lt[4]) == 1 and int(lt[5]) == 1,
712 "lock1_no_fp_atomics_and_neg_ctrl",
713 f"a0={lt[1]} a1={lt[2]} neg_ok={lt[3]} a1_post={lt[4]} launch_blocked={lt[5]}" if len(lt) >= 6 else str(lt),
714 )
715 check(
716 len(lt) == 14 and int(lt[6]) == int(lt[7]) == int(lt[8]),
717 "lock1_i64_fixed_perm_invariant",
718 f"qf={lt[6]} qr={lt[7]} qi={lt[8]}" if len(lt) >= 9 else str(lt),
719 )
720 check(
721 len(lt) == 14 and lt[9] == lt[10] == lt[11],
722 "lock1_f64_fixed_bit_identical",
723 f"ff={lt[9]} fr={lt[10]} fi={lt[11]}" if len(lt) >= 12 else str(lt),
724 )
725 if len(lt) == 14:
726 f_fixed = struct.unpack(">d", bytes.fromhex(lt[9].zfill(16)))[0]
727 t24 = struct.unpack(">d", bytes.fromhex(lt[12].zfill(16)))[0]
728 t19 = struct.unpack(">d", bytes.fromhex(lt[13].zfill(16)))[0]
729 check(
730 abs(f_fixed - 2.3764) < 1e-6 and abs(t24 - 2.3764) < 1e-9 and abs(t19 - 13.7511) < 1e-9,
731 "lock1_tree_f64_accuracy",
732 f"f_fixed={f_fixed:.10f} t24={t24:.10f} t19={t19:.10f}",
733 )
734
735 print(f"\nSUMMARY: passed={len(PASSES)} failed={len(FAILS)}")
736 return 0 if not FAILS else 1
737
738
739if __name__ == "__main__":
740 sys.exit(main())