KBench / tools /factory /kbench.py
ZMC2019's picture
Reorganise: group 313 tasks into 17 families under tasks/, generators under tools/ (part 2)
2e4c7fe verified
Raw
History Blame Contribute Delete
7.49 kB
"""kbench — one entry point for the kernel-generation suite.
Before this, the suite was eight loose scripts with different calling conventions (build.py took a spec
path, validate.sh took a GPU then task names, the audits took task names or nothing, publish took
nothing). Same operations, unified:
kbench list [--tier T3] [--family moe] [--metric GB/s] [--gpus 2] [--json]
kbench show <task>
kbench build <spec.py | task-name | --all>
kbench validate <task...> [--gpu N]
kbench audit [--sizes] [--quality] [--gates] [--span] [--schema] [--all] [task...]
kbench catalog regenerate CATALOG.json + README.md
kbench publish [--dry-run] stage the human-readable tree and push to the Hub
kbench stats
Everything delegates to the existing tools; nothing is reimplemented.
"""
import argparse
import json
import pathlib
import subprocess
import sys
HERE = pathlib.Path(__file__).resolve().parent
LANE = HERE.parent
ROOT = LANE.parent
def _catalog():
p = LANE / "CATALOG.json"
return json.loads(p.read_text()) if p.exists() else []
def _run(cmd, **kw):
return subprocess.run(cmd, shell=isinstance(cmd, str), **kw).returncode
def _spec_for(task):
for sub in ("_factory", "_mega_factory", "_dist_factory"):
p = LANE / sub / "specs" / (task.replace("-", "_") + ".py")
if p.exists():
return p
return None
def cmd_list(a):
rows = _catalog()
for f, v in (("tier", a.tier), ("family", a.family), ("metric", a.metric)):
if v:
rows = [r for r in rows if (r.get(f) or "").lower().find(v.lower()) >= 0]
if a.gpus:
rows = [r for r in rows if r.get("gpus") == a.gpus]
if a.json:
print(json.dumps(rows, indent=2)); return 0
for r in rows:
us = f"{r['roofline_us']:.0f}us" if r.get("roofline_us") else "—"
print(f"{r.get('tier','—'):<3} {r.get('metric') or '—':<8} {us:>8} {r['name']}")
print(f"\n{len(rows)} tasks", file=sys.stderr)
return 0
def cmd_show(a):
r = next((x for x in _catalog() if x["name"] == a.task), None)
if not r:
print(f"no such task: {a.task}", file=sys.stderr); return 1
print(f"{r['name']}\n family {r['family']}\n difficulty{'':1}{r.get('tier','—')} "
f"{r.get('tier_why','')}\n metric {r.get('metric')}\n roofline "
f"{r.get('roofline_us')} us\n gpus {r.get('gpus')}")
sp = _spec_for(a.task)
print(f" spec {sp.relative_to(LANE) if sp else '(hand-written, no spec)'}")
print(f" keywords {', '.join(r.get('keywords', []))}")
print(f"\n{r.get('description','')}")
return 0
def cmd_build(a):
if a.all:
n = f = 0
for sub, b in (("_factory", "build.py"), ("_mega_factory", "build.py")):
for s in sorted((LANE / sub / "specs").glob("*.py")):
if s.name.startswith("_"):
continue
ok = _run([sys.executable, str(LANE / sub / b), str(s)],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) == 0
n, f = n + ok, f + (not ok)
if not ok:
print(f" BUILD FAILED {s.name}", file=sys.stderr)
print(f"built {n}, failed {f}")
return 1 if f else 0
for t in a.target:
p = pathlib.Path(t)
if not p.exists():
p = _spec_for(t)
if p is None:
print(f"no spec for {t}", file=sys.stderr); return 1
b = LANE / ("_mega_factory" if "_mega_factory" in str(p) else "_factory") / "build.py"
if _run([sys.executable, str(b), str(p)]) != 0:
return 1
return 0
def cmd_validate(a):
mega = [t for t in a.task if (LANE / t / "tests" / "verify_env.py").exists()
and "canonical_work" not in (LANE / t / "tests" / "verify_env.py").read_text()]
std = [t for t in a.task if t not in mega]
rc = 0
if std:
rc |= _run(["bash", str(HERE / "validate.sh"), str(a.gpu), *std])
if mega:
print("megakernel-family tasks need the mega harness "
"(reference as pass-through submission); see _mega_factory/CALIBRATION.md §7:",
", ".join(mega), file=sys.stderr)
return rc
def cmd_audit(a):
which = [k for k in ("sizes", "quality", "gates", "span", "schema") if getattr(a, k)] or (
["sizes", "quality", "schema"] if not a.all else ["sizes", "quality", "gates", "span", "schema"])
rc = 0
if "sizes" in which:
print("== sizing =="); rc |= _run([sys.executable, str(HERE / "audit_sizes.py"), *a.task])
if "quality" in which:
print("== quality =="); rc |= _run([sys.executable, str(HERE / "audit_quality.py"), *a.task])
if "schema" in which:
print("== schema =="); rc |= _run([sys.executable, str(HERE / "audit_schema.py"), *a.task])
if "gates" in which:
print("== gate discrimination ==")
lst = pathlib.Path("/tmp/_kb_gates.txt")
lst.write_text("\n".join(a.task or [r["name"] for r in _catalog()]) + "\n")
rc |= _run(f"GPU={a.gpu} bash {HERE/'gate_probe.sh'} {lst}")
if "span" in which:
print("== input span == (run per task inside its container; see _factory/span_check.py)")
return rc
def cmd_catalog(a):
return _run([sys.executable, str(HERE / "make_catalog.py")])
def cmd_publish(a):
if _run([sys.executable, str(HERE / "publish_kbench.py")]) != 0:
return 1
if a.dry_run:
print("staged only (--dry-run); not pushed"); return 0
push = ROOT.parent / "scripts" / "push_kbench.py"
print(f"stage complete. push with the Hub uploader ({push if push.exists() else 'see RUN.md'})")
return 0
def cmd_stats(a):
rows = _catalog()
from collections import Counter
for field, label in (("tier", "difficulty"), ("family", "family"), ("metric", "metric")):
c = Counter(r.get(field) or "—" for r in rows)
print(f"\n{label}:")
for k, v in c.most_common():
print(f" {v:5d} {k}")
print(f"\ntotal in kernels/: {len(rows)}")
return 0
def main():
p = argparse.ArgumentParser(prog="kbench", description=__doc__.split("\n")[0])
sub = p.add_subparsers(dest="cmd", required=True)
q = sub.add_parser("list"); q.set_defaults(fn=cmd_list)
q.add_argument("--tier"); q.add_argument("--family"); q.add_argument("--metric")
q.add_argument("--gpus", type=int); q.add_argument("--json", action="store_true")
q = sub.add_parser("show"); q.set_defaults(fn=cmd_show); q.add_argument("task")
q = sub.add_parser("build"); q.set_defaults(fn=cmd_build)
q.add_argument("target", nargs="*"); q.add_argument("--all", action="store_true")
q = sub.add_parser("validate"); q.set_defaults(fn=cmd_validate)
q.add_argument("task", nargs="+"); q.add_argument("--gpu", type=int, default=1)
q = sub.add_parser("audit"); q.set_defaults(fn=cmd_audit)
q.add_argument("task", nargs="*"); q.add_argument("--gpu", type=int, default=1)
for k in ("sizes", "quality", "gates", "span", "schema", "all"):
q.add_argument(f"--{k}", action="store_true")
sub.add_parser("catalog").set_defaults(fn=cmd_catalog)
q = sub.add_parser("publish"); q.set_defaults(fn=cmd_publish)
q.add_argument("--dry-run", action="store_true")
sub.add_parser("stats").set_defaults(fn=cmd_stats)
a = p.parse_args()
sys.exit(a.fn(a))
if __name__ == "__main__":
main()