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 / tools / om_compile_loop.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Local M2 CPU `ollm spsamp` + `omc` millisecond compile-retry feedback loop |
| 3 | and `omc` compile latency benchmark. |
| 4 | |
| 5 | Demonstrates the local feedback-loop leg: |
| 6 | generate .om via `ollm spsamp` -> compile with local `omc` -> feed exact `omc` |
| 7 | stderr refusal back into the next prompt on non-zero exit. |
| 8 | |
| 9 | Never executes refused compiler output. Does not touch any GPU. |
| 10 | """ |
| 11 | |
| 12 | from __future__ import annotations |
| 13 | |
| 14 | import argparse |
| 15 | import json |
| 16 | import os |
| 17 | import statistics |
| 18 | import subprocess |
| 19 | import sys |
| 20 | import time |
| 21 | from pathlib import Path |
| 22 | from typing import List, Optional, Tuple |
| 23 | |
| 24 | |
| 25 | def compile_omc(omc: Path, src: str, timeout: int = 15) -> Tuple[int, str, int, float]: |
| 26 | """Compile .om source via stdin to omc. Returns (rc, stderr, out_bytes, elapsed_ms).""" |
| 27 | t0 = time.perf_counter() |
| 28 | p = subprocess.run( |
| 29 | [str(omc)], |
| 30 | input=src.encode("utf-8"), |
| 31 | capture_output=True, |
| 32 | timeout=timeout, |
| 33 | ) |
| 34 | dt_ms = (time.perf_counter() - t0) * 1000.0 |
| 35 | stderr = p.stderr.decode("utf-8", errors="replace").strip() |
| 36 | out_bytes = len(p.stdout) if p.returncode == 0 else 0 |
| 37 | return p.returncode, stderr, out_bytes, dt_ms |
| 38 | |
| 39 | |
| 40 | def run_spsamp( |
| 41 | ollm: Path, |
| 42 | base_ck: Path, |
| 43 | pack_sp: Path, |
| 44 | n_toks: int, |
| 45 | temp_milli: int, |
| 46 | prompt: str, |
| 47 | seed: int, |
| 48 | merges: Optional[Path] = None, |
| 49 | timeout: int = 120, |
| 50 | ) -> Tuple[int, str, str, float]: |
| 51 | """Run `ollm spsamp BASE.ck PACK.sp N TEMPMILLI PROMPT SEED [MERGES]`.""" |
| 52 | cmd = [ |
| 53 | str(ollm), |
| 54 | "spsamp", |
| 55 | str(base_ck), |
| 56 | str(pack_sp), |
| 57 | str(n_toks), |
| 58 | str(temp_milli), |
| 59 | prompt, |
| 60 | str(seed), |
| 61 | ] |
| 62 | if merges is not None and merges.is_file(): |
| 63 | cmd.append(str(merges)) |
| 64 | t0 = time.perf_counter() |
| 65 | p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout) |
| 66 | dt_ms = (time.perf_counter() - t0) * 1000.0 |
| 67 | return p.returncode, p.stdout, p.stderr.strip(), dt_ms |
| 68 | |
| 69 | |
| 70 | def extract_om_candidate(raw_output: str, prompt: str) -> str: |
| 71 | """Extract .om source lines from spsamp output, stripping any leading prompt echo.""" |
| 72 | text = raw_output |
| 73 | if text.startswith(prompt): |
| 74 | text = text[len(prompt) :] |
| 75 | # Keep printable lines; stop at NUL if present |
| 76 | if "\x00" in text: |
| 77 | text = text.split("\x00", 1)[0] |
| 78 | return text.strip() + "\n" |
| 79 | |
| 80 | |
| 81 | def run_compile_loop( |
| 82 | ollm: Path, |
| 83 | base_ck: Path, |
| 84 | pack_sp: Path, |
| 85 | omc: Path, |
| 86 | prompt: str, |
| 87 | merges: Optional[Path] = None, |
| 88 | max_retries: int = 3, |
| 89 | n_toks: int = 64, |
| 90 | temp_milli: int = 200, |
| 91 | seed: int = 42, |
| 92 | ) -> dict: |
| 93 | """Execute generate -> compile -> refusal-feedback retry loop.""" |
| 94 | cur_prompt = prompt |
| 95 | attempts: List[dict] = [] |
| 96 | compiled = False |
| 97 | |
| 98 | for attempt in range(max_retries + 1): |
| 99 | rc_s, out_s, err_s, samp_ms = run_spsamp( |
| 100 | ollm=ollm, |
| 101 | base_ck=base_ck, |
| 102 | pack_sp=pack_sp, |
| 103 | n_toks=n_toks, |
| 104 | temp_milli=temp_milli, |
| 105 | prompt=cur_prompt, |
| 106 | seed=seed + attempt, |
| 107 | merges=merges, |
| 108 | ) |
| 109 | if rc_s != 0: |
| 110 | raise RuntimeError(f"ollm spsamp failed (rc={rc_s}): {err_s}") |
| 111 | |
| 112 | cand = extract_om_candidate(out_s, cur_prompt) |
| 113 | rc_c, err_c, bin_bytes, omc_ms = compile_omc(omc, cand) |
| 114 | |
| 115 | rec = { |
| 116 | "attempt": attempt, |
| 117 | "seed": seed + attempt, |
| 118 | "spsamp_ms": round(samp_ms, 2), |
| 119 | "omc_ms": round(omc_ms, 3), |
| 120 | "omc_rc": rc_c, |
| 121 | "omc_stderr": err_c, |
| 122 | "bin_bytes": bin_bytes, |
| 123 | "candidate_preview": cand[:160], |
| 124 | } |
| 125 | attempts.append(rec) |
| 126 | |
| 127 | if rc_c == 0: |
| 128 | compiled = True |
| 129 | break |
| 130 | |
| 131 | # Feed exact omc refusal back into the next prompt |
| 132 | cur_prompt = f"{prompt}\nnote omc refusal: {err_c}\nnote fix:\n" |
| 133 | |
| 134 | return { |
| 135 | "compiled": compiled, |
| 136 | "attempts_used": len(attempts), |
| 137 | "max_retries": max_retries, |
| 138 | "pack": pack_sp.name, |
| 139 | "attempts": attempts, |
| 140 | } |
| 141 | |
| 142 | |
| 143 | def cmd_bench(args: argparse.Namespace) -> int: |
| 144 | omc = Path(args.omc).expanduser() |
| 145 | runs = args.runs |
| 146 | targets: List[Tuple[str, str]] = [] |
| 147 | |
| 148 | if args.files: |
| 149 | for f in args.files: |
| 150 | p = Path(f).expanduser() |
| 151 | targets.append((p.name, p.read_text(encoding="utf-8"))) |
| 152 | else: |
| 153 | # Built-in representative standalone .om units spanning small/medium/large LOC |
| 154 | small = ( |
| 155 | "note small standalone unit\n" |
| 156 | "fn main to int\n" |
| 157 | "x = int 40\n" |
| 158 | "y = add x 2\n" |
| 159 | "ret y\n" |
| 160 | "end\n" |
| 161 | ) |
| 162 | medium_lines = ["note medium standalone unit (100-line loop + helpers)"] |
| 163 | for i in range(10): |
| 164 | medium_lines.append(f"fn h{i} a ulong b ulong to ulong") |
| 165 | medium_lines.append(f"r = add a b") |
| 166 | medium_lines.append(f"r = xor r ulong {i + 1}") |
| 167 | medium_lines.append("ret r") |
| 168 | medium_lines.append("end") |
| 169 | medium_lines.append("fn main to int") |
| 170 | medium_lines.append("acc = ulong 0") |
| 171 | medium_lines.append("for i ulong 64") |
| 172 | for i in range(10): |
| 173 | medium_lines.append(f"acc = h{i} acc i") |
| 174 | medium_lines.append("end") |
| 175 | medium_lines.append("ret int and acc 255") |
| 176 | medium_lines.append("end") |
| 177 | medium = "\n".join(medium_lines) + "\n" |
| 178 | |
| 179 | large_lines = ["note large standalone unit (564-line compute unit)"] |
| 180 | for i in range(80): |
| 181 | large_lines.append(f"fn step{i} x ulong y ulong to ulong") |
| 182 | large_lines.append("a = add x y") |
| 183 | large_lines.append("b = xor a shl y 1") |
| 184 | large_lines.append("c = add b shr x 1") |
| 185 | large_lines.append(f"ret xor c ulong {i + 7}") |
| 186 | large_lines.append("end") |
| 187 | large_lines.append("fn main to int") |
| 188 | large_lines.append("s = ulong 1") |
| 189 | for i in range(80): |
| 190 | large_lines.append(f"s = step{i} s ulong {i + 1}") |
| 191 | large_lines.append("ret int and s 255") |
| 192 | large_lines.append("end") |
| 193 | large = "\n".join(large_lines) + "\n" |
| 194 | |
| 195 | targets = [ |
| 196 | ("small_6loc", small), |
| 197 | ("medium_67loc", medium), |
| 198 | ("large_564loc", large), |
| 199 | ] |
| 200 | |
| 201 | # Warm up once |
| 202 | compile_omc(omc, targets[0][1]) |
| 203 | |
| 204 | results = [] |
| 205 | print(f"{'UNIT':22s} {'LOC':>5s} {'RUNS':>4s} {'MIN_MS':>8s} {'MED_MS':>8s} {'P95_MS':>8s} {'MAX_MS':>8s} {'BIN_B':>8s}") |
| 206 | for name, src in targets: |
| 207 | loc = src.count("\n") |
| 208 | times: List[float] = [] |
| 209 | bin_b = 0 |
| 210 | for _ in range(runs): |
| 211 | rc, err, b, dt = compile_omc(omc, src) |
| 212 | if rc != 0: |
| 213 | raise RuntimeError(f"Benchmark unit {name} failed to compile: rc={rc} {err}") |
| 214 | times.append(dt) |
| 215 | bin_b = b |
| 216 | st = sorted(times) |
| 217 | p95 = st[min(len(st) - 1, int(0.95 * len(st)))] |
| 218 | row = { |
| 219 | "unit": name, |
| 220 | "loc": loc, |
| 221 | "runs": runs, |
| 222 | "min_ms": round(min(times), 3), |
| 223 | "median_ms": round(statistics.median(times), 3), |
| 224 | "p95_ms": round(p95, 3), |
| 225 | "max_ms": round(max(times), 3), |
| 226 | "bin_bytes": bin_b, |
| 227 | } |
| 228 | results.append(row) |
| 229 | print( |
| 230 | f"{name:22s} {loc:5d} {runs:4d} {row['min_ms']:8.3f} {row['median_ms']:8.3f} " |
| 231 | f"{row['p95_ms']:8.3f} {row['max_ms']:8.3f} {bin_b:8d}" |
| 232 | ) |
| 233 | |
| 234 | if args.json_out: |
| 235 | Path(args.json_out).write_text(json.dumps(results, indent=2) + "\n") |
| 236 | return 0 |
| 237 | |
| 238 | |
| 239 | def cmd_loop(args: argparse.Namespace) -> int: |
| 240 | res = run_compile_loop( |
| 241 | ollm=Path(args.ollm).expanduser(), |
| 242 | base_ck=Path(args.base_ck).expanduser(), |
| 243 | pack_sp=Path(args.pack).expanduser(), |
| 244 | omc=Path(args.omc).expanduser(), |
| 245 | prompt=args.prompt, |
| 246 | merges=Path(args.merges).expanduser() if args.merges else None, |
| 247 | max_retries=args.max_retries, |
| 248 | n_toks=args.tokens, |
| 249 | temp_milli=args.temp_milli, |
| 250 | seed=args.seed, |
| 251 | ) |
| 252 | print(json.dumps(res, indent=2)) |
| 253 | return 0 |
| 254 | |
| 255 | |
| 256 | def cmd_selftest(args: argparse.Namespace) -> int: |
| 257 | omc = Path(args.omc).expanduser() |
| 258 | ollm = Path(args.ollm).expanduser() |
| 259 | base_ck = Path(args.base_ck).expanduser() |
| 260 | pack_sp = Path(args.pack).expanduser() |
| 261 | merges = Path(args.merges).expanduser() if args.merges else None |
| 262 | |
| 263 | # Part A: deterministic refusal -> feedback -> repair check against real omc |
| 264 | broken = "fn main to int\nx = 5\nret x\nend\n" |
| 265 | rc0, err0, _, ms0 = compile_omc(omc, broken) |
| 266 | assert rc0 == 11 and "error 11" in err0, f"Expected error 11, got rc={rc0} err={err0!r}" |
| 267 | repaired = "fn main to int\nx = int 5\nret x\nend\n" |
| 268 | rc1, err1, bin1, ms1 = compile_omc(omc, repaired) |
| 269 | assert rc1 == 0 and bin1 > 0, f"Expected clean compile, got rc={rc1} err={err1!r}" |
| 270 | |
| 271 | # Part B: live ollm spsamp + omc compile-retry loop on M2 CPU |
| 272 | loop_res = run_compile_loop( |
| 273 | ollm=ollm, |
| 274 | base_ck=base_ck, |
| 275 | pack_sp=pack_sp, |
| 276 | omc=omc, |
| 277 | prompt="fn main to int\n", |
| 278 | merges=merges, |
| 279 | max_retries=2, |
| 280 | n_toks=32, |
| 281 | temp_milli=200, |
| 282 | seed=7, |
| 283 | ) |
| 284 | |
| 285 | out = { |
| 286 | "deterministic_refusal_repair": { |
| 287 | "attempt0_rc": rc0, |
| 288 | "attempt0_stderr": err0, |
| 289 | "attempt0_omc_ms": round(ms0, 3), |
| 290 | "attempt1_rc": rc1, |
| 291 | "attempt1_bin_bytes": bin1, |
| 292 | "attempt1_omc_ms": round(ms1, 3), |
| 293 | }, |
| 294 | "live_spsamp_omc_loop": loop_res, |
| 295 | } |
| 296 | print(json.dumps(out, indent=2)) |
| 297 | return 0 |
| 298 | |
| 299 | |
| 300 | def main() -> int: |
| 301 | ap = argparse.ArgumentParser(description="Local ollm spsamp + omc compile-retry feedback loop & latency bench.") |
| 302 | sub = ap.add_subparsers(dest="cmd", required=True) |
| 303 | |
| 304 | pb = sub.add_parser("bench", help="Benchmark local omc compile latency across representative .om units") |
| 305 | pb.add_argument("--omc", default=str(Path.home() / ".local/bin/omc")) |
| 306 | pb.add_argument("--runs", type=int, default=20) |
| 307 | pb.add_argument("--files", nargs="*", default=[]) |
| 308 | pb.add_argument("--json-out", default="") |
| 309 | pb.set_defaults(func=cmd_bench) |
| 310 | |
| 311 | pl = sub.add_parser("loop", help="Run live ollm spsamp + omc compile-retry loop") |
| 312 | pl.add_argument("--ollm", default=str(Path.home() / ".local/bin/ollm")) |
| 313 | pl.add_argument("--base-ck", default=str(Path.home() / "workspace/aien-train-macbook/local-mac/omega-v2.ck")) |
| 314 | pl.add_argument("--pack", default=str(Path.home() / "workspace/aien-train-macbook/specialists/packs/omega-code_pro.sp")) |
| 315 | pl.add_argument("--merges", default=str(Path.home() / "workspace/aien-train-macbook/local-mac/merges4096.bin")) |
| 316 | pl.add_argument("--omc", default=str(Path.home() / ".local/bin/omc")) |
| 317 | pl.add_argument("--prompt", default="fn main to int\n") |
| 318 | pl.add_argument("--max-retries", type=int, default=3) |
| 319 | pl.add_argument("--tokens", type=int, default=64) |
| 320 | pl.add_argument("--temp-milli", type=int, default=200) |
| 321 | pl.add_argument("--seed", type=int, default=42) |
| 322 | pl.set_defaults(func=cmd_loop) |
| 323 | |
| 324 | ps = sub.add_parser("selftest", help="Verify deterministic refusal-repair + live ollm spsamp -> omc loop") |
| 325 | ps.add_argument("--ollm", default=str(Path.home() / ".local/bin/ollm")) |
| 326 | ps.add_argument("--base-ck", default=str(Path.home() / "workspace/aien-train-macbook/local-mac/omega-v2.ck")) |
| 327 | ps.add_argument("--pack", default=str(Path.home() / "workspace/aien-train-macbook/specialists/packs/omega-code_pro.sp")) |
| 328 | ps.add_argument("--merges", default=str(Path.home() / "workspace/aien-train-macbook/local-mac/merges4096.bin")) |
| 329 | ps.add_argument("--omc", default=str(Path.home() / ".local/bin/omc")) |
| 330 | ps.set_defaults(func=cmd_selftest) |
| 331 | |
| 332 | args = ap.parse_args() |
| 333 | return args.func(args) |
| 334 | |
| 335 | |
| 336 | if __name__ == "__main__": |
| 337 | sys.exit(main()) |