nki-kernel-bench / tools /validate.py
jburtoft's picture
nki-kernel-bench v0.1
0fef070
Raw History Blame Contribute Delete
10.5 kB
"""Validate dataset entries against schema/ and the cross-field rules in FORMAT.md.
Usage: python tools/validate.py [dataset_dir ...] (exit 1 on any error)
"""
import ast, hashlib, json, os, re, subprocess, sys
import jsonschema
import yaml
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SCHEMA = {n: json.load(open(os.path.join(ROOT, "schema", f"{n}.schema.json")))
for n in ("family", "manifest", "parity", "timing", "multicore")}
# Hygiene: internal hosts and identifiers must never ship.
FORBIDDEN = [
(re.compile(r"git\.amazon\.com|code\.amazon\.com|gitlab\.aws\.dev|\.corp\.amazon\.com|amazon\.com/"), "internal URL"),
(re.compile(r"\bi-0[0-9a-f]{8,16}\b"), "instance id"),
(re.compile(r"\bcr-0[0-9a-f]{8,16}\b"), "capacity reservation id"),
(re.compile(r"\b\d{12}\b(?=.*(arn|account))", re.I), "account id"),
(re.compile(r"\barn:aws:"), "ARN"),
(re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b(?<!0\.0\.0\.0)"), "IP address"),
(re.compile(r"\b[VPT]\d{9,10}\b"), "ticket id"),
]
TEXT_EXT = {".py", ".yaml", ".yml", ".md", ".json", ".txt"}
# Optional local hygiene config (not shipped). Path: $NKB_HYGIENE_FILE, else <root>/.nkb_hygiene.
# Format, one item per line ('#' comments allowed):
# <regex> extra forbidden pattern (reported as "internal name"; the match is not printed)
# registry: <dir> directory of *.md registry files with a "**Customer**: <name>" line; the
# customer names and their file stems become forbidden patterns as well
# $NKB_REGISTRY_DIR overrides the registry directory. Without a config only the generic checks run.
HYGIENE_FILE = os.environ.get("NKB_HYGIENE_FILE") or os.path.join(ROOT, ".nkb_hygiene")
def _local_hygiene():
pats, registry = [], os.environ.get("NKB_REGISTRY_DIR")
if os.path.isfile(HYGIENE_FILE):
for ln in open(HYGIENE_FILE, errors="ignore").read().splitlines():
ln = ln.strip()
if not ln or ln.startswith("#"):
continue
if ln.startswith("registry:"):
p = os.path.expanduser(ln.split(":", 1)[1].strip())
registry = registry or (p if os.path.isabs(p) else os.path.join(os.path.dirname(HYGIENE_FILE), p))
else:
pats.append(re.compile(ln))
return pats, registry
LOCAL_PATTERNS, REGISTRY = _local_hygiene()
def _confidential_patterns():
"""Confidential names read at runtime from the optional local registry (never written anywhere).
Empty when no registry is configured (public copy)."""
pats = list(LOCAL_PATTERNS)
if not REGISTRY or not os.path.isdir(REGISTRY):
return pats
for f in os.listdir(REGISTRY):
if not f.endswith(".md") or f.startswith(("_", "README")):
continue
m = re.search(r"^\*\*Customer\*\*:\s*(.+)$", open(os.path.join(REGISTRY, f), errors="ignore").read(), re.M)
if not m:
continue
val = m.group(1).strip()
if re.match(r"(?i)(n/a|none|tbd|-)\b", val):
continue
name = re.split(r"\s+--|\s+\(|,|;", val)[0].strip(" *`")
for tok in {name, f[:-3]}:
if len(tok) >= 4:
pats.append(re.compile(r"(?i)(?<![A-Za-z0-9])" + re.escape(tok) + r"(?![A-Za-z0-9])"))
for part in re.split(r"[-_ ]", f[:-3]): # codename components such as "<name>-troubleshooting"
if len(part) >= 5 and part.lower() == name.lower()[:len(part)].lower():
pats.append(re.compile(r"(?i)(?<![A-Za-z0-9])" + re.escape(part) + r"(?![A-Za-z0-9])"))
return pats
CONFIDENTIAL = _confidential_patterns()
def sha(p):
return hashlib.sha256(open(p, "rb").read()).hexdigest()
def jit_functions(src):
out = set()
for n in ast.walk(ast.parse(src)):
if isinstance(n, ast.FunctionDef):
for d in n.decorator_list:
t = d.func if isinstance(d, ast.Call) else d
if (isinstance(t, ast.Attribute) and t.attr == "jit") or (isinstance(t, ast.Name) and t.id == "jit"):
out.add(n.name)
return out
def numpy_only(fam_dir):
"""Import inputs.py + reference.py in a clean interpreter; fail if torch/nki get imported."""
code = ("import sys, importlib.util\n"
f"sys.path.insert(0, {fam_dir!r})\n"
"import inputs, reference\n"
"bad = sorted(m for m in sys.modules if m.split('.')[0] in ('torch', 'nki', 'neuronxcc', 'jax'))\n"
"assert hasattr(inputs, 'make_inputs') and hasattr(reference, 'reference')\n"
"print(','.join(bad))\n")
r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)
if r.returncode:
return f"inputs/reference import failed: {r.stderr.strip().splitlines()[-1] if r.stderr.strip() else r.returncode}"
return f"inputs/reference import non-numpy modules: {r.stdout.strip()}" if r.stdout.strip() else None
def hygiene(path, errs):
if os.path.splitext(path)[1] not in TEXT_EXT:
return
txt = open(path, errors="ignore").read()
for rx, what in FORBIDDEN:
m = rx.search(txt)
if m:
errs.append(f"{path}: {what} found ({m.group(0)[:40]!r})")
for rx in CONFIDENTIAL:
if rx.search(txt):
errs.append(f"{path}: confidential/internal name found (pattern redacted)")
def check_family(fd, errs):
fy = os.path.join(fd, "family.yaml")
fam = yaml.safe_load(open(fy))
for e in jsonschema.Draft202012Validator(SCHEMA["family"]).iter_errors(fam):
errs.append(f"{fy}: {e.json_path}: {e.message}")
if fam.get("family") != os.path.basename(fd):
errs.append(f"{fy}: family {fam.get('family')!r} != dir {os.path.basename(fd)!r}")
for f in ("inputs.py", "reference.py"):
if not os.path.isfile(os.path.join(fd, f)):
errs.append(f"{fd}: missing {f}")
if not any(e.startswith(fd) and "missing" in e for e in errs):
m = numpy_only(fd)
if m:
errs.append(f"{fd}: {m}")
shape_ids = {s["id"] for s in fam.get("shapes", [])}
orders, n = {}, 0
for v in sorted(os.listdir(fd)):
vd = os.path.join(fd, v)
if not os.path.isdir(vd) or v in ("__pycache__",):
continue
n += 1
mf = os.path.join(vd, "manifest.yaml")
if not os.path.isfile(mf):
errs.append(f"{vd}: missing manifest.yaml"); continue
m = yaml.safe_load(open(mf))
for e in jsonschema.Draft202012Validator(SCHEMA["manifest"]).iter_errors(m):
errs.append(f"{mf}: {e.json_path}: {e.message}")
if m.get("id") != f"{fam['family']}/{v}" or m.get("version") != v or m.get("family") != fam["family"]:
errs.append(f"{mf}: id/version/family inconsistent with path")
o = m.get("order")
if o in orders:
errs.append(f"{mf}: order {o} duplicates {orders[o]}")
orders[o] = v
kp = os.path.join(vd, "kernel.py")
if not os.path.isfile(kp):
errs.append(f"{vd}: missing kernel.py"); continue
port, prov = m.get("port", {}), m.get("provenance", {})
if port.get("kernel_sha256") != sha(kp):
errs.append(f"{mf}: port.kernel_sha256 != sha256(kernel.py)")
if port.get("status") == "verbatim":
if port.get("kernel_sha256") != prov.get("source_sha256"):
errs.append(f"{mf}: verbatim but kernel_sha256 != provenance.source_sha256")
if port.get("notes"):
errs.append(f"{mf}: verbatim with port notes")
if port.get("status") == "ported" and not port.get("notes"):
errs.append(f"{mf}: ported without port notes")
fn = m.get("entry", {}).get("function")
if fn not in jit_functions(open(kp).read()):
errs.append(f"{mf}: entry.function {fn!r} is not an @nki.jit function in kernel.py")
sh = m.get("shapes")
if sh != "all" and not set(sh or []) <= shape_ids:
errs.append(f"{mf}: shapes {sorted(set(sh) - shape_ids)} not in family")
o, src = prov.get("origin", ""), prov.get("source")
want = ("nki-lib" if o.startswith("https://github.com/aws-neuron/")
else "hugging-face" if o.startswith("https://huggingface.co/") else "jburtoft" if o.startswith(("workspace:", "https://github.com/jimburtoft/")) or o == "unpublished" else None)
if src != want:
errs.append(f"{mf}: provenance.source {src!r} inconsistent with origin (expected {want!r})")
if o.startswith("workspace:"):
errs.append(f"{mf}: workspace origin must not ship (use 'unpublished')")
if prov.get("license", "TBD") == "TBD":
errs.append(f"{mf}: WARNING license TBD (blocks public packaging)")
for d in m.get("deps", []):
p = os.path.join(vd, "deps", d["path"])
if not os.path.isfile(p) or sha(p) != d["sha256"]:
errs.append(f"{mf}: dep {d['path']} missing or sha mismatch")
rd = os.path.join(vd, "results")
for name, kind in (("sim_parity.json", "parity"), ("hw_parity.json", "parity"), ("timing.json", "timing"), ("multicore.json", "multicore"), ("hosts/trn2.3xlarge/timing.json", "timing"), ("hosts/trn2.3xlarge/multicore.json", "multicore")):
p = os.path.join(rd, name)
if os.path.isfile(p):
for e in jsonschema.Draft202012Validator(SCHEMA[kind]).iter_errors(json.load(open(p))):
errs.append(f"{p}: {e.json_path}: {e.message}")
if n == 0:
errs.append(f"{fd}: no versions")
for root, dirs, files in os.walk(fd):
dirs[:] = [d for d in dirs if d not in ("__pycache__", "neff", "ifmaps") and not d.startswith(("profile_", "multicore_"))]
for f in files:
hygiene(os.path.join(root, f), errs)
return n
def main(paths):
errs, nf, nv = [], 0, 0
for base in paths or [os.path.join(ROOT, "dataset")]:
for root, dirs, files in os.walk(base):
if "family.yaml" in files:
nf += 1
nv += check_family(root, errs)
dirs[:] = []
hard = [e for e in errs if "WARNING" not in e]
for e in errs:
print(("WARN " if "WARNING" in e else "ERROR ") + e)
print(f"validated {nf} families, {nv} versions: {len(hard)} errors, {len(errs) - len(hard)} warnings")
return 1 if hard else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))