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
aien-train / tests / omegallm / ollm_metrics_bench.py
| 1 | #!/usr/bin/env python3 |
| 2 | """One-command OLLM metrics & readiness benchmark suite. |
| 3 | |
| 4 | Measures and reports all host-verifiable OLLM metrics in structured JSON and a |
| 5 | clean Markdown summary table, while explicitly marking unrun hardware slots |
| 6 | (GB10 GPU, Aienux/GB20B) as NOT_RUN. |
| 7 | |
| 8 | Stdlib-only. Zero hardcoded machine paths. Does not touch any GPU. |
| 9 | """ |
| 10 | |
| 11 | from __future__ import annotations |
| 12 | |
| 13 | import argparse |
| 14 | import hashlib |
| 15 | import json |
| 16 | import os |
| 17 | import platform |
| 18 | import re |
| 19 | import shutil |
| 20 | import struct |
| 21 | import subprocess |
| 22 | import sys |
| 23 | import tempfile |
| 24 | import time |
| 25 | from pathlib import Path |
| 26 | from typing import Dict, List, Optional, Tuple |
| 27 | |
| 28 | |
| 29 | REPO_ROOT = Path(__file__).resolve().parents[2] |
| 30 | BPE_MAGIC = 3550332126946413647 |
| 31 | FNV_OFFSET = 14695981039346656037 |
| 32 | FNV_PRIME = 1099511628211 |
| 33 | |
| 34 | |
| 35 | def sha256_file(path: Path) -> str: |
| 36 | h = hashlib.sha256() |
| 37 | with path.open("rb") as f: |
| 38 | for chunk in iter(lambda: f.read(1 << 20), b""): |
| 39 | h.update(chunk) |
| 40 | return h.hexdigest() |
| 41 | |
| 42 | |
| 43 | def fnv1a64(data: bytes) -> int: |
| 44 | h = FNV_OFFSET |
| 45 | for b in data: |
| 46 | h = ((h ^ b) * FNV_PRIME) & 0xFFFFFFFFFFFFFFFF |
| 47 | return h |
| 48 | |
| 49 | |
| 50 | def write_synthetic_merges(path: Path) -> None: |
| 51 | """Write a minimal valid OLLM BPE merges file (V=258, 2 merges) for self-contained kvcmp.""" |
| 52 | payload = struct.pack("<HHHH", ord("t"), ord("h"), ord("i"), ord("n")) |
| 53 | h = fnv1a64(payload) |
| 54 | header = struct.pack("<QQQ", BPE_MAGIC, 258, h) |
| 55 | path.write_bytes(header + payload) |
| 56 | |
| 57 | |
| 58 | def write_synthetic_tokens(path: Path, n_tokens: int, seed: int = 1) -> None: |
| 59 | """Write deterministic u16 byte-range tokens (0..255) for small-model chain checks.""" |
| 60 | vals = [] |
| 61 | x = seed & 0xFFFFFFFF |
| 62 | for i in range(n_tokens): |
| 63 | if i % 16 == 0: |
| 64 | vals.append(0) |
| 65 | else: |
| 66 | x = (1664525 * x + 1013904223) & 0xFFFFFFFF |
| 67 | vals.append(32 + ((x >> 16) % 95)) |
| 68 | path.write_bytes(struct.pack("<" + "H" * len(vals), *vals)) |
| 69 | |
| 70 | |
| 71 | def find_omc(explicit: Optional[str]) -> Path: |
| 72 | if explicit: |
| 73 | p = Path(explicit).expanduser() |
| 74 | if p.is_file(): |
| 75 | return p |
| 76 | raise FileNotFoundError(f"omc not found at {p}") |
| 77 | cand = Path.home() / ".local/bin/omc" |
| 78 | if cand.is_file(): |
| 79 | return cand |
| 80 | found = shutil.which("omc") |
| 81 | if found: |
| 82 | return Path(found) |
| 83 | raise FileNotFoundError("omc not found; pass --omc PATH") |
| 84 | |
| 85 | |
| 86 | def concat_ollm_source(target: str, out_om: Path) -> None: |
| 87 | """Concatenate native/omegallm/*.om for darwin-arm64, linux-aarch64, or gb10.""" |
| 88 | src = REPO_ROOT / "native/omegallm" |
| 89 | core = [ |
| 90 | src / "math.om", |
| 91 | src / "data.om", |
| 92 | src / "lpool.om", |
| 93 | src / "model.om", |
| 94 | src / "adam.om", |
| 95 | src / "ckpt.om", |
| 96 | src / "bpe.om", |
| 97 | src / "spec.om", |
| 98 | src / "cli.om", |
| 99 | ] |
| 100 | parts: List[str] = [] |
| 101 | if target == "darwin-arm64": |
| 102 | parts.append("target a64macos\n") |
| 103 | files = core + [src / "mio.om", src / "noserve.om", src / "nogpu.om"] |
| 104 | elif target == "linux-aarch64": |
| 105 | parts.append("om2\n") |
| 106 | files = [src / "net/http.om", src / "net/json.om", src / "net/jsonw.om"] + core + [ |
| 107 | src / "lio.om", |
| 108 | src / "serve.om", |
| 109 | src / "nogpu.om", |
| 110 | ] |
| 111 | elif target == "gb10": |
| 112 | parts.append("om2\n") |
| 113 | files = [src / "net/http.om", src / "net/json.om", src / "net/jsonw.om"] + core + [ |
| 114 | src / "lio.om", |
| 115 | src / "serve.om", |
| 116 | ] |
| 117 | else: |
| 118 | raise ValueError(f"Unknown target: {target}") |
| 119 | |
| 120 | for fp in files: |
| 121 | parts.append(fp.read_text(encoding="utf-8")) |
| 122 | combined = "".join(parts) |
| 123 | |
| 124 | if target == "gb10": |
| 125 | matches = re.findall(r"^fn main to int$", combined, flags=re.MULTILINE) |
| 126 | if len(matches) != 1: |
| 127 | raise RuntimeError(f"Expected 1 fn main in gb10 concat, found {len(matches)}") |
| 128 | combined = re.sub(r"^fn main to int$", "fn ocpumain to int", combined, count=1, flags=re.MULTILINE) |
| 129 | g = src / "gpu" |
| 130 | for gp in ( |
| 131 | g / "context.om", |
| 132 | g / "vector.om", |
| 133 | g / "launch.om", |
| 134 | g / "batch.om", |
| 135 | g / "gk.om", |
| 136 | g / "gr.om", |
| 137 | g / "gb.om", |
| 138 | g / "gg.om", |
| 139 | ): |
| 140 | combined += gp.read_text(encoding="utf-8") |
| 141 | |
| 142 | out_om.write_text(combined, encoding="utf-8") |
| 143 | |
| 144 | |
| 145 | def run_cmd(cmd: List[str], timeout: int = 120, cwd: Optional[Path] = None) -> Tuple[int, bytes, bytes, float]: |
| 146 | t0 = time.perf_counter() |
| 147 | p = subprocess.run(cmd, capture_output=True, timeout=timeout, cwd=str(cwd) if cwd else None) |
| 148 | dt_ms = (time.perf_counter() - t0) * 1000.0 |
| 149 | return p.returncode, p.stdout, p.stderr, dt_ms |
| 150 | |
| 151 | |
| 152 | def compile_omc_file(omc: Path, src_om: Path, out_bin: Path) -> dict: |
| 153 | data = src_om.read_bytes() |
| 154 | t0 = time.perf_counter() |
| 155 | p = subprocess.run([str(omc)], input=data, capture_output=True, timeout=60) |
| 156 | dt_ms = (time.perf_counter() - t0) * 1000.0 |
| 157 | if p.returncode != 0: |
| 158 | return { |
| 159 | "status": "FAIL", |
| 160 | "rc": p.returncode, |
| 161 | "stderr": p.stderr.decode("utf-8", errors="replace").strip(), |
| 162 | "compile_ms": round(dt_ms, 2), |
| 163 | } |
| 164 | out_bin.write_bytes(p.stdout) |
| 165 | out_bin.chmod(0o755) |
| 166 | return { |
| 167 | "status": "PASS", |
| 168 | "rc": 0, |
| 169 | "compile_ms": round(dt_ms, 2), |
| 170 | "bytes": len(p.stdout), |
| 171 | "sha256": sha256_file(out_bin), |
| 172 | } |
| 173 | |
| 174 | |
| 175 | def parse_eval_line(out: str) -> Tuple[int, int, int, int]: |
| 176 | """Parse `E step W loss_micro bpb_micro`.""" |
| 177 | for line in reversed(out.strip().splitlines()): |
| 178 | parts = line.split() |
| 179 | if len(parts) >= 5 and parts[0] == "E": |
| 180 | return int(parts[1]), int(parts[2]), int(parts[3]), int(parts[4]) |
| 181 | raise RuntimeError(f"Could not parse E line from: {out!r}") |
| 182 | |
| 183 | |
| 184 | def section_gate_and_build(omc: Path, workdir: Path, explicit_ollm: Optional[str]) -> Tuple[dict, Path]: |
| 185 | rc_pr, out_pr, err_pr, ms_pr = run_cmd([sys.executable, str(REPO_ROOT / "tests/omegallm/pre-review.py")], cwd=REPO_ROOT) |
| 186 | pre_review = { |
| 187 | "status": "PASS" if rc_pr == 0 else "FAIL", |
| 188 | "rc": rc_pr, |
| 189 | "output": (out_pr.decode("utf-8", errors="replace").strip() or err_pr.decode("utf-8", errors="replace").strip()), |
| 190 | "ms": round(ms_pr, 2), |
| 191 | } |
| 192 | |
| 193 | builds: Dict[str, dict] = {} |
| 194 | darwin_bin: Optional[Path] = None |
| 195 | for target in ("darwin-arm64", "linux-aarch64", "gb10"): |
| 196 | om_path = workdir / f"ollm-{target}.om" |
| 197 | bin_path = workdir / f"ollm-{target}" |
| 198 | concat_ollm_source(target, om_path) |
| 199 | res = compile_omc_file(omc, om_path, bin_path) |
| 200 | builds[target] = res |
| 201 | if target == "darwin-arm64" and res["status"] == "PASS": |
| 202 | darwin_bin = bin_path |
| 203 | |
| 204 | if explicit_ollm: |
| 205 | ollm_bin = Path(explicit_ollm).expanduser() |
| 206 | if not ollm_bin.is_file(): |
| 207 | raise FileNotFoundError(f"--ollm-bin not found: {ollm_bin}") |
| 208 | elif darwin_bin is not None: |
| 209 | ollm_bin = darwin_bin |
| 210 | else: |
| 211 | raise RuntimeError("Failed to build darwin-arm64 ollm binary and no --ollm-bin supplied") |
| 212 | |
| 213 | return {"pre_review": pre_review, "builds": builds}, ollm_bin |
| 214 | |
| 215 | |
| 216 | def section_kv_cache(ollm: Path, workdir: Path) -> dict: |
| 217 | ck = workdir / "kv_l8.ck" |
| 218 | merges = workdir / "merges_258.bin" |
| 219 | write_synthetic_merges(merges) |
| 220 | rc, _, err, _ = run_cmd([str(ollm), "init", str(ck), "258", "32", "32", "2", "64", "8", "1", "7", "10", "1000"]) |
| 221 | if rc != 0: |
| 222 | raise RuntimeError(f"init kv_l8 failed rc={rc}: {err.decode('utf-8', errors='replace')}") |
| 223 | |
| 224 | n_steps = 20 |
| 225 | rc, out, err, wall_ms = run_cmd([str(ollm), "kvcmp", str(ck), str(n_steps), "hello world", str(merges)]) |
| 226 | text = out.decode("utf-8", errors="replace") |
| 227 | if rc != 0: |
| 228 | raise RuntimeError(f"kvcmp failed rc={rc}: {text} {err.decode('utf-8', errors='replace')}") |
| 229 | |
| 230 | m = re.search(r"KVCMP\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)", text) |
| 231 | if not m: |
| 232 | raise RuntimeError(f"Failed to parse KVCMP line: {text!r}") |
| 233 | n_got, ndiff, inc_ns, full_ns = (int(m.group(i)) for i in range(1, 5)) |
| 234 | inc_s = max(inc_ns, 1) / 1e9 |
| 235 | full_s = max(full_ns, 1) / 1e9 |
| 236 | return { |
| 237 | "status": "PASS" if ndiff == 0 else "FAIL", |
| 238 | "layers": 8, |
| 239 | "vocab": 258, |
| 240 | "steps": n_got, |
| 241 | "ndiff_logits": ndiff, |
| 242 | "inc_ms": round(inc_ns / 1e6, 3), |
| 243 | "full_ms": round(full_ns / 1e6, 3), |
| 244 | "inc_tok_per_s": round(n_got / inc_s, 1), |
| 245 | "full_tok_per_s": round(n_got / full_s, 1), |
| 246 | "speedup_x": round(full_ns / max(inc_ns, 1), 2), |
| 247 | "wall_ms": round(wall_ms, 2), |
| 248 | } |
| 249 | |
| 250 | |
| 251 | def section_chains_and_spclip(ollm: Path, workdir: Path) -> Tuple[dict, dict]: |
| 252 | base_ck = workdir / "base_l2.ck" |
| 253 | tr_tok = workdir / "chain_train.tok" |
| 254 | he_tok = workdir / "chain_held.tok" |
| 255 | write_synthetic_tokens(tr_tok, 16 * 12 + 1, seed=11) |
| 256 | write_synthetic_tokens(he_tok, 16 * 6 + 1, seed=29) |
| 257 | |
| 258 | rc, _, err, _ = run_cmd([str(ollm), "init", str(base_ck), "256", "16", "32", "2", "64", "2", "1", "42", "5", "5000"]) |
| 259 | if rc != 0: |
| 260 | raise RuntimeError(f"init base_l2 failed: {err.decode()}") |
| 261 | |
| 262 | _, out_b, _, _ = run_cmd([str(ollm), "eval", str(base_ck), str(he_tok), "4"]) |
| 263 | _, _, base_loss, _ = parse_eval_line(out_b.decode()) |
| 264 | |
| 265 | # Grow L2 -> L3 via growpro and verify step-0 bit-identity |
| 266 | l3_ck = workdir / "l3.ck" |
| 267 | rc, _, err, _ = run_cmd([str(ollm), "growpro", str(base_ck), str(l3_ck), "3", "5", "5000"]) |
| 268 | if rc != 0: |
| 269 | raise RuntimeError(f"growpro L2->3 failed: {err.decode()}") |
| 270 | _, out_g0, _, _ = run_cmd([str(ollm), "eval", str(l3_ck), str(he_tok), "4"]) |
| 271 | _, _, g0_loss, _ = parse_eval_line(out_g0.decode()) |
| 272 | growpro_delta_unats = g0_loss - base_loss |
| 273 | |
| 274 | # Train Link 1 (L2->3) and extract P1.sp |
| 275 | rc, _, err, _ = run_cmd([str(ollm), "trainf", str(l3_ck), str(tr_tok), "5", "5", "2", "1"]) |
| 276 | if rc != 0: |
| 277 | raise RuntimeError(f"trainf L2->3 failed: {err.decode()}") |
| 278 | p1_sp = workdir / "p1.sp" |
| 279 | rc, _, err, _ = run_cmd([str(ollm), "spext", str(base_ck), str(l3_ck), str(p1_sp)]) |
| 280 | if rc != 0: |
| 281 | raise RuntimeError(f"spext p1 failed: {err.decode()}") |
| 282 | |
| 283 | prefix_l3 = workdir / "prefix_l3.ck" |
| 284 | rc, _, err, _ = run_cmd([str(ollm), "spapp", str(base_ck), str(p1_sp), str(prefix_l3)]) |
| 285 | if rc != 0: |
| 286 | raise RuntimeError(f"spapp p1 failed: {err.decode()}") |
| 287 | |
| 288 | # Train 3 distinct Link-2 sibling branches (P2_a, P2_b, P2_c) pinned to base + P1 |
| 289 | branch_packs: List[Path] = [] |
| 290 | l4_a_ck = workdir / "l4_a.ck" |
| 291 | for idx, (tag, lr, steps) in enumerate([("a", "5000", "5"), ("b", "8000", "4"), ("c", "3000", "3")]): |
| 292 | ck4 = l4_a_ck if idx == 0 else workdir / f"l4_{tag}.ck" |
| 293 | sp4 = workdir / f"p2_{tag}.sp" |
| 294 | rc, _, err, _ = run_cmd([str(ollm), "growpro", str(prefix_l3), str(ck4), "4", steps, lr]) |
| 295 | if rc != 0: |
| 296 | raise RuntimeError(f"growpro L3->4 ({tag}) failed: {err.decode()}") |
| 297 | rc, _, err, _ = run_cmd([str(ollm), "trainf", str(ck4), str(tr_tok), steps, steps, "3", "1"]) |
| 298 | if rc != 0: |
| 299 | raise RuntimeError(f"trainf L3->4 ({tag}) failed: {err.decode()}") |
| 300 | rc, _, err, _ = run_cmd([str(ollm), "spext", str(prefix_l3), str(ck4), str(sp4)]) |
| 301 | if rc != 0: |
| 302 | raise RuntimeError(f"spext p2_{tag} failed: {err.decode()}") |
| 303 | branch_packs.append(sp4) |
| 304 | |
| 305 | p2_a, p2_b, p2_c = branch_packs |
| 306 | |
| 307 | # Verify spchainapp + spchaineval + spchainsamp bit-identity against l4_a_ck |
| 308 | rebuilt_l4 = workdir / "rebuilt_l4.ck" |
| 309 | rc, _, err, _ = run_cmd([str(ollm), "spchainapp", str(base_ck), str(rebuilt_l4), "2", str(p1_sp), str(p2_a)]) |
| 310 | if rc != 0: |
| 311 | raise RuntimeError(f"spchainapp failed: {err.decode()}") |
| 312 | |
| 313 | _, out_ref_e, _, _ = run_cmd([str(ollm), "eval", str(l4_a_ck), str(he_tok), "4"]) |
| 314 | _, out_ch_e, _, _ = run_cmd([str(ollm), "spchaineval", str(base_ck), str(he_tok), "4", "-", "2", str(p1_sp), str(p2_a)]) |
| 315 | _, out_rb_e, _, _ = run_cmd([str(ollm), "eval", str(rebuilt_l4), str(he_tok), "4"]) |
| 316 | _, _, ref_loss, ref_bpb = parse_eval_line(out_ref_e.decode()) |
| 317 | _, _, ch_loss, ch_bpb = parse_eval_line(out_ch_e.decode()) |
| 318 | _, _, rb_loss, rb_bpb = parse_eval_line(out_rb_e.decode()) |
| 319 | chain_eval_match = (ref_loss == ch_loss == rb_loss) and (ref_bpb == ch_bpb == rb_bpb) |
| 320 | |
| 321 | rc_s0, samp_ref, _, _ = run_cmd([str(ollm), "sample", str(l4_a_ck), "7", "24", "0", "hi"]) |
| 322 | rc_s1, samp_ch, _, _ = run_cmd([str(ollm), "spchainsamp", str(base_ck), "24", "0", "hi", "7", "-", "2", str(p1_sp), str(p2_a)]) |
| 323 | chain_samp_match = (rc_s0 == 0 and rc_s1 == 0 and samp_ref == samp_ch) |
| 324 | |
| 325 | # Negative controls: truncated (60), 1-bit flip (61), swapped order (62), skipped link (62) |
| 326 | trunc_sp = workdir / "trunc.sp" |
| 327 | trunc_sp.write_bytes(p2_a.read_bytes()[:32]) |
| 328 | rc_trunc, _, _, _ = run_cmd([str(ollm), "spchaineval", str(base_ck), str(he_tok), "4", "-", "2", str(p1_sp), str(trunc_sp)]) |
| 329 | |
| 330 | flip_sp = workdir / "flip.sp" |
| 331 | fb = bytearray(p2_a.read_bytes()) |
| 332 | fb[-1] ^= 0x01 |
| 333 | flip_sp.write_bytes(bytes(fb)) |
| 334 | rc_flip, _, _, _ = run_cmd([str(ollm), "spchaineval", str(base_ck), str(he_tok), "4", "-", "2", str(p1_sp), str(flip_sp)]) |
| 335 | |
| 336 | rc_swap, _, _, _ = run_cmd([str(ollm), "spchaineval", str(base_ck), str(he_tok), "4", "-", "2", str(p2_a), str(p1_sp)]) |
| 337 | rc_skip, _, _, _ = run_cmd([str(ollm), "spchaineval", str(base_ck), str(he_tok), "4", "-", "1", str(p2_a)]) |
| 338 | |
| 339 | neg_ok = (rc_trunc == 60 and rc_flip == 61 and rc_swap == 62 and rc_skip == 62) |
| 340 | |
| 341 | pack_total_bytes = p1_sp.stat().st_size + p2_a.stat().st_size |
| 342 | full_ck_bytes = l4_a_ck.stat().st_size |
| 343 | |
| 344 | chains_res = { |
| 345 | "status": "PASS" if (growpro_delta_unats == 0 and chain_eval_match and chain_samp_match and neg_ok) else "FAIL", |
| 346 | "growpro_step0_delta_unats": growpro_delta_unats, |
| 347 | "spchaineval_bit_identical": chain_eval_match, |
| 348 | "spchainsamp_bit_identical": chain_samp_match, |
| 349 | "chain_pack_bytes": pack_total_bytes, |
| 350 | "full_ck_bytes": full_ck_bytes, |
| 351 | "compression_ratio_x": round(full_ck_bytes / max(pack_total_bytes, 1), 2), |
| 352 | "neg_controls": { |
| 353 | "truncated_rc": rc_trunc, |
| 354 | "bitflip_rc": rc_flip, |
| 355 | "swapped_order_rc": rc_swap, |
| 356 | "skipped_link_rc": rc_skip, |
| 357 | "all_exact": neg_ok, |
| 358 | }, |
| 359 | } |
| 360 | |
| 361 | # Multi-Helix DNA Clipping (spclip S=2 and S=3) |
| 362 | # 1. Double-helix identity (A, A) == A in MODE=0 and MODE=1 |
| 363 | dh_m0_rc, dh_m0, _, _ = run_cmd([ |
| 364 | str(ollm), "spclip", str(base_ck), "0", "hi", "24", "0", "7", "-", "2", |
| 365 | "500", "2", str(p1_sp), str(p2_a), |
| 366 | "500", "2", str(p1_sp), str(p2_a), |
| 367 | ]) |
| 368 | dh_m1_rc, dh_m1, _, _ = run_cmd([ |
| 369 | str(ollm), "spclip", str(base_ck), "1", "hi", "24", "0", "7", "-", "2", |
| 370 | "500", "2", str(p1_sp), str(p2_a), |
| 371 | "500", "2", str(p1_sp), str(p2_a), |
| 372 | ]) |
| 373 | double_id_m0 = (dh_m0_rc == 0 and dh_m0 == samp_ch) |
| 374 | double_id_m1 = (dh_m1_rc == 0 and dh_m1 == samp_ch) |
| 375 | |
| 376 | # 2. Triple-helix identity (A, A, A) == A in MODE=0 and MODE=1 |
| 377 | th_m0_rc, th_m0, _, _ = run_cmd([ |
| 378 | str(ollm), "spclip", str(base_ck), "0", "hi", "24", "0", "7", "-", "3", |
| 379 | "334", "2", str(p1_sp), str(p2_a), |
| 380 | "333", "2", str(p1_sp), str(p2_a), |
| 381 | "333", "2", str(p1_sp), str(p2_a), |
| 382 | ]) |
| 383 | th_m1_rc, th_m1, _, _ = run_cmd([ |
| 384 | str(ollm), "spclip", str(base_ck), "1", "hi", "24", "0", "7", "-", "3", |
| 385 | "334", "2", str(p1_sp), str(p2_a), |
| 386 | "333", "2", str(p1_sp), str(p2_a), |
| 387 | "333", "2", str(p1_sp), str(p2_a), |
| 388 | ]) |
| 389 | triple_id_m0 = (th_m0_rc == 0 and th_m0 == samp_ch) |
| 390 | triple_id_m1 = (th_m1_rc == 0 and th_m1 == samp_ch) |
| 391 | |
| 392 | # 3. Distinct Triple-Helix (A, B, C) in MODE=1 (entropy-gated), 32 tokens |
| 393 | n_clip = 32 |
| 394 | d3_rc, d3_out, _, d3_ms = run_cmd([ |
| 395 | str(ollm), "spclip", str(base_ck), "1", "hi", str(n_clip), "200", "7", "-", "3", |
| 396 | "334", "2", str(p1_sp), str(p2_a), |
| 397 | "333", "2", str(p1_sp), str(p2_b), |
| 398 | "333", "2", str(p1_sp), str(p2_c), |
| 399 | ]) |
| 400 | distinct_ok = (d3_rc == 0 and len(d3_out) > 0) |
| 401 | |
| 402 | spclip_res = { |
| 403 | "status": "PASS" if (double_id_m0 and double_id_m1 and triple_id_m0 and triple_id_m1 and distinct_ok) else "FAIL", |
| 404 | "double_helix_identity_mode0": double_id_m0, |
| 405 | "double_helix_identity_mode1": double_id_m1, |
| 406 | "triple_helix_identity_mode0": triple_id_m0, |
| 407 | "triple_helix_identity_mode1": triple_id_m1, |
| 408 | "distinct_triple_helix_rc": d3_rc, |
| 409 | "distinct_triple_helix_bytes": len(d3_out), |
| 410 | "distinct_triple_helix_tokens": n_clip, |
| 411 | "distinct_triple_helix_ms_per_tok": round(d3_ms / n_clip, 3), |
| 412 | } |
| 413 | return chains_res, spclip_res |
| 414 | |
| 415 | |
| 416 | def section_om_feedback(omc: Path, workdir: Path) -> dict: |
| 417 | # 1. Live 30-error refusal-repair coverage |
| 418 | rc_r, out_r, err_r, ms_r = run_cmd([ |
| 419 | sys.executable, |
| 420 | str(REPO_ROOT / "tools/om_bundle_data.py"), |
| 421 | "refusals", |
| 422 | "--omc", |
| 423 | str(omc), |
| 424 | "--include-err24", |
| 425 | ]) |
| 426 | ref_line = out_r.decode("utf-8", errors="replace").strip() |
| 427 | m_ref = re.search(r"Verified (\d+) live omc refusal-repair pairs covering (\d+) error codes", ref_line) |
| 428 | pairs_n = int(m_ref.group(1)) if m_ref else 0 |
| 429 | codes_n = int(m_ref.group(2)) if m_ref else 0 |
| 430 | |
| 431 | # 2. Local omc compile latency benchmark (20 runs) |
| 432 | bench_json = workdir / "omc_bench.json" |
| 433 | rc_b, _, err_b, _ = run_cmd([ |
| 434 | sys.executable, |
| 435 | str(REPO_ROOT / "tools/om_compile_loop.py"), |
| 436 | "bench", |
| 437 | "--omc", |
| 438 | str(omc), |
| 439 | "--runs", |
| 440 | "20", |
| 441 | "--json-out", |
| 442 | str(bench_json), |
| 443 | ]) |
| 444 | bench_rows = json.loads(bench_json.read_text()) if (rc_b == 0 and bench_json.is_file()) else [] |
| 445 | |
| 446 | # 3. Deterministic refusal -> repair check |
| 447 | broken = "fn main to int\nx = 5\nret x\nend\n" |
| 448 | repaired = "fn main to int\nx = int 5\nret x\nend\n" |
| 449 | t0 = time.perf_counter() |
| 450 | p0 = subprocess.run([str(omc)], input=broken.encode(), capture_output=True, timeout=15) |
| 451 | ms0 = (time.perf_counter() - t0) * 1000.0 |
| 452 | t1 = time.perf_counter() |
| 453 | p1 = subprocess.run([str(omc)], input=repaired.encode(), capture_output=True, timeout=15) |
| 454 | ms1 = (time.perf_counter() - t1) * 1000.0 |
| 455 | repair_ok = (p0.returncode == 11 and p1.returncode == 0 and len(p1.stdout) > 0) |
| 456 | |
| 457 | ok = (rc_r == 0 and codes_n == 30 and rc_b == 0 and len(bench_rows) >= 3 and repair_ok) |
| 458 | return { |
| 459 | "status": "PASS" if ok else "FAIL", |
| 460 | "refusal_pairs": pairs_n, |
| 461 | "refusal_error_codes": codes_n, |
| 462 | "refusal_check_ms": round(ms_r, 1), |
| 463 | "omc_bench": bench_rows, |
| 464 | "deterministic_refusal_repair": { |
| 465 | "attempt0_rc": p0.returncode, |
| 466 | "attempt0_stderr": p0.stderr.decode("utf-8", errors="replace").strip(), |
| 467 | "attempt0_ms": round(ms0, 3), |
| 468 | "attempt1_rc": p1.returncode, |
| 469 | "attempt1_bin_bytes": len(p1.stdout), |
| 470 | "attempt1_ms": round(ms1, 3), |
| 471 | "passed": repair_ok, |
| 472 | }, |
| 473 | } |
| 474 | |
| 475 | |
| 476 | def section_real_checkpoint( |
| 477 | ollm: Path, |
| 478 | base_ck: Optional[Path], |
| 479 | spec_pack: Optional[Path], |
| 480 | held_tok: Optional[Path], |
| 481 | merges: Optional[Path], |
| 482 | ) -> dict: |
| 483 | if not (base_ck and spec_pack and held_tok and base_ck.is_file() and spec_pack.is_file() and held_tok.is_file()): |
| 484 | return { |
| 485 | "status": "NOT_RUN", |
| 486 | "reason": "optional real checkpoint/pack/held-tok not supplied or not present", |
| 487 | } |
| 488 | he_toks = held_tok.stat().st_size // 2 |
| 489 | wins = max(1, min(9, (he_toks - 1) // 256)) |
| 490 | m_args = [str(merges)] if (merges and merges.is_file()) else [] |
| 491 | |
| 492 | rc_b, out_b, err_b, ms_b = run_cmd([str(ollm), "eval", str(base_ck), str(held_tok), str(wins)] + m_args, timeout=300) |
| 493 | if rc_b != 0: |
| 494 | raise RuntimeError(f"real base eval failed rc={rc_b}: {err_b.decode()}") |
| 495 | _, _, b_loss, b_bpb = parse_eval_line(out_b.decode()) |
| 496 | |
| 497 | rc_s, out_s, err_s, ms_s = run_cmd( |
| 498 | [str(ollm), "speval", str(base_ck), str(spec_pack), str(held_tok), str(wins)] + m_args, timeout=300 |
| 499 | ) |
| 500 | if rc_s != 0: |
| 501 | raise RuntimeError(f"real speval failed rc={rc_s}: {err_s.decode()}") |
| 502 | _, _, s_loss, s_bpb = parse_eval_line(out_s.decode()) |
| 503 | |
| 504 | delta_pct = ((s_loss - b_loss) / b_loss) * 100.0 |
| 505 | ck_bytes = base_ck.stat().st_size |
| 506 | sp_bytes = spec_pack.stat().st_size |
| 507 | return { |
| 508 | "status": "PASS", |
| 509 | "base_ck_name": base_ck.name, |
| 510 | "spec_pack_name": spec_pack.name, |
| 511 | "windows": wins, |
| 512 | "base_nats_per_tok": round(b_loss / 1e6, 6), |
| 513 | "base_bpb": round(b_bpb / 1e6, 6), |
| 514 | "spec_nats_per_tok": round(s_loss / 1e6, 6), |
| 515 | "spec_bpb": round(s_bpb / 1e6, 6), |
| 516 | "delta_nats_pct": round(delta_pct, 2), |
| 517 | "base_ck_bytes": ck_bytes, |
| 518 | "spec_pack_bytes": sp_bytes, |
| 519 | "pack_compression_vs_base_x": round(ck_bytes / max(sp_bytes, 1), 2), |
| 520 | "base_eval_ms": round(ms_b, 1), |
| 521 | "spec_eval_ms": round(ms_s, 1), |
| 522 | } |
| 523 | |
| 524 | |
| 525 | def render_markdown(rep: dict) -> str: |
| 526 | m = rep["metrics"] |
| 527 | gb = m["gate_and_build"] |
| 528 | kv = m["kv_cache"] |
| 529 | ch = m["merkle_chains"] |
| 530 | cl = m["multi_helix_spclip"] |
| 531 | fb = m["om_feedback_loop"] |
| 532 | rc = m["real_checkpoint"] |
| 533 | hw = m["hardware_unrun"] |
| 534 | |
| 535 | b_summary = ", ".join( |
| 536 | f"{k}: {v['status']} ({v.get('bytes', 0):,} B)" for k, v in gb["builds"].items() |
| 537 | ) |
| 538 | small_b = next((r for r in fb["omc_bench"] if r["unit"] == "small_6loc"), None) |
| 539 | large_b = next((r for r in fb["omc_bench"] if r["unit"] == "large_564loc"), None) |
| 540 | omc_lat = ( |
| 541 | f"6 LOC p50={small_b['median_ms']} ms (p95={small_b['p95_ms']} ms); " |
| 542 | f"565 LOC p50={large_b['median_ms']} ms (p95={large_b['p95_ms']} ms)" |
| 543 | if (small_b and large_b) |
| 544 | else "n/a" |
| 545 | ) |
| 546 | |
| 547 | if rc["status"] == "PASS": |
| 548 | rc_detail = ( |
| 549 | f"{rc['spec_pack_name']} on {rc['base_ck_name']} (W={rc['windows']}): " |
| 550 | f"{rc['base_nats_per_tok']} -> {rc['spec_nats_per_tok']} nats/tok " |
| 551 | f"({rc['delta_nats_pct']:+.2f}%), bpb {rc['base_bpb']} -> {rc['spec_bpb']}, " |
| 552 | f"pack {rc['spec_pack_bytes']:,} B ({rc['pack_compression_vs_base_x']}x smaller than base)" |
| 553 | ) |
| 554 | else: |
| 555 | rc_detail = rc.get("reason", "NOT_RUN") |
| 556 | |
| 557 | lines = [ |
| 558 | f"# OLLM Metrics & Readiness Report (`--mode {rep['mode']}`)", |
| 559 | "", |
| 560 | f"- **Host:** `{rep['host']['system']} {rep['host']['release']} ({rep['host']['machine']})`", |
| 561 | f"- **Git HEAD:** `{rep['git_head']}`", |
| 562 | f"- **Total runtime:** `{rep['elapsed_s']} s`", |
| 563 | "", |
| 564 | "| Category | Status | Key Measured Metrics |", |
| 565 | "|---|---|---|", |
| 566 | f"| **Pre-review gate** | `{gb['pre_review']['status']}` | `{gb['pre_review']['output']}` |", |
| 567 | f"| **Cross-target `omc` build** | `{'PASS' if all(v['status']=='PASS' for v in gb['builds'].values()) else 'FAIL'}` | {b_summary} |", |
| 568 | f"| **KV-cache (`kvcmp`, L={kv['layers']})** | `{kv['status']}` | `ndiff={kv['ndiff_logits']}`, `{kv['inc_tok_per_s']} tok/s` vs `{kv['full_tok_per_s']} tok/s` (`{kv['speedup_x']}x` speedup) |", |
| 569 | f"| **Merkle chains (`OLLMSP01`, L=2->3->4)** | `{ch['status']}` | `growpro` step-0 `Δ={ch['growpro_step0_delta_unats']} µnats`, `spchaineval/samp` bit-identical, `{ch['compression_ratio_x']}x` smaller, neg controls `rc={ch['neg_controls']['truncated_rc']}/{ch['neg_controls']['bitflip_rc']}/{ch['neg_controls']['swapped_order_rc']}/{ch['neg_controls']['skipped_link_rc']}` |", |
| 570 | f"| **Multi-helix `spclip` (`S=2,3`)** | `{cl['status']}` | Double `(A,A)==A` & Triple `(A,A,A)==A` bit-identical (`MODE=0,1`); distinct 3-strand `(A,B,C)` `{cl['distinct_triple_helix_ms_per_tok']} ms/tok` |", |
| 571 | f"| **`.om` refusals & `omc` loop** | `{fb['status']}` | `{fb['refusal_pairs']}` pairs covering `{fb['refusal_error_codes']}/30` errors (`1..30`); {omc_lat}; repair `rc=11 -> rc=0` |", |
| 572 | f"| **Real checkpoint specialist eval** | `{rc['status']}` | {rc_detail} |", |
| 573 | f"| **GB10 GPU (`gtrainb`/`geval`/`v3 L=16` Rung 11)** | `{hw['gb10_gpu_training']['status']}` | {hw['gb10_gpu_training']['reason']} |", |
| 574 | f"| **Aienux / GB20B live decode** | `{hw['aienux_gb20b_live_decode']['status']}` | {hw['aienux_gb20b_live_decode']['reason']} |", |
| 575 | "", |
| 576 | ] |
| 577 | return "\n".join(lines) |
| 578 | |
| 579 | |
| 580 | def main() -> int: |
| 581 | ap = argparse.ArgumentParser(description="One-command OLLM metrics & readiness benchmark suite.") |
| 582 | ap.add_argument("--mode", choices=("quick", "full"), default="quick") |
| 583 | ap.add_argument("--json-out", default="") |
| 584 | ap.add_argument("--md-out", default="") |
| 585 | ap.add_argument("--ollm-bin", default="") |
| 586 | ap.add_argument("--omc", default="") |
| 587 | ap.add_argument("--base-ck", default="") |
| 588 | ap.add_argument("--spec-pack", default="") |
| 589 | ap.add_argument("--held-tok", default="") |
| 590 | ap.add_argument("--merges", default="") |
| 591 | args = ap.parse_args() |
| 592 | |
| 593 | t_start = time.perf_counter() |
| 594 | omc = find_omc(args.omc or None) |
| 595 | |
| 596 | rc_g, out_g, _, _ = run_cmd(["git", "-C", str(REPO_ROOT), "rev-parse", "--short", "HEAD"]) |
| 597 | git_head = out_g.decode().strip() if rc_g == 0 else "unknown" |
| 598 | |
| 599 | base_ck = Path(args.base_ck).expanduser() if args.base_ck else None |
| 600 | spec_pack = Path(args.spec_pack).expanduser() if args.spec_pack else None |
| 601 | held_tok = Path(args.held_tok).expanduser() if args.held_tok else None |
| 602 | merges = Path(args.merges).expanduser() if args.merges else None |
| 603 | |
| 604 | if args.mode == "full": |
| 605 | home = Path.home() |
| 606 | if base_ck is None: |
| 607 | cand = home / "workspace/aien-train-macbook/local-mac/omega-v2.ck" |
| 608 | if cand.is_file(): |
| 609 | base_ck = cand |
| 610 | if merges is None: |
| 611 | cand = home / "workspace/aien-train-macbook/local-mac/merges4096.bin" |
| 612 | if cand.is_file(): |
| 613 | merges = cand |
| 614 | if held_tok is None: |
| 615 | cand = home / "workspace/aien-train-macbook/specialists/data_m/tool-call_held.tok" |
| 616 | if cand.is_file(): |
| 617 | held_tok = cand |
| 618 | if spec_pack is None: |
| 619 | cand = home / "workspace/aien-train-macbook/specialists/packs/tool-call_pro.sp" |
| 620 | if cand.is_file(): |
| 621 | spec_pack = cand |
| 622 | |
| 623 | with tempfile.TemporaryDirectory(prefix="ollm-metrics-") as tmp: |
| 624 | workdir = Path(tmp) |
| 625 | gate_build, ollm_bin = section_gate_and_build(omc, workdir, args.ollm_bin or None) |
| 626 | kv_res = section_kv_cache(ollm_bin, workdir) |
| 627 | chains_res, spclip_res = section_chains_and_spclip(ollm_bin, workdir) |
| 628 | fb_res = section_om_feedback(omc, workdir) |
| 629 | real_res = section_real_checkpoint(ollm_bin, base_ck, spec_pack, held_tok, merges) |
| 630 | |
| 631 | elapsed_s = round(time.perf_counter() - t_start, 2) |
| 632 | report = { |
| 633 | "mode": args.mode, |
| 634 | "git_head": git_head, |
| 635 | "elapsed_s": elapsed_s, |
| 636 | "host": { |
| 637 | "system": platform.system(), |
| 638 | "release": platform.release(), |
| 639 | "machine": platform.machine(), |
| 640 | }, |
| 641 | "metrics": { |
| 642 | "gate_and_build": gate_build, |
| 643 | "kv_cache": kv_res, |
| 644 | "merkle_chains": chains_res, |
| 645 | "multi_helix_spclip": spclip_res, |
| 646 | "om_feedback_loop": fb_res, |
| 647 | "real_checkpoint": real_res, |
| 648 | "hardware_unrun": { |
| 649 | "gb10_gpu_training": { |
| 650 | "status": "NOT_RUN", |
| 651 | "reason": "requires authorized DGX Spark spark-window (no GPU touched)", |
| 652 | }, |
| 653 | "aienux_gb20b_live_decode": { |
| 654 | "status": "NOT_RUN", |
| 655 | "reason": "requires authorized Aienux/GB20B hardware window", |
| 656 | }, |
| 657 | }, |
| 658 | }, |
| 659 | } |
| 660 | |
| 661 | md = render_markdown(report) |
| 662 | print(md) |
| 663 | |
| 664 | if args.json_out: |
| 665 | p = Path(args.json_out).expanduser() |
| 666 | p.parent.mkdir(parents=True, exist_ok=True) |
| 667 | p.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") |
| 668 | if args.md_out: |
| 669 | p = Path(args.md_out).expanduser() |
| 670 | p.parent.mkdir(parents=True, exist_ok=True) |
| 671 | p.write_text(md, encoding="utf-8") |
| 672 | |
| 673 | all_pass = ( |
| 674 | gate_build["pre_review"]["status"] == "PASS" |
| 675 | and all(v["status"] == "PASS" for v in gate_build["builds"].values()) |
| 676 | and kv_res["status"] == "PASS" |
| 677 | and chains_res["status"] == "PASS" |
| 678 | and spclip_res["status"] == "PASS" |
| 679 | and fb_res["status"] == "PASS" |
| 680 | and real_res["status"] in ("PASS", "NOT_RUN") |
| 681 | ) |
| 682 | return 0 if all_pass else 1 |
| 683 | |
| 684 | |
| 685 | if __name__ == "__main__": |
| 686 | sys.exit(main()) |