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/aien-train/blob/main/tools/om_bundle_data.py # aien-train AIEN training programme: language-model history, GB10 constraints and the route to training on the project engine. Plans and runnable checks are distinguished. 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 `aien-train / tools / om_bundle_data.py` 1012 lines ยท 39728 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Audit local .om corpus, generate live omc refusal-repair pairs (errors 1..30), 3 and build deterministic, zero-leakage OLLM specialist bundle datasets (.tok + .msk). 4 5 Bundles: 6 - om-core: core .om language, stdlib, compiler, OLLM CPU, omc refusal-repair pairs 7 - gb20b-mmio: GB20B / Blackwell / GPU / CUDApp / GSP / SEC2 / MMIO / VFIO / KFD 8 - aienux-kernel: Aienux OS / ARM64/x86 EFI / boot / MMU / drivers (e.g. rtl8127) 9 - libos-rpc: LibosLog / RPC / HTTP / JSON / wire protocols / IPC / net 10 11 Zero machine-specific paths are hardcoded; override via CLI flags. 12 """ 13 14 from __future__ import annotations 15 16 import argparse 17 import hashlib 18 import json 19 import os 20 import re 21 import struct 22 import subprocess 23 import sys 24 import tempfile 25 from collections import defaultdict 26 from pathlib import Path 27 from typing import Dict, List, Optional, Tuple 28 29 T_CTX = 256 30 BUNDLES = ("om-core", "aienux-kernel", "gb20b-mmio", "libos-rpc") 31 32 # Merkle specialist chain hierarchy (parent -> child links; each child's OLLMSP01 33 # base_hash cryptographically pins its frozen prefix layers 0..freeze_layers-1). 34 CHAIN_TOPOLOGY = { 35 "om-core": { 36 "link_depth": 1, 37 "parent": "base", 38 "freeze_layers": 8, 39 "target_layers": 10, 40 "strand": "trunk", 41 "role": "Core .om syntax/stdlib/OLLM CPU + live omc refusal-repair pairs (errors 1..30)", 42 }, 43 "aienux-kernel": { 44 "link_depth": 2, 45 "parent": "om-core", 46 "freeze_layers": 10, 47 "target_layers": 12, 48 "strand": "trunk", 49 "role": "Aienux OS, ARM64/x86 UEFI, MMU/boot, bare-metal drivers", 50 }, 51 "gb20b-mmio": { 52 "link_depth": 3, 53 "parent": "aienux-kernel", 54 "freeze_layers": 12, 55 "target_layers": 14, 56 "strand": "branch-a", 57 "role": "GB20B / Blackwell GPU, GSP/SEC2, MMIO, CUDApp, VFIO/KFD", 58 }, 59 "libos-rpc": { 60 "link_depth": 3, 61 "parent": "aienux-kernel", 62 "freeze_layers": 12, 63 "target_layers": 14, 64 "strand": "branch-b", 65 "role": "LibosLog, GSP/host RPC, HTTP/JSON/TLS wire codecs, serve.om, IPC", 66 }, 67 } 68 69 CANONICAL_REPO_ORDER = ( 70 "omega-mv", 71 "aien-train", 72 "aienux-arm64-model", 73 "aienux-macbook", 74 "omega-arm64efi", 75 "omega-harness", 76 "rtl8127-omega", 77 "interplane-forge", 78 "ipl-hop", 79 "ggml-omega-macbook", 80 "astra-inference-cache", 81 "omega-bridge-macbook", 82 "si-plain-start", 83 "aien-train-voice-ui", 84 "interplane.io", 85 ) 86 87 SKIP_DIRS = {".git", "node_modules", "__pycache__", "target", "build", ".venv"} 88 89 NEGATIVE_FILE_RE = re.compile( 90 r"(^|/)(err\d{2}_|mistake_|.*-mut\d*\.om$|.*mutants\.om$|.*_bad\.om$|.*_fail\.om$)", 91 re.IGNORECASE, 92 ) 93 94 95 def sha256_bytes(data: bytes) -> str: 96 return hashlib.sha256(data).hexdigest() 97 98 99 def is_negative_control(rel_path: str) -> bool: 100 p = rel_path.lower() 101 if "/controls/" in p and ("mut" in p or "e13" in p or "bad" in p): 102 return True 103 return bool(NEGATIVE_FILE_RE.search(p)) 104 105 106 def classify_domain(repo: str, rel_path: str, head_lower: str) -> Tuple[str, str]: 107 """Return (bundle_name, audit_category). 108 109 audit_category separates OLLM CPU from general om-core for reporting, 110 while bundle_name maps every file to one of the 4 specialist bundles. 111 """ 112 p = rel_path.lower() 113 114 # 1. GB20B / GPU / MMIO / CUDApp / GSP / SEC2 115 if ( 116 "/gpu/" in p 117 or any( 118 k in p 119 for k in ( 120 "gb20", 121 "blackwell", 122 "cudapp", 123 "nvrm", 124 "gsp", 125 "sec2", 126 "mmio", 127 "vfio", 128 "kfd", 129 "uvm", 130 ) 131 ) 132 or ( 133 "omegallm/gpu/" in p 134 or any( 135 p.endswith(s) 136 for s in ( 137 "/gg.om", 138 "/gk.om", 139 "/gr.om", 140 "/gb.om", 141 "/launch.om", 142 "/vector.om", 143 "/context.om", 144 "/batch.om", 145 ) 146 ) 147 ) 148 ): 149 return "gb20b-mmio", "gb20b-mmio" 150 151 if any( 152 w in head_lower 153 for w in ("devctl ", "devcall ", "uvmctl ", "vfioctl ", "mapget ", "mapset ", "kfdctl ") 154 ): 155 return "gb20b-mmio", "gb20b-mmio" 156 157 # 2. LibosLog / RPC / net / HTTP / JSON / wire / IPC 158 if any( 159 k in p 160 for k in ( 161 "libos", 162 "rpc", 163 "/net/", 164 "http", 165 "json", 166 "wire", 167 "serve.om", 168 "ipc", 169 "proto", 170 "sock", 171 "tls-", 172 ) 173 ): 174 return "libos-rpc", "libos-rpc" 175 176 # 3. Aienux kernel / EFI / MMU / bare-metal drivers (excluding benchmark kernels/) 177 if ( 178 repo in ("aienux-arm64-model", "aienux-macbook", "omega-arm64efi", "rtl8127-omega") 179 or any(k in p for k in ("aienux", "mmu", "a64efi", "x86efi", "efirt", "pagetable", "rtl8127")) 180 or ("target a64efi" in head_lower or "target x86efi" in head_lower) 181 ): 182 return "aienux-kernel", "aienux-kernel" 183 184 # 4. OLLM CPU / native trainer (audited separately, bundled into om-core) 185 if ( 186 "omegallm" in p 187 or repo in ("aien-train", "aien-train-macbook", "ggml-omega-macbook", "astra-inference-cache") 188 ): 189 return "om-core", "ollm" 190 191 return "om-core", "om-core" 192 193 194 def scan_workspace(workspace: Path) -> dict: 195 """Scan all .om files under workspace, deduplicating by SHA-256 content hash.""" 196 if not workspace.is_dir(): 197 raise FileNotFoundError(f"Workspace not found: {workspace}") 198 199 entries = sorted( 200 d for d in os.listdir(workspace) if not d.startswith(".") and (workspace / d).is_dir() 201 ) 202 ordered_repos = [r for r in CANONICAL_REPO_ORDER if r in entries] 203 ordered_repos += [r for r in entries if r not in ordered_repos] 204 205 by_repo = defaultdict(lambda: {"files": 0, "loc": 0, "bytes": 0}) 206 by_category = defaultdict(lambda: {"files": 0, "loc": 0, "bytes": 0, "clean_files": 0, "clean_loc": 0}) 207 by_bundle = defaultdict(lambda: {"files": 0, "loc": 0, "bytes": 0, "clean_files": 0, "clean_loc": 0}) 208 209 seen_hashes: Dict[str, dict] = {} 210 total_files = total_loc = total_bytes = dup_files = 0 211 212 for repo in ordered_repos: 213 rpath = workspace / repo 214 for dirpath, dirnames, filenames in os.walk(rpath): 215 dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIRS) 216 for fn in sorted(filenames): 217 if not fn.endswith(".om"): 218 continue 219 fpath = Path(dirpath) / fn 220 if fpath.is_symlink(): 221 continue 222 try: 223 data = fpath.read_bytes() 224 except OSError: 225 continue 226 loc = data.count(b"\n") + (1 if data and not data.endswith(b"\n") else 0) 227 nbytes = len(data) 228 total_files += 1 229 total_loc += loc 230 total_bytes += nbytes 231 by_repo[repo]["files"] += 1 232 by_repo[repo]["loc"] += loc 233 by_repo[repo]["bytes"] += nbytes 234 235 h = sha256_bytes(data) 236 if h in seen_hashes: 237 dup_files += 1 238 continue 239 240 rel = str(fpath.relative_to(workspace)) 241 head_lower = data[:8192].decode("latin1").lower() 242 bundle, cat = classify_domain(repo, rel, head_lower) 243 neg = is_negative_control(rel) 244 245 rec = { 246 "sha256": h, 247 "repo": repo, 248 "rel": rel, 249 "path": str(fpath), 250 "loc": loc, 251 "bytes": nbytes, 252 "bundle": bundle, 253 "category": cat, 254 "negative_control": neg, 255 } 256 seen_hashes[h] = rec 257 258 by_category[cat]["files"] += 1 259 by_category[cat]["loc"] += loc 260 by_category[cat]["bytes"] += nbytes 261 by_bundle[bundle]["files"] += 1 262 by_bundle[bundle]["loc"] += loc 263 by_bundle[bundle]["bytes"] += nbytes 264 if not neg: 265 by_category[cat]["clean_files"] += 1 266 by_category[cat]["clean_loc"] += loc 267 by_bundle[bundle]["clean_files"] += 1 268 by_bundle[bundle]["clean_loc"] += loc 269 270 unique_recs = list(seen_hashes.values()) 271 return { 272 "total_all_dirs": { 273 "files": total_files, 274 "loc": total_loc, 275 "bytes": total_bytes, 276 "duplicates": dup_files, 277 }, 278 "unique_dedup": { 279 "files": len(unique_recs), 280 "loc": sum(r["loc"] for r in unique_recs), 281 "bytes": sum(r["bytes"] for r in unique_recs), 282 "clean_files": sum(1 for r in unique_recs if not r["negative_control"]), 283 "clean_loc": sum(r["loc"] for r in unique_recs if not r["negative_control"]), 284 }, 285 "by_repo": dict(sorted(by_repo.items(), key=lambda kv: -kv[1]["loc"])), 286 "by_category": dict(by_category), 287 "by_bundle": dict(by_bundle), 288 "records": unique_recs, 289 } 290 291 292 def refusal_specs(include_err24: bool = False) -> List[dict]: 293 """Controlled defective/repaired .om pairs spanning omc error codes 1..30 294 plus common out-of-distribution mistakes (infix, C calls, comments, etc.). 295 """ 296 specs: List[dict] = [ 297 { 298 "id": "err01_stdin_dir", 299 "code": 1, 300 "kind": "io", 301 "desc": "stdin read failed (directory passed as stdin)", 302 "bad": "fn main to int\nret 0\nend\n", 303 "good": "fn main to int\nret 0\nend\n", 304 "trigger": "stdin_dir", 305 }, 306 { 307 "id": "err02_stdout_ro", 308 "code": 2, 309 "kind": "io", 310 "desc": "stdout write failed (read-only stdout descriptor)", 311 "bad": "fn main to int\nret 0\nend\n", 312 "good": "fn main to int\nret 0\nend\n", 313 "trigger": "stdout_ro", 314 }, 315 { 316 "id": "err03_unknown_name", 317 "code": 3, 318 "kind": "source", 319 "desc": "unknown variable name", 320 "bad": "fn main to int\nret foo\nend\n", 321 "good": "fn main to int\nfoo = int 0\nret foo\nend\n", 322 }, 323 { 324 "id": "err03_char_literal", 325 "code": 3, 326 "kind": "source", 327 "desc": "C char literal instead of uchar byte value", 328 "bad": "fn main to int\nc = 'A'\nret int c\nend\n", 329 "good": "fn main to int\nc = uchar 65\nret int c\nend\n", 330 }, 331 { 332 "id": "err03_rotr_without_om2", 333 "code": 3, 334 "kind": "source", 335 "desc": "rotr used without om2 header", 336 "bad": "fn main to int\nx = rotr uint 1 1\nret int x\nend\n", 337 "good": "om2\nfn main to int\nx = rotr uint 1 1\nret int x\nend\n", 338 }, 339 { 340 "id": "err04_line_ends_early", 341 "code": 4, 342 "kind": "source", 343 "desc": "missing operand in prefix add", 344 "bad": "fn main to int\nx = add int 1\nret x\nend\n", 345 "good": "fn main to int\nx = add int 1 2\nret x\nend\n", 346 }, 347 { 348 "id": "err05_extra_words", 349 "code": 5, 350 "kind": "source", 351 "desc": "extra trailing token on line", 352 "bad": "fn main to int\nx = int 1 2\nret x\nend\n", 353 "good": "fn main to int\nx = int 1\nret x\nend\n", 354 }, 355 { 356 "id": "err05_infix_plus", 357 "code": 5, 358 "kind": "source", 359 "desc": "infix x + 1 instead of prefix add x 1", 360 "bad": "fn main to int\nx = int 1\ny = x + 1\nret y\nend\n", 361 "good": "fn main to int\nx = int 1\ny = add x 1\nret y\nend\n", 362 }, 363 { 364 "id": "err05_else_if", 365 "code": 5, 366 "kind": "source", 367 "desc": "else if on one line instead of nested if inside else", 368 "bad": "fn main to int\nx = int 1\nif eq x 0\nret 0\nelse if eq x 1\nret 1\nend\nret 2\nend\n", 369 "good": "fn main to int\nx = int 1\nif eq x 0\nret 0\nelse\nif eq x 1\nret 1\nend\nend\nret 2\nend\n", 370 }, 371 { 372 "id": "err06_semicolon", 373 "code": 6, 374 "kind": "source", 375 "desc": "trailing semicolon on number literal", 376 "bad": "fn main to int\nx = int 1;\nret x\nend\n", 377 "good": "fn main to int\nx = int 1\nret x\nend\n", 378 }, 379 { 380 "id": "err06_upper_hex", 381 "code": 6, 382 "kind": "source", 383 "desc": "uppercase hex literal in om2", 384 "bad": "om2\nfn main to int\nx = uint 0xFF\nret int x\nend\n", 385 "good": "om2\nfn main to int\nx = uint 0xff\nret int x\nend\n", 386 }, 387 { 388 "id": "err07_type_mismatch", 389 "code": 7, 390 "kind": "source", 391 "desc": "implicit int + ulong mismatch without explicit cast", 392 "bad": "fn main to int\na = int 1\nb = ulong 2\nret add a b\nend\n", 393 "good": "fn main to int\na = int 1\nb = ulong 2\nret add a int b\nend\n", 394 }, 395 { 396 "id": "err07_value_as_stmt", 397 "code": 7, 398 "kind": "source", 399 "desc": "non-void function called as bare statement", 400 "bad": "fn f x int to int\nret add x 1\nend\nfn main to int\nf 1\nret 0\nend\n", 401 "good": "fn f x int to int\nret add x 1\nend\nfn main to int\nv = f 1\nret v\nend\n", 402 }, 403 { 404 "id": "err08_out_of_range", 405 "code": 8, 406 "kind": "source", 407 "desc": "uchar literal exceeds 255", 408 "bad": "fn main to int\nx = uchar 300\nret int x\nend\n", 409 "good": "fn main to int\nx = uchar 255\nret int x\nend\n", 410 }, 411 { 412 "id": "err08_bound_zero", 413 "code": 8, 414 "kind": "source", 415 "desc": "while loop bound 0 is out of range", 416 "bad": "fn main to int\nwhile false bound 0\nend\nret 0\nend\n", 417 "good": "fn main to int\nwhile false bound 1\nend\nret 0\nend\n", 418 }, 419 { 420 "id": "err09_free_disallowed", 421 "code": 9, 422 "kind": "source", 423 "desc": "free is refused (no heap in Omega)", 424 "bad": "fn main to int\na = new uchar 4 0\nfree a\nret 0\nend\n", 425 "good": "fn main to int\na = new uchar 4 0\nret int get a 0\nend\n", 426 }, 427 { 428 "id": "err09_main_params", 429 "code": 9, 430 "kind": "source", 431 "desc": "fn main cannot take parameters (use argcnt/argread)", 432 "bad": "fn main argc int to int\nret argc\nend\n", 433 "good": "fn main to int\nn = argcnt\nret int n\nend\n", 434 }, 435 { 436 "id": "err10_duplicate_fn", 437 "code": 10, 438 "kind": "source", 439 "desc": "duplicate function name", 440 "bad": "fn main to int\nret 0\nend\nfn main to int\nret 1\nend\n", 441 "good": "fn helper to int\nret 1\nend\nfn main to int\nret helper\nend\n", 442 }, 443 { 444 "id": "err11_ambiguous_bare_number", 445 "code": 11, 446 "kind": "source", 447 "desc": "bare untyped integer literal on new variable", 448 "bad": "fn main to int\nx = 5\nret x\nend\n", 449 "good": "fn main to int\nx = int 5\nret x\nend\n", 450 }, 451 { 452 "id": "err12_register_pool", 453 "code": 12, 454 "kind": "source", 455 "desc": "more than 16 live registers in one function", 456 "bad": "fn main to int\n" + "".join(f"v{i} = int {i}\n" for i in range(18)) + "ret v0\nend\n", 457 "good": "fn main to int\ns = int 0\nfor i int 18\ns = add s i\nend\nret s\nend\n", 458 }, 459 { 460 "id": "err13_name_too_long", 461 "code": 13, 462 "kind": "source", 463 "desc": "identifier exceeds 63-byte limit", 464 "bad": "fn main to int\n" + ("a" * 64) + " = int 1\nret 0\nend\n", 465 "good": "fn main to int\nval = int 1\nret val\nend\n", 466 }, 467 { 468 "id": "err14_export_capacity", 469 "code": 14, 470 "kind": "source", 471 "desc": "more than 32 export fn entries in om2 unit", 472 "bad": "om2\n" + "".join(f"export fn f{i} to int\nret {i}\nend\n" for i in range(33)), 473 "good": "om2\nexport fn f0 to int\nret 0\nend\n", 474 }, 475 { 476 "id": "err15_missing_end", 477 "code": 15, 478 "kind": "source", 479 "desc": "unclosed block missing end", 480 "bad": "fn main to int\nif true\nret 0\nend\n", 481 "good": "fn main to int\nif true\nret 0\nend\nret 1\nend\n", 482 }, 483 { 484 "id": "err16_reserved_name", 485 "code": 16, 486 "kind": "source", 487 "desc": "reserved keyword len used as variable name", 488 "bad": "fn main to int\nlen = int 1\nret 0\nend\n", 489 "good": "fn main to int\nn = int 1\nret n\nend\n", 490 }, 491 { 492 "id": "err17_after_ret", 493 "code": 17, 494 "kind": "source", 495 "desc": "unreachable statement after ret", 496 "bad": "fn main to int\nret 0\nx = int 1\nend\n", 497 "good": "fn main to int\nx = int 1\nret x\nend\n", 498 }, 499 { 500 "id": "err18_missing_ret", 501 "code": 18, 502 "kind": "source", 503 "desc": "non-void function missing ret (also catches silent return x typo)", 504 "bad": "fn main to int\nx = int 1\nreturn x\nend\n", 505 "good": "fn main to int\nx = int 1\nret x\nend\n", 506 }, 507 { 508 "id": "err19_global_arg", 509 "code": 19, 510 "kind": "source", 511 "desc": "global array passed as function argument", 512 "bad": "global g uchar 4\nfn f a view uchar 4 to int\nret int get a 0\nend\nfn main to int\nret f g\nend\n", 513 "good": "global g uchar 4\nfn f to int\nret int get g 0\nend\nfn main to int\nret f\nend\n", 514 }, 515 { 516 "id": "err20_readonly_text", 517 "code": 20, 518 "kind": "source", 519 "desc": "put into read-only text array", 520 "bad": "text s \"hi\"\nfn main to int\nput s 0 uchar 65\nret 0\nend\n", 521 "good": "fn main to int\ns = new uchar 2 0\nput s 0 uchar 65\nret int get s 0\nend\n", 522 }, 523 { 524 "id": "err21_const_index_oob", 525 "code": 21, 526 "kind": "source", 527 "desc": "constant array index out of bounds", 528 "bad": "fn main to int\na = new uchar 4 0\nret int get a 4\nend\n", 529 "good": "fn main to int\na = new uchar 4 0\nret int get a 3\nend\n", 530 }, 531 { 532 "id": "err22_bad_text_escape", 533 "code": 22, 534 "kind": "source", 535 "desc": "unsupported escape sequence in text literal", 536 "bad": "text s \"bad\\x\"\nfn main to int\nret 0\nend\n", 537 "good": "text s \"ok\\n\"\nfn main to int\nret 0\nend\n", 538 }, 539 { 540 "id": "err23_size_capacity", 541 "code": 23, 542 "kind": "source", 543 "desc": "global array exceeds `16777216`-element limit", 544 "bad": "global big uchar `16777217`\nfn main to int\nret 0\nend\n", 545 "good": "global big uchar 1024\nfn main to int\nret 0\nend\n", 546 }, 547 { 548 "id": "err25_target_hostword", 549 "code": 25, 550 "kind": "source", 551 "desc": "Linux host word write used under target a64efi", 552 "bad": "target a64efi\ntext s \"a\"\nfn main to int\nk = write 1 s 0 1\nret 0\nend\n", 553 "good": "fn main to int\ntext_ok = int 0\nret text_ok\nend\n", 554 }, 555 { 556 "id": "err26_bad_memory_max", 557 "code": 26, 558 "kind": "env", 559 "desc": "malformed OMC_MEMORY_MAX environment variable", 560 "bad": "fn main to int\nret 0\nend\n", 561 "good": "fn main to int\nret 0\nend\n", 562 "env": {"OMC_MEMORY_MAX": "abc"}, 563 }, 564 { 565 "id": "err27_fresh_uninit_read", 566 "code": 27, 567 "kind": "source", 568 "desc": "OM-2 fresh scratch array read before write", 569 "bad": "om2\nfn f s edit uchar 4 fresh to int\nret int get s 0\nend\nfn main to int\na = new uchar 4 0\nret f edit a\nend\n", 570 "good": "om2\nfn f s edit uchar 4 fresh to int\nput s 0 uchar 1\nret int get s 0\nend\nfn main to int\na = new uchar 4 0\nret f edit a\nend\n", 571 }, 572 { 573 "id": "err28_seal_outside_ctor", 574 "code": 28, 575 "kind": "source", 576 "desc": "OM-2 abstract type sealed outside NAME+mk constructor", 577 "bad": "om2\nabstract Tok uint\nfn main to int\nt = seal Tok uint 1\nret int open t\nend\n", 578 "good": "om2\nabstract Tok uint\nfn Tokmk v uint to Tok\nret seal Tok v\nend\nfn main to int\nt = Tokmk uint 1\nret int open t\nend\n", 579 }, 580 { 581 "id": "err29_layout_after_fn", 582 "code": 29, 583 "kind": "source", 584 "desc": "OM-2 layout declared after first fn", 585 "bad": "om2\nfn main to int\nret 0\nend\nlayout Hdr 4\nfield x uint at 0 little\nend\n", 586 "good": "om2\nlayout Hdr 4\nfield x uint at 0 little\nend\nfn main to int\nret 0\nend\n", 587 }, 588 { 589 "id": "err30_impure_contract", 590 "code": 30, 591 "kind": "source", 592 "desc": "OM-2 requires clause calls a function (must be pure)", 593 "bad": "om2\nfn helper to bool\nret true\nend\nfn f x int to int\nrequires helper\nret x\nend\nfn main to int\nret f int 1\nend\n", 594 "good": "om2\nfn f x int to int\nrequires ge x 0\nret x\nend\nfn main to int\nret f int 1\nend\n", 595 }, 596 ] 597 598 if include_err24: 599 specs.append( 600 { 601 "id": "err24_branch_range", 602 "code": 24, 603 "kind": "generated", 604 "desc": "branch displacement > 1 MiB inside single loop (split into helper fn)", 605 "bad": ( 606 "fn main to int\nx = ulong 0\nc = true\nwhile c bound 1\n" 607 + ("x = add x 1\n" * 270000) 608 + "c = false\nend\nret int and x 1\nend\n" 609 ), 610 "bad_display": ( 611 "fn main to int\nx = ulong 0\nc = true\nwhile c bound 1\n" 612 "note 270000 repeated x = add x 1 lines (>1 MiB branch)\n" 613 "c = false\nend\nret int and x 1\nend\n" 614 ), 615 "good": ( 616 "fn step x ulong to ulong\nret add x 270000\nend\n" 617 "fn main to int\nx = step ulong 0\nret int and x 1\nend\n" 618 ), 619 } 620 ) 621 return specs 622 623 624 def compile_with_omc(omc: Path, src: str, trigger: Optional[str] = None, env_extra: Optional[dict] = None) -> Tuple[int, str]: 625 env = os.environ.copy() 626 if env_extra: 627 env.update(env_extra) 628 if trigger == "stdin_dir": 629 fd = os.open("/tmp", os.O_RDONLY) 630 try: 631 p = subprocess.run([str(omc)], stdin=fd, capture_output=True, env=env, timeout=15) 632 finally: 633 os.close(fd) 634 elif trigger == "stdout_ro": 635 fd = os.open("/dev/null", os.O_RDONLY) 636 try: 637 p = subprocess.run([str(omc)], input=src.encode("utf-8"), stdout=fd, stderr=subprocess.PIPE, env=env, timeout=15) 638 finally: 639 os.close(fd) 640 else: 641 p = subprocess.run([str(omc)], input=src.encode("utf-8"), capture_output=True, env=env, timeout=15) 642 return p.returncode, p.stderr.decode("utf-8", errors="replace").strip() 643 644 645 def generate_verified_refusals(omc: Path, include_err24: bool = False) -> List[dict]: 646 """Compile every refusal-repair spec against real omc and assert exact error code + valid fix.""" 647 results = [] 648 for sp in refusal_specs(include_err24=include_err24): 649 rc_bad, err_bad = compile_with_omc(omc, sp["bad"], trigger=sp.get("trigger"), env_extra=sp.get("env")) 650 if rc_bad != sp["code"]: 651 raise RuntimeError( 652 f"Refusal spec {sp['id']} expected rc={sp['code']}, got rc={rc_bad} stderr={err_bad!r}" 653 ) 654 rc_good, err_good = compile_with_omc(omc, sp["good"]) 655 if rc_good != 0: 656 raise RuntimeError( 657 f"Repair spec {sp['id']} failed to compile: rc={rc_good} stderr={err_good!r}" 658 ) 659 results.append( 660 { 661 "id": sp["id"], 662 "code": sp["code"], 663 "kind": sp["kind"], 664 "desc": sp["desc"], 665 "omc_stderr": err_bad, 666 "bad": sp.get("bad_display", sp["bad"]), 667 "good": sp["good"], 668 "sha256": sha256_bytes((sp["id"] + "\n" + sp["good"]).encode("utf-8")), 669 } 670 ) 671 return results 672 673 674 def extract_fn_examples(text: str, rel_path: str, max_examples: int = 8) -> List[Tuple[str, str]]: 675 """Extract (prompt, completion) pairs from clean .om source at fn boundaries.""" 676 lines = text.splitlines() 677 examples: List[Tuple[str, str]] = [] 678 i = 0 679 n = len(lines) 680 while i < n and len(examples) < max_examples: 681 line = lines[i] 682 if line.startswith("fn ") or line.startswith("export fn "): 683 # Include up to 2 preceding note lines as context 684 start = i 685 while start > 0 and i - start < 2 and lines[start - 1].startswith("note "): 686 start -= 1 687 prompt = f"note file {Path(rel_path).name}\n" + "\n".join(lines[start : i + 1]) + "\n" 688 # Scan until matching top-level end 689 depth = 1 690 j = i + 1 691 while j < n and depth > 0: 692 s = lines[j].strip() 693 if s.startswith(("if ", "while ", "for ")): 694 depth += 1 695 elif s == "end": 696 depth -= 1 697 j += 1 698 body = "\n".join(lines[i + 1 : j]) + "\n" 699 if 10 <= len(body) <= 700 and depth == 0: 700 examples.append((prompt, body)) 701 i = j 702 else: 703 i += 1 704 return examples 705 706 707 def is_held_out(content_sha256: str, held_mod: int = 10) -> bool: 708 """Deterministic split by SHA-256 hash: ~10% held-out, zero content leakage.""" 709 return (int(content_sha256[:8], 16) % held_mod) == 0 710 711 712 def encode_bpe_batch(ollm: Path, merges: Path, texts: List[str], vocab: int = 4096) -> List[List[int]]: 713 """Encode a list of UTF-8 strings with ollm bpeenc via a NUL-separated temp file.""" 714 if not texts: 715 return [] 716 with tempfile.TemporaryDirectory(prefix="om-bpe-") as tmp: 717 in_path = Path(tmp) / "in.txt" 718 out_path = Path(tmp) / "out.tok" 719 # Use NUL byte (token 0) as exact record separator 720 joined = b"\x00".join(t.replace("\x00", "").encode("utf-8", errors="ignore") for t in texts) 721 in_path.write_bytes(joined) 722 p = subprocess.run( 723 [str(ollm), "bpeenc", str(merges), str(vocab), str(in_path), str(out_path)], 724 capture_output=True, 725 text=True, 726 timeout=120, 727 ) 728 if p.returncode != 0: 729 raise RuntimeError(f"ollm bpeenc failed (rc={p.returncode}): {p.stderr}") 730 raw = out_path.read_bytes() 731 toks = list(struct.unpack("<" + "H" * (len(raw) // 2), raw)) 732 # Split on token 0 (NUL) 733 records: List[List[int]] = [] 734 cur: List[int] = [] 735 for t in toks: 736 if t == 0: 737 records.append(cur) 738 cur = [] 739 else: 740 cur.append(t) 741 records.append(cur) 742 if len(records) != len(texts): 743 raise RuntimeError(f"bpeenc record count mismatch: expected {len(texts)}, got {len(records)}") 744 return records 745 746 747 def pack_aligned_masked( 748 pairs: List[Tuple[str, str]], ollm: Path, merges: Path, ctx: int = T_CTX 749 ) -> Tuple[bytes, bytes, int, int]: 750 """Pack (prompt, completion) pairs into BOS-aligned ctx-token windows with 1-byte-per-token mask. 751 752 Mask byte = 0 on BOS, prompt, and padding tokens; 1 on completion tokens. 753 Appends 1 trailing 0 token + 0 mask byte so obrow(w * T) reads T+1 tokens cleanly. 754 """ 755 if not pairs: 756 return b"", b"", 0, 0 757 prompts = [p for p, _ in pairs] 758 comps = [c for _, c in pairs] 759 p_toks = encode_bpe_batch(ollm, merges, prompts) 760 c_toks = encode_bpe_batch(ollm, merges, comps) 761 762 blocks_t: List[List[int]] = [] 763 blocks_m: List[List[int]] = [] 764 blk_t: List[int] = [] 765 blk_m: List[int] = [] 766 used_examples = 0 767 768 for pt, ct in zip(p_toks, c_toks): 769 ex_t = [0] + pt + ct 770 ex_m = [0] + ([0] * len(pt)) + ([1] * len(ct)) 771 if len(ex_t) >= ctx or len(ct) == 0: 772 continue 773 used_examples += 1 774 if len(blk_t) + len(ex_t) > ctx: 775 pad = ctx - len(blk_t) 776 blk_t.extend([0] * pad) 777 blk_m.extend([0] * pad) 778 blocks_t.append(blk_t) 779 blocks_m.append(blk_m) 780 blk_t = list(ex_t) 781 blk_m = list(ex_m) 782 else: 783 blk_t.extend(ex_t) 784 blk_m.extend(ex_m) 785 786 if blk_t: 787 pad = ctx - len(blk_t) 788 blk_t.extend([0] * pad) 789 blk_m.extend([0] * pad) 790 blocks_t.append(blk_t) 791 blocks_m.append(blk_m) 792 793 flat_t: List[int] = [] 794 flat_m: List[int] = [] 795 for bt, bm in zip(blocks_t, blocks_m): 796 flat_t.extend(bt) 797 flat_m.extend(bm) 798 if flat_t: 799 flat_t.append(0) 800 flat_m.append(0) 801 802 tok_bytes = struct.pack("<" + "H" * len(flat_t), *flat_t) 803 msk_bytes = bytes(flat_m) 804 return tok_bytes, msk_bytes, len(blocks_t), used_examples 805 806 807 def cmd_audit(args: argparse.Namespace) -> int: 808 report = scan_workspace(Path(args.workspace).expanduser()) 809 print(f"Workspace: {args.workspace}") 810 t = report["total_all_dirs"] 811 u = report["unique_dedup"] 812 print(f"Total (.om across all dirs): {t['files']} files, {t['loc']} LOC, {t['bytes']} bytes (dups={t['duplicates']})") 813 print( 814 f"Unique (SHA-256 dedup): {u['files']} files, {u['loc']} LOC, {u['bytes']} bytes " 815 f"(clean positive: {u['clean_files']} files, {u['clean_loc']} LOC)" 816 ) 817 print("\nBy audit category (SHA-256 dedup):") 818 print(f"{'CATEGORY':16s} {'FILES':>6s} {'LOC':>9s} {'CLEAN_F':>8s} {'CLEAN_LOC':>10s}") 819 for cat in ("om-core", "ollm", "gb20b-mmio", "aienux-kernel", "libos-rpc"): 820 c = report["by_category"].get(cat, {"files": 0, "loc": 0, "clean_files": 0, "clean_loc": 0}) 821 print(f"{cat:16s} {c['files']:6d} {c['loc']:9d} {c['clean_files']:8d} {c['clean_loc']:10d}") 822 print("\nBy specialist bundle (SHA-256 dedup):") 823 print(f"{'BUNDLE':16s} {'FILES':>6s} {'LOC':>9s} {'CLEAN_F':>8s} {'CLEAN_LOC':>10s}") 824 for b in BUNDLES: 825 c = report["by_bundle"].get(b, {"files": 0, "loc": 0, "clean_files": 0, "clean_loc": 0}) 826 print(f"{b:16s} {c['files']:6d} {c['loc']:9d} {c['clean_files']:8d} {c['clean_loc']:10d}") 827 828 if args.json_out: 829 out_obj = {k: v for k, v in report.items() if k != "records"} 830 Path(args.json_out).write_text(json.dumps(out_obj, indent=2) + "\n") 831 print(f"\nWrote audit summary to {args.json_out}") 832 return 0 833 834 835 def cmd_refusals(args: argparse.Namespace) -> int: 836 omc = Path(args.omc).expanduser() 837 pairs = generate_verified_refusals(omc, include_err24=args.include_err24) 838 codes = sorted({p["code"] for p in pairs}) 839 print(f"Verified {len(pairs)} live omc refusal-repair pairs covering {len(codes)} error codes: {codes}") 840 if args.out: 841 out = Path(args.out) 842 out.parent.mkdir(parents=True, exist_ok=True) 843 with out.open("w", encoding="utf-8") as f: 844 for p in pairs: 845 f.write(json.dumps(p) + "\n") 846 print(f"Wrote {out}") 847 return 0 848 849 850 def cmd_build(args: argparse.Namespace) -> int: 851 workspace = Path(args.workspace).expanduser() 852 out_dir = Path(args.out_dir).expanduser() 853 out_dir.mkdir(parents=True, exist_ok=True) 854 omc = Path(args.omc).expanduser() 855 ollm = Path(args.ollm).expanduser() if args.ollm else None 856 merges = Path(args.merges).expanduser() if args.merges else None 857 base_ck = Path(args.base_ck).expanduser() if args.base_ck else None 858 859 report = scan_workspace(workspace) 860 refusals = generate_verified_refusals(omc, include_err24=args.include_err24) 861 862 summary = { 863 "chain_topology": CHAIN_TOPOLOGY, 864 "bundles": {}, 865 "refusal_pairs": len(refusals), 866 "refusal_codes": sorted({r["code"] for r in refusals}), 867 } 868 869 for bundle in BUNDLES: 870 train_pairs: List[Tuple[str, str]] = [] 871 held_pairs: List[Tuple[str, str]] = [] 872 train_hashes = set() 873 held_hashes = set() 874 875 recs = [r for r in report["records"] if r["bundle"] == bundle and not r["negative_control"]] 876 for r in recs: 877 try: 878 text = Path(r["path"]).read_text(encoding="utf-8", errors="ignore") 879 except OSError: 880 continue 881 exs = extract_fn_examples(text, r["rel"], max_examples=args.max_per_file) 882 if not exs: 883 continue 884 if is_held_out(r["sha256"]): 885 held_hashes.add(r["sha256"]) 886 held_pairs.extend(exs) 887 else: 888 train_hashes.add(r["sha256"]) 889 train_pairs.extend(exs) 890 891 # Mix live omc refusal-repair pairs into om-core (deterministically split) 892 if bundle == "om-core": 893 for rp in refusals: 894 prompt = ( 895 f"note fix omc refusal ({rp['omc_stderr']})\n" 896 f"note broken:\n{rp['bad']}note fixed:\n" 897 ) 898 comp = rp["good"] 899 if is_held_out(rp["sha256"]): 900 held_hashes.add(rp["sha256"]) 901 held_pairs.append((prompt, comp)) 902 else: 903 train_hashes.add(rp["sha256"]) 904 train_pairs.append((prompt, comp)) 905 906 # Assert zero content leakage between train and held-out 907 overlap = train_hashes.intersection(held_hashes) 908 if overlap: 909 raise AssertionError(f"Leakage detected in bundle {bundle}: {len(overlap)} overlapping hashes") 910 911 # Cap if requested for fast smoke builds 912 if args.max_examples > 0: 913 train_pairs = train_pairs[: args.max_examples] 914 held_pairs = held_pairs[: max(20, args.max_examples // 5)] 915 916 # Write JSONL splits 917 for split_name, split_pairs in (("train", train_pairs), ("held", held_pairs)): 918 jpath = out_dir / f"{bundle}_{split_name}.jsonl" 919 with jpath.open("w", encoding="utf-8") as f: 920 for pr, co in split_pairs: 921 f.write(json.dumps({"prompt": pr, "completion": co}) + "\n") 922 923 binfo = { 924 "link_depth": CHAIN_TOPOLOGY[bundle]["link_depth"], 925 "parent": CHAIN_TOPOLOGY[bundle]["parent"], 926 "freeze_layers": CHAIN_TOPOLOGY[bundle]["freeze_layers"], 927 "target_layers": CHAIN_TOPOLOGY[bundle]["target_layers"], 928 "strand": CHAIN_TOPOLOGY[bundle]["strand"], 929 "train_files": len(train_hashes), 930 "held_files": len(held_hashes), 931 "train_examples": len(train_pairs), 932 "held_examples": len(held_pairs), 933 "leakage_hashes": 0, 934 } 935 936 # Optional BPE tokenization + fcachem verification 937 if ollm and merges and ollm.is_file() and merges.is_file(): 938 tr_tok, tr_msk, tr_wins, tr_used = pack_aligned_masked(train_pairs, ollm, merges) 939 he_tok, he_msk, he_wins, he_used = pack_aligned_masked(held_pairs, ollm, merges) 940 tr_tok_p = out_dir / f"{bundle}_aligned.tok" 941 tr_msk_p = out_dir / f"{bundle}_aligned.msk" 942 he_tok_p = out_dir / f"{bundle}_held.tok" 943 he_msk_p = out_dir / f"{bundle}_held.msk" 944 tr_tok_p.write_bytes(tr_tok) 945 tr_msk_p.write_bytes(tr_msk) 946 he_tok_p.write_bytes(he_tok) 947 he_msk_p.write_bytes(he_msk) 948 binfo.update( 949 { 950 "train_windows": tr_wins, 951 "train_packed_examples": tr_used, 952 "held_windows": he_wins, 953 "held_packed_examples": he_used, 954 } 955 ) 956 if args.verify_fcachem and base_ck and base_ck.is_file() and tr_wins >= 1: 957 hc_path = out_dir / f"{bundle}_verify.hc" 958 w_check = min(2, tr_wins) 959 p = subprocess.run( 960 [str(ollm), "fcachem", str(base_ck), str(tr_tok_p), str(tr_msk_p), str(w_check), str(hc_path)], 961 capture_output=True, 962 text=True, 963 timeout=120, 964 ) 965 if p.returncode != 0: 966 raise RuntimeError(f"fcachem verification failed for {bundle} (rc={p.returncode}): {p.stderr}") 967 binfo["fcachem_verify"] = p.stdout.strip() 968 hc_path.unlink(missing_ok=True) 969 970 summary["bundles"][bundle] = binfo 971 print(f"[{bundle:14s}] {json.dumps(binfo)}") 972 973 manifest_path = out_dir / "manifest.json" 974 manifest_path.write_text(json.dumps(summary, indent=2) + "\n") 975 print(f"Wrote manifest to {manifest_path}") 976 return 0 977 978 979 def main() -> int: 980 ap = argparse.ArgumentParser(description="Build .om specialist bundle datasets and live omc refusal pairs.") 981 sub = ap.add_subparsers(dest="cmd", required=True) 982 983 pa = sub.add_parser("audit", help="Audit .om corpus across workspace") 984 pa.add_argument("--workspace", default=str(Path.home() / "workspace")) 985 pa.add_argument("--json-out", default="") 986 pa.set_defaults(func=cmd_audit) 987 988 pr = sub.add_parser("refusals", help="Generate live omc refusal-repair pairs (errors 1..30)") 989 pr.add_argument("--omc", default=str(Path.home() / ".local/bin/omc")) 990 pr.add_argument("--include-err24", action="store_true") 991 pr.add_argument("--out", default="") 992 pr.set_defaults(func=cmd_refusals) 993 994 pb = sub.add_parser("build", help="Build leak-free bundle splits, tokenize, and optionally verify fcachem") 995 pb.add_argument("--workspace", default=str(Path.home() / "workspace")) 996 pb.add_argument("--omc", default=str(Path.home() / ".local/bin/omc")) 997 pb.add_argument("--out-dir", required=True) 998 pb.add_argument("--ollm", default=str(Path.home() / ".local/bin/ollm")) 999 pb.add_argument("--merges", default=str(Path.home() / "workspace/aien-train-macbook/local-mac/merges4096.bin")) 1000 pb.add_argument("--base-ck", default=str(Path.home() / "workspace/aien-train-macbook/local-mac/omega-v2.ck")) 1001 pb.add_argument("--verify-fcachem", action="store_true") 1002 pb.add_argument("--include-err24", action="store_true") 1003 pb.add_argument("--max-per-file", type=int, default=6) 1004 pb.add_argument("--max-examples", type=int, default=0, help="0 = all; >0 caps examples per bundle") 1005 pb.set_defaults(func=cmd_build) 1006 1007 args = ap.parse_args() 1008 return args.func(args) 1009 1010 1011 if __name__ == "__main__": 1012 sys.exit(main())