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/conformance/max_runner.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 / conformance / max_runner.py` 198 lines ยท 7654 bytes Raw Blame History 1 #!/usr/bin/env python3 2 # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 3 """MAX-side conformance runner for the frozen matmul and causal GQA contracts. 4 5 Reads one fixture generated by conformance/oracle.py, builds a MAX graph, runs 6 it in a separate process, and writes raw f32 output plus run metadata. The 7 oracle is deliberately not called here: conformance/verify.py is the independent 8 judge. A CPU run validates the harness only; a GPU run is device evidence and 9 must carry the Spark window identifier. 10 11 max_runner.py --fixture F.json --device cpu|gpu --out PREFIX 12 """ 13 import argparse 14 import json 15 import math 16 import os 17 import struct 18 import sys 19 import time 20 21 sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) 22 import oracle # noqa: E402 23 24 import numpy as np # noqa: E402 25 from max.driver import Accelerator, CPU, Buffer # noqa: E402 26 from max.dtype import DType # noqa: E402 27 from max.engine import InferenceSession # noqa: E402 28 from max.graph import DeviceRef, Graph, TensorType, ops # noqa: E402 29 30 31 def f32_from_hex(items): 32 return np.array([oracle.f32_from_bits(int(x, 16)) for x in items], dtype=np.float32) 33 34 35 def bf16_from_hex(items): 36 return np.array([oracle.bf16_from_bits(int(x, 16)) for x in items], dtype=np.float32) 37 38 39 def matmul_graph(m, k, n, dev): 40 dt = DeviceRef.from_device(dev) 41 return Graph( 42 "omega-matmul-bf16-v1", 43 input_types=[ 44 TensorType(DType.float32, [m, k], device=dt), 45 TensorType(DType.float32, [k, n], device=dt), 46 ], 47 # Operands are exact bf16 values carried in f32. This is the contract's 48 # fp32-accumulation path; MAX's bf16 output dtype would round the result 49 # before the contract's f32 comparison. Recorded in metadata. 50 forward=lambda a, b: ops.matmul(a, b), 51 ) 52 53 54 def attention_graph(r, t, hq, hkv, hd, base, dev): 55 group = hq // hkv 56 dt = DeviceRef.from_device(dev) 57 def forward(q, k, v, mask): 58 scale = ops.constant(1.0 / math.sqrt(hd), DType.float32, device=dt) 59 kk = ops.repeat_interleave(k, group, axis=1) # [T, Hq, D] 60 vv = ops.transpose(ops.repeat_interleave(v, group, axis=1), 0, 1) # [Hq, T, D] 61 kt = ops.transpose(ops.transpose(kk, 0, 1), 1, 2) # [Hq, D, T] 62 qt = ops.transpose(q, 0, 1) # [Hq, R, D] 63 scores = ops.mul(ops.matmul(qt, kt), scale) # [Hq, R, T] 64 m = ops.broadcast_to(ops.reshape(mask, [1, r, t]), scores.shape) 65 probs = ops.softmax(ops.add(scores, m), -1) 66 return ops.transpose(ops.matmul(probs, vv), 0, 1) # [R, Hq, D] 67 68 return Graph( 69 "omega-gqa-causal-v1", 70 input_types=[ 71 TensorType(DType.float32, [r, hq, hd], device=dt), 72 TensorType(DType.float32, [t, hkv, hd], device=dt), 73 TensorType(DType.float32, [t, hkv, hd], device=dt), 74 TensorType(DType.float32, [r, t], device=dt), 75 ], 76 forward=forward, 77 ) 78 79 80 def main(): 81 ap = argparse.ArgumentParser() 82 ap.add_argument("--fixture", required=True) 83 ap.add_argument("--device", choices=["cpu", "gpu"], default="cpu") 84 ap.add_argument("--out", required=True) 85 args = ap.parse_args() 86 87 if args.device == "gpu": 88 # Refuse before constructing Accelerator: construction itself opens the 89 # reserved chip (REVIEW B-01). 90 if os.environ.get("SPARK_WINDOW") is None: 91 print("gpu run refused: SPARK_WINDOW is not set (no authorized window)", file=sys.stderr) 92 return 3 93 dev = Accelerator() 94 else: 95 # MAX 26.7.0 Graph() creates an Accelerator() (a CUDA context) whenever one is 96 # visible, even for an all-CPU graph (max-cpu/run.sh). A CPU run must not open 97 # the chip, so refuse unless the GPU is hidden: run.sh exports 98 # CUDA_VISIBLE_DEVICES= for its CPU calls. 99 from max.driver import accelerator_count 100 101 if accelerator_count() != 0: 102 print("cpu run refused: an accelerator is visible; export CUDA_VISIBLE_DEVICES= " 103 "(a CPU run must not open the GPU)", file=sys.stderr) 104 return 2 105 dev = CPU() 106 f = json.load(open(args.fixture)) 107 session = InferenceSession(devices=[dev]) 108 t0 = time.perf_counter() 109 110 if f["name"] == "matmul-v1": 111 m, k, n = (f["shape"][x] for x in ("m", "k", "n")) 112 a = bf16_from_hex(f["inputs"]["a"]).reshape(m, k) 113 b = bf16_from_hex(f["inputs"]["b"]).reshape(k, n) 114 model = session.load(matmul_graph(m, k, n, dev)) 115 # Buffer.from_numpy places the data on the host; a GPU graph refuses host 116 # inputs ("expected argument 0 to be on device gpu"), so move them first, 117 # outside the timed execute. .to() is a no-op for a CPU device. 118 ins = [Buffer.from_numpy(x).to(dev) for x in (a, b)] 119 t_compile = time.perf_counter() - t0 120 t1 = time.perf_counter() 121 out = model.execute(*ins)[0].to_numpy() 122 t_run = time.perf_counter() - t1 123 flat = out.astype(np.float32).ravel() 124 shape = [m, n] 125 elif f["name"] == "gqa-causal-v1": 126 s = f["shape"] 127 r, base, t, hq, hkv, hd = s["r"], s["base"], s["t"], s["hq"], s["hkv"], s["head_dim"] 128 q = f32_from_hex(f["inputs"]["q"]).reshape(r, hq, hd) 129 kk = f32_from_hex(f["inputs"]["k"]).reshape(t, hkv, hd) 130 vv = f32_from_hex(f["inputs"]["v"]).reshape(t, hkv, hd) 131 mask = np.full((r, t), -np.inf, dtype=np.float32) 132 for i in range(r): 133 for j in range(t): 134 if j <= base + i: 135 mask[i, j] = 0.0 136 model = session.load(attention_graph(r, t, hq, hkv, hd, base, dev)) 137 ins = [Buffer.from_numpy(x).to(dev) for x in (q, kk, vv, mask)] 138 t_compile = time.perf_counter() - t0 139 t1 = time.perf_counter() 140 out = model.execute(*ins)[0].to_numpy() 141 t_run = time.perf_counter() - t1 142 flat = out.astype(np.float32).ravel() 143 shape = [r, hq, hd] 144 else: 145 print(f"unknown fixture {f['name']}", file=sys.stderr) 146 return 2 147 148 with open(args.out + ".bin", "wb") as fp: 149 fp.write(struct.pack("<%df" % flat.size, *[float(x) for x in flat])) 150 meta = { 151 "runner": "modular-max", 152 "device": args.device, 153 "shape": shape, 154 "contract_id": f["contract_id"], 155 "max_version": _max_version(), 156 "accelerator_api": _api() if args.device == "gpu" else "cpu", 157 "compile_seconds": t_compile, 158 "execute_seconds": t_run, 159 "spark_window": os.environ.get("SPARK_WINDOW"), 160 "numeric_path": "fp32-mul-add (exact for this fixture)" if f["name"] == "matmul-v1" else "fp32-softmax", 161 "output_sha256": _sha(args.out + ".bin"), 162 } 163 with open(args.out + ".json", "w") as fp: 164 json.dump(meta, fp, indent=2, sort_keys=True) 165 fp.write("\n") 166 print(json.dumps(meta, sort_keys=True)) 167 return 0 168 169 170 def _max_version(): 171 try: 172 import max as m 173 version = getattr(m, "__version__", None) 174 # The requested release is not evidence of the installed release. 175 return version if isinstance(version, str) and version.strip() else "unknown" 176 except Exception: 177 return "unknown" 178 179 180 def _api(): 181 try: 182 from max.driver import accelerator_api 183 return accelerator_api() 184 except Exception: 185 return "unknown" 186 187 188 def _sha(path): 189 import hashlib 190 h = hashlib.sha256() 191 with open(path, "rb") as f: 192 for b in iter(lambda: f.read(1 << 20), b""): 193 h.update(b) 194 return h.hexdigest() 195 196 197 if __name__ == "__main__": 198 sys.exit(main())