interplane.Get Omega
Read in your language

omega-bridge

Omega-first language interoperability: checked conversion backends and native language bindings

Brought by drakestapleton

branch main Branches Tags History

omega-bridge / conformance / verify.py

121 lines · 4851 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3"""Independent judge for one conformance run.
4
5Reads the frozen fixture, checks every declared input checksum, reads the raw
6f32 output a runner wrote, and compares it with the oracle from oracle.py. It
7also proves the detector is not vacuous: a scaled output, a swapped element and
8(for attention) the wrong head map must all fail.
9
10 verify.py --fixture F.json --result PREFIX [--expect-device cpu|gpu]
11"""
12import argparse
13import json
14import os
15import struct
16import sys
17
18sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
19import oracle # noqa: E402
20
21
22
23def bits16(items):
24 return [oracle.bf16_from_bits(int(x, 16)) for x in items]
25
26
27def bits32(items):
28 return [oracle.f32_from_bits(int(x, 16)) for x in items]
29
30
31def read_f32(path):
32 with open(path, "rb") as f:
33 b = f.read()
34 if len(b) % 4:
35 raise ValueError("output is not a multiple of 4 bytes")
36 return list(struct.unpack("<%df" % (len(b) // 4), b))
37
38
39def main():
40 ap = argparse.ArgumentParser()
41 ap.add_argument("--fixture", required=True)
42 ap.add_argument("--result", required=True)
43 ap.add_argument("--expect-device", default=None)
44 args = ap.parse_args()
45 f = json.load(open(args.fixture))
46 meta = json.load(open(args.result + ".json"))
47 checks = 0
48 fails = 0
49
50 def check(cond, msg):
51 nonlocal checks, fails
52 checks += 1
53 if not cond:
54 fails += 1
55 print("FAIL:", msg)
56
57 if args.expect_device:
58 check(meta.get("device") == args.expect_device, f"device {meta.get('device')} != {args.expect_device}")
59 check(meta.get("contract_id") == f["contract_id"], "runner contract id mismatch")
60 check(meta.get("runner") in ("modular-max", "omega-native"), "unknown runner")
61 raw = open(args.result + ".bin", "rb").read()
62 import hashlib
63 check(hashlib.sha256(raw).hexdigest() == meta.get("output_sha256"), "output digest mismatch")
64 if meta.get("device") == "gpu":
65 check(bool(meta.get("spark_window")), "GPU result has no SPARK_WINDOW identifier")
66
67 max_abs = None
68 if f["name"] == "matmul-v1":
69 for key in ("a", "b"):
70 check(oracle.input_checksum(f["inputs"][key]) == f["input_sha256"][key],
71 f"input {key} checksum stale")
72 m, k, n = (f["shape"][x] for x in ("m", "k", "n"))
73 ref = oracle.matmul_bf16_ref(
74 [int(x, 16) for x in f["inputs"]["a"]],
75 [int(x, 16) for x in f["inputs"]["b"]], m, k, n)
76 got = read_f32(args.result + ".bin")
77 check(len(got) == m * n, f"output length {len(got)} != {m*n}")
78 check(oracle.matmul_matches(got, ref), "output does not match the fp64 reference")
79 max_abs = max((abs(int(a) - int(b)) for a, b in zip(got, ref)), default=0)
80 check(meta.get("shape") == [m, n], "runner shape mismatch")
81 mut = list(got)
82 mut[0] = mut[0] * 1.01 + (1e-3 if mut[0] == 0 else 0.0)
83 check(not oracle.matmul_matches(mut, ref), "detector missed a 1% output mutation")
84 if len(mut) > 1:
85 mut = list(got)
86 mut[0], mut[1] = mut[1], mut[0]
87 check(not oracle.matmul_matches(mut, ref), "detector missed a swapped element")
88 elif f["name"] == "gqa-causal-v1":
89 for key in ("q", "k", "v"):
90 check(oracle.input_checksum(f["inputs"][key]) == f["input_sha256"][key],
91 f"input {key} checksum stale")
92 s = f["shape"]
93 q = bits32(f["inputs"]["q"]); k = bits32(f["inputs"]["k"]); v = bits32(f["inputs"]["v"])
94 ref = oracle.attention_ref(q, k, v, s["base"], s["hq"], s["hkv"], s["head_dim"])
95 got = read_f32(args.result + ".bin")
96 check(len(got) == len(ref), f"output length {len(got)} != {len(ref)}")
97 check(oracle.attention_matches(got, ref), "output does not match the fp64 reference")
98 max_abs = max((abs(a - b) for a, b in zip(got, ref)), default=0.0)
99 check(meta.get("shape") == [s["r"], s["hq"], s["head_dim"]], "runner shape mismatch")
100 wrong = oracle.attention_ref(q, k, v, s["base"], s["hq"], s["hkv"], s["head_dim"], head_map="mod")
101 check(not oracle.attention_matches(got, wrong), "detector missed the wrong head map")
102 mut = [x * 1.01 for x in got]
103 check(not oracle.attention_matches(mut, ref), "detector missed a 1% output mutation")
104 else:
105 check(False, "unknown fixture name")
106
107 summary = {
108 "max_abs_error": max_abs,
109 "runner": meta.get("runner"),
110 "device": meta.get("device"),
111 "fixture": f["name"],
112 "contract_id": f["contract_id"],
113 "checks": checks,
114 "fail": fails,
115 }
116 print(json.dumps(summary, sort_keys=True))
117 return 1 if fails else 0
118
119
120if __name__ == "__main__":
121 sys.exit(main())