interplane.Get Omega
Read in your language

omega-gpu-bench

First-party Omega GPU kernel benchmark harness and receipts

Brought by drakestapleton

branch main Branches Tags History

omega-gpu-bench / tools / validate.py

270 lines · 14419 bytes Raw Blame History
1#!/usr/bin/env python3
2# tools/validate.py -- check receipts. A receipt is self-reported: nothing here can re-run someone's GPU.
3# What it does check, from public inputs alone:
4# * the receipt hash covers every field (an edit after ./run breaks it unless the editor re-seals it,
5# which the rules below then have to survive);
6# * each kernel's sha256 equals kernels/SHA256SUMS at the kit commit the receipt names, and that commit
7# is in this repository's history; the kit was unmodified;
8# * the receipt lists exactly the kernels its GPU's compute capability can load (no dropped failures);
9# * every count is the fixed n = 2^20 + 7, and each verdict agrees with its mismatch count;
10# * every reported reference value in first_bad is recomputed here from the public seed, and every
11# reported GPU value differs from it; a clean run's output hash must equal the reference's hash;
12# * GB/s is recomputed from the kernel time; the libcuda label and the sign-off are present;
13# * imported CloudKernels runs are accepted only if their hash is on receipts/imports.sha256, and their
14# kernels are checked against kernels/WITHDRAWN.sha256 (the cubins they ran, since withdrawn);
15# * a kit run of a withdrawn kernel is rejected, whatever kit commit it names;
16# * receipts made with the test fixture driver are rejected (tests use --allow-fake).
17# INTERIM host glue (Python); Omega successor: an omc-built checker, see DEPENDENCIES.md.
18import argparse, hashlib, json, os, random, re, subprocess, sys
19from array import array
20
21sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
22import receipt as R # noqa: E402
23
24HEX64, HEX40 = re.compile(r"[0-9a-f]{64}"), re.compile(r"[0-9a-f]{40}")
25TOP = {"schema", "origin", "path", "provider", "kit", "machine", "run", "submitter", "results", "not_run",
26 "evidence", "receipt_sha256"}
27KIT_KEYS = {"repo", "commit", "modified", "kernels_sha256sums"}
28MACHINE_KEYS = {"gpu", "cc", "cuda_driver_api", "driver_version", "nvrm", "os", "kernel", "arch", "cpu"}
29RUN_KEYS = {"utc", "driver", "python"}
30RAN = {"PASS", "WRONG", "NEG_DETECTED", "NEG_MISSED"}
31FAILED = {"INIT_FAIL", "LOAD_FAIL", "RUN_FAIL", "HARNESS_CRASH"}
32_ref = {}
33
34
35def reference():
36 if not _ref:
37 rng = random.Random(R.SEED)
38 a = [rng.getrandbits(32) for _ in range(R.N)]
39 b = [rng.getrandbits(32) for _ in range(R.N)]
40 ref = array("I", ((x + y) & 0xFFFFFFFF for x, y in zip(a, b)))
41 if sys.byteorder != "little":
42 ref.byteswap()
43 _ref["sha"] = hashlib.sha256(ref.tobytes()).hexdigest()
44 if sys.byteorder != "little":
45 ref.byteswap()
46 _ref["ref"] = ref
47 return _ref
48
49
50def git(repo, *args):
51 p = subprocess.run(["git", "-C", repo, *args], capture_output=True)
52 return p.stdout if p.returncode == 0 else None
53
54
55class Checker:
56 def __init__(self, repo, sums_path, imports_path, allow_fake):
57 self.repo, self.allow_fake = repo, allow_fake
58 self.sums_text = open(sums_path).read()
59 withdrawn = os.path.join(os.path.dirname(sums_path), "WITHDRAWN.sha256")
60 self.withdrawn_text = open(withdrawn).read() if os.path.exists(withdrawn) else ""
61 self.withdrawn = set(R.parse_sums(self.withdrawn_text).values())
62 self.imports = set()
63 if os.path.exists(imports_path):
64 self.imports = {l.split()[0] for l in open(imports_path) if l.strip() and not l.startswith("#")}
65 self.is_git = git(repo, "rev-parse", "--git-dir") is not None
66
67 def sums_at(self, commit, errs):
68 if commit is None or not self.is_git:
69 return self.sums_text
70 if git(self.repo, "cat-file", "-e", commit + "^{commit}") is None:
71 errs.append("kit.commit %s is not in %s's history" % (commit, R.REPO))
72 return self.sums_text
73 text = git(self.repo, "show", commit + ":kernels/SHA256SUMS")
74 if text is None:
75 errs.append("kit.commit %s has no kernels/SHA256SUMS" % commit)
76 return self.sums_text
77 return text.decode()
78
79 def check(self, rec):
80 errs = []
81 e = errs.append
82 if not isinstance(rec, dict):
83 return ["not a JSON object"]
84 if set(rec) != TOP:
85 return ["top-level keys differ: missing %s, extra %s" % (sorted(TOP - set(rec)), sorted(set(rec) - TOP))]
86 if rec["schema"] != R.SCHEMA:
87 e("schema is not %s" % R.SCHEMA)
88 if rec["receipt_sha256"] != hashlib.sha256(R.canonical(rec)).hexdigest():
89 e("receipt_sha256 does not match the receipt's contents (edited after it was written)")
90 if rec["path"] != R.PATH_LABEL:
91 e("the libcuda path label is missing or changed")
92 if not isinstance(rec["provider"], str) or not rec["provider"].strip():
93 e("provider is empty")
94 origin = rec["origin"]
95 if origin not in ("kit-run", "cloudkernels-import"):
96 return errs + ["origin must be kit-run or cloudkernels-import"]
97 kit, mach, run, sub = rec["kit"], rec["machine"], rec["run"], rec["submitter"]
98 if not (isinstance(kit, dict) and set(kit) == KIT_KEYS):
99 return errs + ["kit must have exactly %s" % sorted(KIT_KEYS)]
100 if not (isinstance(mach, dict) and set(mach) == MACHINE_KEYS):
101 return errs + ["machine must have exactly %s" % sorted(MACHINE_KEYS)]
102 if not (isinstance(run, dict) and set(run) == RUN_KEYS):
103 return errs + ["run must have exactly %s" % sorted(RUN_KEYS)]
104 if not (isinstance(sub, dict) and set(sub) == {"signed_off_by", "statement"}):
105 return errs + ["submitter must have exactly signed_off_by and statement"]
106 if not (isinstance(sub["signed_off_by"], str) and R.SIGNOFF.fullmatch(sub["signed_off_by"])):
107 e('submitter.signed_off_by must be "Name <email>"')
108 if not re.fullmatch(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ", str(run["utc"])):
109 e("run.utc must be YYYY-MM-DDTHH:MM:SSZ")
110 if run["driver"] == "fake" and not self.allow_fake:
111 e("made with the test fixture driver (tests/fakecuda.py), not a GPU")
112 elif run["driver"] not in ("libcuda", "fake"):
113 e("run.driver must be libcuda")
114 if not (isinstance(mach["gpu"], str) and mach["gpu"]):
115 e("machine.gpu is empty")
116 if not isinstance(mach["cuda_driver_api"], int) or mach["cuda_driver_api"] <= 0:
117 e("machine.cuda_driver_api must be a positive integer")
118 if not re.fullmatch(r"\d+\.\d+", str(mach["cc"])):
119 return errs + ["machine.cc must look like 8.9"]
120
121 if origin == "kit-run":
122 if kit["repo"] != R.REPO:
123 e("kit.repo must be %s" % R.REPO)
124 if not (isinstance(kit["commit"], str) and HEX40.fullmatch(kit["commit"])):
125 e("kit.commit must be a 40-hex commit (run the kit from a git clone)")
126 if kit["modified"] is not False:
127 e("the kit had local changes when it ran")
128 if sub["statement"] != R.STATEMENT:
129 e("submitter.statement is missing or changed")
130 if rec["evidence"] is not None:
131 e("evidence is only for imported runs")
132 sums_text = self.sums_at(kit["commit"] if HEX40.fullmatch(str(kit["commit"])) else None, errs)
133 if kit["kernels_sha256sums"] != hashlib.sha256(sums_text.encode()).hexdigest():
134 e("kit.kernels_sha256sums is not the hash of kernels/SHA256SUMS at kit.commit")
135 else:
136 if rec["receipt_sha256"] not in self.imports:
137 e("imported run is not listed in receipts/imports.sha256")
138 ev = rec["evidence"]
139 if not (isinstance(ev, dict) and isinstance(ev.get("source"), str) and isinstance(ev.get("files"), list)
140 and ev["files"] and all(isinstance(f, dict) and HEX64.fullmatch(str(f.get("sha256")))
141 for f in ev["files"])):
142 e("imported run needs evidence.source and evidence.files [{path, sha256}]")
143 sums_text = self.withdrawn_text
144 sums = R.parse_sums(sums_text)
145
146 rows = rec["results"]
147 if not isinstance(rows, list):
148 return errs + ["results must be a list"]
149 want = R.expected_cubins(mach["cc"], sums)
150 names = [r.get("cubin") for r in rows if isinstance(r, dict)]
151 if len(names) != len(rows) or len(set(names)) != len(names):
152 e("results must be distinct objects")
153 if origin == "kit-run" and sorted(names) != want:
154 e("results list %s but a cc %s GPU must run exactly %s" % (sorted(names), mach["cc"], want))
155 if origin != "kit-run" and (not rows or not set(names) <= set(want)):
156 e("imported results must be kit kernels this GPU can load")
157 if (rec["not_run"] is None) != bool(want):
158 e("not_run must be set exactly when this kit has no kernel for the GPU")
159 for r in rows:
160 if isinstance(r, dict):
161 self.check_row(r, sums, origin, e)
162 if origin == "kit-run" and r.get("cubin_sha256") in self.withdrawn:
163 e("%s: kernel withdrawn from this kit: %s" % (r.get("cubin"), R.WITHDRAWN))
164 return errs
165
166 def check_row(self, r, sums, origin, e):
167 name = r.get("cubin")
168 if set(r) != set(R.ROW_KEYS):
169 e("%s: row keys must be exactly %s" % (name, list(R.ROW_KEYS)))
170 return
171 m = R.CUBIN.fullmatch(str(name))
172 if not m or name not in sums:
173 e("%s: not a kernel of this kit" % name)
174 return
175 if r["cubin_sha256"] != sums[name]:
176 e("%s: cubin_sha256 differs from kernels/SHA256SUMS" % name)
177 if r["kind"] != m.group(1):
178 e("%s: kind must be %s" % (name, m.group(1)))
179 v, kind = r["verdict"], m.group(1)
180 timing = (r["kernel_ms"], r["gbps"], r["timing_n"])
181 if v in FAILED:
182 if not (isinstance(r["error"], str) and r["error"]):
183 e("%s: %s needs the error text" % (name, v))
184 if any(r[k] is not None for k in ("checked", "mismatches", "first_bad", "output_sha256")) or \
185 any(t is not None for t in timing):
186 e("%s: %s cannot carry results" % (name, v))
187 return
188 if v not in RAN:
189 e("%s: unknown verdict %r" % (name, v))
190 return
191 if (kind == "vecadd") != (v in ("PASS", "WRONG")):
192 e("%s: verdict %s does not belong to a %s kernel" % (name, v, kind))
193 if r["error"] is not None:
194 e("%s: a kernel that ran has no error" % name)
195 if r["checked"] != R.N:
196 e("%s: checked must be %d" % (name, R.N))
197 mm = r["mismatches"]
198 if not (isinstance(mm, int) and not isinstance(mm, bool) and 0 <= mm <= R.N):
199 e("%s: mismatches must be an integer 0..%d" % (name, R.N))
200 return
201 if (mm == 0) != (v in ("PASS", "NEG_MISSED")):
202 e("%s: verdict %s contradicts %d mismatches" % (name, v, mm))
203 fb = r["first_bad"]
204 if not (isinstance(fb, list) and len(fb) == min(3, mm)):
205 e("%s: first_bad must list the first min(3, mismatches) words" % name)
206 else:
207 ref = reference()["ref"]
208 last = -1
209 for t in fb:
210 if not (isinstance(t, list) and len(t) == 3 and all(isinstance(x, int) for x in t)
211 and last < t[0] < R.N):
212 e("%s: bad first_bad entry %r" % (name, t))
213 break
214 last = t[0]
215 if t[2] != ref[t[0]]:
216 e("%s: first_bad reference at %d is %d, recomputed %d" % (name, t[0], t[2], ref[t[0]]))
217 if t[1] == t[2]:
218 e("%s: first_bad at %d is not a mismatch" % (name, t[0]))
219 osha = r["output_sha256"]
220 if origin == "kit-run":
221 if not (isinstance(osha, str) and HEX64.fullmatch(osha)):
222 e("%s: output_sha256 is required" % name)
223 elif (osha == reference()["sha"]) != (mm == 0):
224 e("%s: output_sha256 %s the reference output but mismatches = %d"
225 % (name, "equals" if osha == reference()["sha"] else "differs from", mm))
226 elif osha is not None:
227 e("%s: imported runs have no output_sha256" % name)
228 if origin == "kit-run" and v == "PASS":
229 if r["timing_error"] is not None:
230 if any(t is not None for t in timing):
231 e("%s: timing_error and a timing together" % name)
232 else:
233 kms, gbps, nt = timing
234 if nt != R.NT or not isinstance(kms, (int, float)) or kms <= 0 or not isinstance(gbps, (int, float)):
235 e("%s: PASS needs timing_n = %d, kernel_ms > 0 and gbps (or timing_error)" % (name, R.NT))
236 elif abs(gbps - round(12 * R.NT / (kms * 1e6), 3)) > 0.0015:
237 e("%s: gbps %s is not 12 * %d bytes / %s ms" % (name, gbps, R.NT, kms))
238 elif any(t is not None for t in timing) or r["timing_error"] is not None:
239 e("%s: only a kit-run PASS carries timing" % name)
240
241
242def main():
243 root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
244 ap = argparse.ArgumentParser(description="Validate omega-gpu-bench receipts.")
245 ap.add_argument("files", nargs="+")
246 ap.add_argument("--repo", default=root, help="git checkout used to resolve kit.commit")
247 ap.add_argument("--sums", default=os.path.join(root, "kernels", "SHA256SUMS"))
248 ap.add_argument("--imports", default=os.path.join(root, "receipts", "imports.sha256"))
249 ap.add_argument("--allow-fake", action="store_true", help="tests only: accept the fixture driver")
250 o = ap.parse_args()
251 c = Checker(o.repo, o.sums, o.imports, o.allow_fake)
252 bad = 0
253 for path in o.files:
254 try:
255 errs = c.check(json.load(open(path)))
256 except (OSError, ValueError) as x:
257 errs = ["unreadable: %s" % x]
258 if errs:
259 bad += 1
260 print("REJECT %s" % path)
261 for msg in errs:
262 print(" - " + msg)
263 else:
264 print("VALID %s" % path)
265 print("%d valid, %d rejected" % (len(o.files) - bad, bad))
266 return 1 if bad else 0
267
268
269if __name__ == "__main__":
270 sys.exit(main())