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/omega-bridge/blob/main/max-cpu/omega_max.py # omega-bridge Omega-first language interoperability: checked conversion backends and native language bindings 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 `omega-bridge / max-cpu / omega_max.py` 325 lines ยท 14687 bytes Raw Blame History 1 """MAX CPU harness for the Omega matmul custom op (max-cpu/omatmul.om via max-cpu/kernels). 2 3 Subcommands (run with the MAX venv python, see max-cpu/run.sh): 4 check numerics: Omega op vs numpy float64 and vs ops.matmul on the same graph 5 neg-shape bad shapes: refused by Omega (codes 1/2/3) and at graph construction 6 neg-load a kernels dir that must fail to load or execute (wrong symbol, external_call) 7 measure one op/shape in this process: cold start, warm latencies, peak RSS 8 measure-all spawns one `measure` child per (op, shape, cache state) 9 10 Every graph runs on DeviceRef.CPU() only, and main() refuses (exit 2) while an accelerator is 11 visible, because MAX 26.7.0 Graph() otherwise opens a CUDA context. Exit 0 = the expected 12 outcome was observed. 13 """ 14 15 import argparse 16 import ctypes 17 import json 18 import os 19 import pathlib 20 import resource 21 import subprocess 22 import sys 23 import time 24 25 import numpy as np 26 27 HERE = pathlib.Path(__file__).resolve().parent 28 29 # Error bound per K (Wolfram, evidence/MAX-CPU/README.md "Tolerances"): 30 # g[n_,u_]:=n u/(1-n u); u32=2^-24; u64=2^-53 31 # ref: g[K-1,u32]+g[K-1,u64] max: 2 g[K-1,u32] 32 # Elementwise |C - R| <= tol * (|A| @ |B|), evaluated in float64. 33 TOL = { 34 1: (0.0, 0.0), 35 5: (2.`384186363890841e`-7, 4.`768372718899898e`-7), 36 16: (8.`940704726574863e`-7, 1.`788140941984304e`-6), 37 17: (9.`536752276781760e`-7, 1.`907350451803638e`-6), 38 128: (7.`569847202727132e`-6, 1.`513969437725460e`-5), 39 256: (1.`519941546475356e`-5, 3.`039883087288574e`-5), 40 } 41 SHAPES = [(1, 1, 1), (3, 5, 7), (16, 16, 8), (33, 17, 9), (64, 128, 32), (256, 256, 256)] 42 43 44 def load_omega(lib): 45 # RTLD_GLOBAL puts omega2_omatmul in the process scope that the glue's dlopen(NULL) searches. 46 ctypes.CDLL(str(lib), mode=ctypes.RTLD_GLOBAL) 47 48 49 def bf16_bits(x): 50 """float32 -> bf16 bit patterns, round to nearest even.""" 51 u = np.asarray(x, np.float32).view(np.uint32).astype(np.uint64) 52 return ((u + 0x7FFF + ((u >> 16) & 1)) >> 16).astype(np.uint16) 53 54 55 def bf16_round(x): 56 """float32 values exactly representable in bf16 (so the in-graph cast is exact).""" 57 return (bf16_bits(x).astype(np.uint32) << 16).view(np.float32).reshape(np.shape(x)) 58 59 60 def max_mods(): 61 from max.driver import CPU, Buffer 62 from max.dtype import DType 63 from max.engine import InferenceSession 64 from max.graph import DeviceRef, Graph, TensorType, ops 65 66 return CPU, Buffer, DType, InferenceSession, DeviceRef, Graph, TensorType, ops 67 68 69 def build_graph(kind, M, K, N, kernels): 70 CPU, Buffer, DType, InferenceSession, DeviceRef, Graph, TensorType, ops = max_mods() 71 dev = DeviceRef.CPU() 72 f32a = TensorType(DType.float32, [M, K], dev) 73 f32b = TensorType(DType.float32, [K, N], dev) 74 s3 = TensorType(DType.int64, [3], dev) 75 abt = TensorType(DType.bfloat16, [M * K + K * N], dev) 76 cout = [TensorType(DType.float32, [M, N], dev)] 77 78 def cat(a, b): 79 return ops.concat( 80 [ 81 ops.reshape(ops.cast(a, DType.bfloat16), [M * K]), 82 ops.reshape(ops.cast(b, DType.bfloat16), [K * N]), 83 ], 84 axis=0, 85 ) 86 87 def omega(ab, s): 88 return ops.custom("omega_matmul", device=dev, values=[ab, s], out_types=cout)[0].tensor 89 90 if kind == "both": 91 fwd, types = (lambda a, b, s: (omega(cat(a, b), s), ops.matmul(a, b))), [f32a, f32b, s3] 92 elif kind == "omega": 93 fwd, types = (lambda a, b, s: omega(cat(a, b), s)), [f32a, f32b, s3] 94 elif kind == "omega_nocat": 95 fwd, types = omega, [abt, s3] 96 elif kind == "concat": 97 fwd, types = cat, [f32a, f32b] 98 elif kind == "matmul": 99 fwd, types = (lambda a, b: ops.matmul(a, b)), [f32a, f32b] 100 else: 101 raise ValueError(kind) 102 return Graph(f"om_{kind}_{M}x{K}x{N}", forward=fwd, input_types=types, 103 custom_extensions=[pathlib.Path(kernels)]) 104 105 106 def session(): 107 CPU = max_mods()[0] 108 return max_mods()[3](devices=[CPU()]) 109 110 111 def inputs(kind, a, b, shape): 112 Buffer, DType = max_mods()[1], max_mods()[2] 113 s = Buffer.from_numpy(np.array(shape, np.int64)) 114 if kind == "omega_nocat": 115 ab = np.concatenate([bf16_bits(a).ravel(), bf16_bits(b).ravel()]) 116 return [Buffer.from_numpy(ab).view(DType.bfloat16), s] 117 fa, fb = Buffer.from_numpy(np.ascontiguousarray(a)), Buffer.from_numpy(np.ascontiguousarray(b)) 118 return [fa, fb, s] if kind in ("both", "omega") else [fa, fb] 119 120 121 def judge(c, r, a, b, tol): 122 """max ratio |c-r| / (tol*|A||B|); <= 1 passes. Zero tolerance means exact equality.""" 123 bound = tol * (np.abs(a.astype(np.float64)) @ np.abs(b.astype(np.float64))) 124 err = np.abs(c.astype(np.float64) - r.astype(np.float64)) 125 if tol == 0.0: 126 return (0.0 if np.array_equal(err, np.zeros_like(err)) else float("inf")), float(err.max()) 127 with np.errstate(divide="ignore", invalid="ignore"): 128 ratio = np.where(bound > 0, err / bound, np.where(err > 0, np.inf, 0.0)) 129 return float(ratio.max()), float(err.max()) 130 131 132 def cases(M, K, N, rng): 133 out = [("random", bf16_round(rng.standard_normal((M, K)).astype(np.float32)), 134 bf16_round(rng.standard_normal((K, N)).astype(np.float32)))] 135 out.append(("zeros", np.zeros((M, K), np.float32), np.zeros((K, N), np.float32))) 136 if K == N: 137 out.append(("identity", out[0][1], np.eye(K, dtype=np.float32))) 138 if (M, K, N) == (16, 16, 8): 139 big = np.float32(2.0**60) 140 out.append(("large", out[0][1] * big, out[0][2] * big)) 141 return out 142 143 144 def cmd_check(args): 145 load_omega(args.lib) 146 sess, rng, rows, ok = session(), np.random.default_rng(args.seed), [], True 147 for M, K, N in SHAPES: 148 t = time.monotonic() 149 model = sess.load(build_graph("both", M, K, N, args.kernels)) 150 load_s = time.monotonic() - t 151 tref, tmax = TOL[K] 152 for name, a, b in cases(M, K, N, rng): 153 o = model.execute(*inputs("both", a, b, [M, K, N])) 154 c, r = o[0].to_numpy(), o[1].to_numpy() 155 ref = a.astype(np.float64) @ b.astype(np.float64) 156 rr, er = judge(c, ref, a, b, tref) 157 rm, em = judge(c, r, a, b, tmax) 158 exact = name in ("zeros", "identity") 159 passed = rr <= 1.0 and rm <= 1.0 and (not exact or np.array_equal(c, ref.astype(np.float32))) 160 ok &= bool(passed) and bool(np.isfinite(c).all()) 161 row = dict(shape=[M, K, N], case=name, load_s=load_s, tol_ref=tref, tol_max=tmax, 162 ratio_ref=rr, maxerr_ref=er, ratio_max=rm, maxerr_max=em, 163 result="PASS" if passed else "FAIL") 164 rows.append(row) 165 print(f"{M}x{K}x{N} {name:8s} ratio_ref={rr:.3g} maxerr_ref={er:.3g} " 166 f"ratio_max={rm:.3g} maxerr_max={em:.3g} {row['result']}", flush=True) 167 pathlib.Path(args.out).write_text(json.dumps(dict(lib=str(args.lib), rows=rows), indent=1)) 168 print("OMEGA_MAX_CHECK:", "PASS" if ok else "FAIL") 169 return 0 if ok else 1 170 171 172 def cmd_neg_shape(args): 173 load_omega(args.lib) 174 CPU, Buffer, DType, InferenceSession, DeviceRef, Graph, TensorType, ops = max_mods() 175 M, K, N = 16, 16, 8 176 model = session().load(build_graph("omega", M, K, N, args.kernels)) 177 rng = np.random.default_rng(args.seed) 178 a = bf16_round(rng.standard_normal((M, K)).astype(np.float32)) 179 b = bf16_round(rng.standard_normal((K, N)).astype(np.float32)) 180 rows, ok = [], True 181 # ab holds 16*16+16*8 = 384 elements, c holds 128; only the declared shape changes. 182 refused = "omega_matmul refused: status 0 result " 183 for shape, want in (([16, 15, 8], refused + "2"), ([5000, 16, 8], refused + "1"), 184 ([0, 16, 8], refused + "1"), ([12, 16, 12], refused + "3")): 185 try: 186 model.execute(*inputs("omega", a, b, shape)) 187 got = "returned" 188 except Exception as e: # MAX surfaces the glue's raise as an execution error 189 got = str(e) or repr(e) 190 hit = want in got 191 ok &= hit 192 rows.append(dict(shape=shape, want=want, got=got, result="PASS" if hit else "FAIL")) 193 print(f"shape={shape} want '{want}' got: {got} -> {'PASS' if hit else 'FAIL'}", flush=True) 194 # The refused calls must leave the model usable and correct. 195 c = model.execute(*inputs("omega", a, b, [M, K, N]))[0].to_numpy() 196 ratio, _ = judge(c, a.astype(np.float64) @ b.astype(np.float64), a, b, TOL[K][0]) 197 ok &= ratio <= 1.0 198 rows.append(dict(after_refusals="valid call", ratio_ref=ratio, result="PASS" if ratio <= 1 else "FAIL")) 199 print(f"valid call after refusals ratio_ref={ratio:.3g} {'PASS' if ratio <= 1 else 'FAIL'}") 200 try: 201 dev = DeviceRef.CPU() 202 Graph("om_bad_matmul", forward=lambda x, y: ops.matmul(x, y), 203 input_types=[TensorType(DType.float32, [16, 16], dev), TensorType(DType.float32, [15, 8], dev)]) 204 got, hit = "constructed", False 205 except Exception as e: 206 got, hit = str(e).strip().splitlines()[0], True 207 ok &= hit 208 rows.append(dict(graph="ops.matmul [16,16]x[15,8]", got=got, result="PASS" if hit else "FAIL")) 209 print(f"graph construction ops.matmul [16,16]x[15,8]: {got} -> {'PASS' if hit else 'FAIL'}") 210 pathlib.Path(args.out).write_text(json.dumps(rows, indent=1)) 211 print("OMEGA_MAX_NEG_SHAPE:", "PASS" if ok else "FAIL") 212 return 0 if ok else 1 213 214 215 def cmd_neg_load(args): 216 """Expect the kernels dir to fail (load or execute) with `args.want` in the error.""" 217 load_omega(args.lib) 218 M, K, N = 16, 16, 8 219 a, b = np.ones((M, K), np.float32), np.ones((K, N), np.float32) 220 try: 221 model = session().load(build_graph("omega", M, K, N, args.kernels)) 222 model.execute(*inputs("omega", a, b, [M, K, N])) 223 got = "ran" 224 except Exception as e: 225 got = str(e) 226 hit = args.want in got 227 print(f"kernels={args.kernels}\nwant '{args.want}'\ngot: {got}") 228 print("OMEGA_MAX_NEG_LOAD:", "PASS" if hit else "FAIL") 229 return 0 if hit else 1 230 231 232 def cmd_measure(args): 233 load_omega(args.lib) 234 M, K, N = args.shape 235 rng = np.random.default_rng(args.seed) 236 a = bf16_round(rng.standard_normal((M, K)).astype(np.float32)) 237 b = bf16_round(rng.standard_normal((K, N)).astype(np.float32)) 238 model = session().load(build_graph(args.op, M, K, N, args.kernels)) 239 ins = inputs(args.op, a, b, [M, K, N]) 240 u16 = max_mods()[2].uint16 241 # numpy has no bf16: the concat-only graph's output is read back through a uint16 view. 242 done = (lambda o: o[0].view(u16).to_numpy()) if args.op == "concat" else (lambda o: o[0].to_numpy()) 243 done(model.execute(*ins)) 244 first = time.monotonic_ns() 245 for _ in range(args.warmup): 246 done(model.execute(*ins)) 247 lat = [] 248 for _ in range(args.iters): 249 t = time.perf_counter_ns() 250 done(model.execute(*ins)) 251 lat.append(time.perf_counter_ns() - t) 252 rec = dict(op=args.op, shape=[M, K, N], cache=args.cache, cold_ns=first - args.t0, 253 iters=args.iters, warmup=args.warmup, lat_ns=lat, 254 p50_ns_numpy=float(np.percentile(lat, 50)), p99_ns_numpy=float(np.percentile(lat, 99)), 255 maxrss_kib=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss, 256 affinity=sorted(os.sched_getaffinity(0))) 257 pathlib.Path(args.out).write_text(json.dumps(rec)) 258 print(f"{args.op} {M}x{K}x{N} cache={args.cache} cold_ms={rec['cold_ns']/1e6:.1f} " 259 f"p50_us={rec['p50_ns_numpy']/1e3:.2f} p99_us={rec['p99_ns_numpy']/1e3:.2f} " 260 f"maxrss_kib={rec['maxrss_kib']}", flush=True) 261 return 0 262 263 264 def cmd_measure_all(args): 265 out = pathlib.Path(args.out) 266 out.mkdir(parents=True, exist_ok=True) 267 rows = [] 268 for M, K, N in ((16, 16, 8), (256, 256, 256)): 269 for op in ("omega", "omega_nocat", "concat", "matmul"): 270 cache = out / f"cache-{op}-{M}x{K}x{N}" 271 for state in ("fresh", "warm"): 272 if state == "fresh": 273 subprocess.run(["rm", "-rf", str(cache)], check=True) 274 f = out / f"{op}-{M}x{K}x{N}-{state}.json" 275 env = dict(os.environ, MODULAR_CACHE_DIR=str(cache)) 276 cmd = [sys.executable, __file__, "measure", "--lib", str(args.lib), "--kernels", 277 str(args.kernels), "--op", op, "--shape", str(M), str(K), str(N), 278 "--iters", str(args.iters), "--cache", state, "--out", str(f), 279 "--t0", str(time.monotonic_ns())] 280 subprocess.run(cmd, check=True, env=env) 281 r = json.loads(f.read_text()) 282 rows.append([op, f"{M}x{K}x{N}", state, r["cold_ns"], r["iters"], 283 r["p50_ns_numpy"], r["p99_ns_numpy"], r["maxrss_kib"]]) 284 head = ["op", "shape", "cache", "cold_ns", "iters", "p50_ns", "p99_ns", "maxrss_kib"] 285 (out / "summary.tsv").write_text("\n".join("\t".join(map(str, x)) for x in [head] + rows) + "\n") 286 print((out / "summary.tsv").read_text()) 287 return 0 288 289 290 def main(): 291 p = argparse.ArgumentParser() 292 sub = p.add_subparsers(dest="cmd", required=True) 293 for name in ("check", "neg-shape", "neg-load", "measure", "measure-all"): 294 s = sub.add_parser(name) 295 s.add_argument("--lib", required=True) 296 s.add_argument("--kernels", default=str(HERE / "kernels")) 297 s.add_argument("--seed", type=int, default=`20261030`) 298 s.add_argument("--out", required=name != "neg-load") 299 if name == "neg-load": 300 s.add_argument("--want", required=True) 301 if name in ("measure", "measure-all"): 302 s.add_argument("--iters", type=int, default=300) 303 if name == "measure": 304 s.add_argument("--op", required=True, 305 choices=["omega", "omega_nocat", "concat", "matmul"]) 306 s.add_argument("--shape", type=int, nargs=3, required=True) 307 s.add_argument("--warmup", type=int, default=20) 308 s.add_argument("--cache", default="fresh") 309 s.add_argument("--t0", type=int, required=True) 310 a = p.parse_args() 311 # MAX 26.7.0 Graph() creates an Accelerator() (a CUDA context) whenever one is visible, even 312 # for an all-CPU graph. Refuse unless the GPU is hidden: run.sh exports CUDA_VISIBLE_DEVICES=. 313 from max.driver import accelerator_count 314 315 if accelerator_count() != 0: 316 print("omega_max.py: an accelerator is visible; export CUDA_VISIBLE_DEVICES= " 317 "(this harness must not open the GPU)", file=sys.stderr) 318 sys.exit(2) 319 fn = {"check": cmd_check, "neg-shape": cmd_neg_shape, "neg-load": cmd_neg_load, 320 "measure": cmd_measure, "measure-all": cmd_measure_all}[a.cmd] 321 sys.exit(fn(a)) 322 323 324 if __name__ == "__main__": 325 main()