jburtoft's picture
nki-kernel-bench v0.1
0fef070
Raw History Blame Contribute Delete
8.66 kB
"""Batch driver: run many families/versions on one trn2 host.
python harness/batch.py --hw dataset/ [--workers 4] [--shapes ...] [--reps 2] [--force] [--tar out.tgz]
python harness/batch.py --sim dataset/ [--workers 4]
- Finds every version dir under the given paths.
- One lane per Neuron device (trn2.3xlarge: 1, trn2.48xlarge: 16). Lane d runs, for each version it
pulls from the queue, compile+parity (`hwc`) then profile (`hwp`) on the first logical core of
device d -- one process at a time per chip, so a profile never shares its chip with another run.
LNC=1 versions run first, then LNC=2 (never mixed on the host at the same time).
- Resumable: a version is skipped if its results are complete and current (kernel sha256 and
manifest unchanged, see `fingerprint`). --force reruns.
- Every outcome appends a line to batch_status.jsonl in the package root (parent of harness/) and
prints a final table with
the failure class (HWPARITYFAIL, CAPFAIL, INGESTFAIL, LNCMISMATCH, NONEFF, COMPILEFAIL, SIMFAIL).
"""
import argparse, glob, hashlib, json, os, subprocess, sys, tarfile, time
from concurrent.futures import ThreadPoolExecutor
HERE = os.path.dirname(os.path.abspath(__file__))
RUN = os.path.join(HERE, "run.py")
CLASSES = ("COMPILEFAIL", "HWPARITYFAIL", "CAPFAIL", "INGESTFAIL", "LNCMISMATCH", "NONEFF")
def yload(p):
import yaml
return yaml.safe_load(open(p))
def versions(paths):
out = []
for p in paths:
for m in sorted(glob.glob(os.path.join(os.path.abspath(p), "**", "manifest.yaml"), recursive=True)):
vd = os.path.dirname(m)
if os.path.isfile(os.path.join(os.path.dirname(vd), "family.yaml")):
out.append(vd)
return out
EXEC_KEYS = ("entry", "launch_grid", "shapes", "extra_outputs", "call_adapter", "deps", "port")
def fingerprint(vd):
"""Hash of everything that affects execution. Manifest metadata (provenance, labels, summaries)
is excluded, so editing it does not invalidate results."""
h = hashlib.sha256()
fd = os.path.dirname(vd)
man = yload(os.path.join(vd, "manifest.yaml"))
h.update(json.dumps({k: man.get(k) for k in EXEC_KEYS}, sort_keys=True).encode())
for p in [os.path.join(vd, "kernel.py"), os.path.join(fd, "family.yaml"),
os.path.join(fd, "inputs.py"), os.path.join(fd, "reference.py")] + sorted(glob.glob(os.path.join(fd, "adapter*.py"))) + sorted(glob.glob(os.path.join(vd, "deps", "**", "*.py"), recursive=True)):
h.update(open(p, "rb").read())
return h.hexdigest()
def complete(vd, mode):
rd = os.path.join(vd, "results")
fp = os.path.join(rd, f".fingerprint_{mode}")
if not os.path.isfile(fp) or open(fp).read().strip() != fingerprint(vd):
return False
if mode == "sim":
p = os.path.join(rd, "sim_parity.json")
return os.path.isfile(p) and json.load(open(p)).get("pass")
p, t = os.path.join(rd, "hw_parity.json"), os.path.join(rd, "timing.json")
return os.path.isfile(p) and json.load(open(p)).get("pass") and os.path.isfile(t)
def run_phase(phase, vd, core, shapes, reps, logdir):
man = yload(os.path.join(vd, "manifest.yaml"))
env = dict(os.environ, NEURON_LOGICAL_NC_CONFIG=str(man.get("launch_grid", 1)), NEURON_RT_VISIBLE_CORES=str(core))
env.setdefault("NEURON_PLATFORM_TARGET_OVERRIDE", "trn2"); env.setdefault("NKI_LNC1_SHARED_HBM", "0"); env.setdefault("TORCH_DEVICE_BACKEND_AUTOLOAD", "0")
cmd = [sys.executable, RUN, "--_one", phase, vd, "--reps", str(reps)] + (["--shapes", shapes] if shapes else [])
log = os.path.join(logdir, man["id"].replace("/", "__") + f".{phase}.log")
t0 = time.time()
with open(log, "w") as f:
rc = subprocess.run(cmd, env=env, stdout=f, stderr=subprocess.STDOUT).returncode
txt = open(log, errors="ignore").read()
cls = next((c for c in CLASSES if c in txt), None)
if rc and not cls:
cls = {"hwc": "COMPILEFAIL", "hwp": "PROFILEFAIL", "sim": "SIMFAIL"}[phase]
return {"id": man["id"], "phase": phase, "rc": rc, "class": cls, "core": core, "lnc": man.get("launch_grid", 1),
"wall_s": round(time.time() - t0, 1), "log": log}
def main():
ap = argparse.ArgumentParser()
g = ap.add_mutually_exclusive_group(required=True)
g.add_argument("--hw", nargs="+"); g.add_argument("--sim", nargs="+")
ap.add_argument("--workers", type=int, default=0, help="hw: device lanes (default all devices); sim: threads (default 4)")
ap.add_argument("--shapes", default="")
ap.add_argument("--reps", type=int, default=2)
ap.add_argument("--force", action="store_true")
ap.add_argument("--devices", type=int, default=0, help="Neuron devices on the host (default: count /dev/neuron*)")
ap.add_argument("--tar", default="")
a = ap.parse_args()
mode = "hw" if a.hw else "sim"
paths = a.hw or a.sim
vds = versions(paths)
base = os.path.dirname(HERE) # logs + status always under the package root, never in dataset/
logdir = os.path.join(base, "batch_logs"); os.makedirs(logdir, exist_ok=True)
status = open(os.path.join(base, "batch_status.jsonl"), "a")
todo = [v for v in vds if a.force or not complete(v, mode)]
print(f"{len(vds)} versions, {len(vds) - len(todo)} already complete, {len(todo)} to run ({mode})", flush=True)
results = {}
def record(r):
status.write(json.dumps(dict(r, t=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))) + "\n"); status.flush()
print(f"{'OK ' if r['rc'] == 0 else 'FAIL'} {r['phase']} {r['id']} core={r['core']} {r['wall_s']}s {r['class'] or ''}", flush=True)
if mode == "sim":
with ThreadPoolExecutor(a.workers or 4) as ex:
for v, r in ex.map(lambda v: (v, run_phase("sim", v, 0, a.shapes, a.reps, logdir)), todo):
record(r); results[r["id"]] = r
if r["rc"] == 0:
open(os.path.join(v, "results", ".fingerprint_sim"), "w").write(fingerprint(v))
else:
by_lnc = {1: [v for v in todo if yload(os.path.join(v, "manifest.yaml")).get("launch_grid", 1) == 1],
2: [v for v in todo if yload(os.path.join(v, "manifest.yaml")).get("launch_grid", 1) == 2]}
ndev = a.devices or max(1, len(glob.glob("/dev/neuron[0-9]*")))
cpd = {1: 8, 2: 4} # logical cores per trn2 device at LNC=1 / LNC=2
lanes = max(1, min(a.workers, ndev)) if a.workers else ndev
print(f"{ndev} Neuron device(s); {lanes} device lanes (each: compile -> profile, serial on its own chip)", flush=True)
for lnc in (1, 2): # never mix LNC=1 and LNC=2 processes on the host
queue = [v for v in todo if yload(os.path.join(v, "manifest.yaml")).get("launch_grid", 1) == lnc]
if not queue:
continue
def lane(d):
core = d * cpd[lnc] # first logical core of device d
while True:
try:
v = queue.pop(0)
except IndexError:
return
r = run_phase("hwc", v, core, a.shapes, a.reps, logdir); record(r); results[r["id"]] = r
if r["rc"]:
continue
r = run_phase("hwp", v, core, a.shapes, a.reps, logdir); record(r); results[r["id"]] = r
if r["rc"] == 0:
open(os.path.join(v, "results", ".fingerprint_hw"), "w").write(fingerprint(v))
with ThreadPoolExecutor(lanes) as ex:
list(ex.map(lane, range(lanes)))
status.close()
fails = {k: v for k, v in results.items() if v["rc"]}
by = {}
for v in fails.values():
by.setdefault(v["class"], []).append(v["id"])
print(f"\nBATCH DONE {mode}: ran {len(results)}, ok {len(results) - len(fails)}, failed {len(fails)}")
for c, ids in sorted(by.items()):
print(f" {c}: {len(ids)} e.g. {ids[:5]}")
if a.tar:
with tarfile.open(a.tar, "w:gz") as tf:
for v in vds:
rd = os.path.join(v, "results")
if os.path.isdir(rd):
tf.add(rd, arcname=os.path.relpath(rd, os.path.commonpath([os.path.abspath(x) for x in paths] + [rd]) if len(paths) > 1 else os.path.dirname(os.path.abspath(paths[0]))),
filter=lambda ti: None if "/_work" in ti.name else ti)
tf.add(os.path.join(base, "batch_status.jsonl"), arcname="batch_status.jsonl")
print("tarball", a.tar)
sys.exit(1 if fails else 0)
if __name__ == "__main__":
main()