"""Compare a compiler flag / technique against the dataset baseline. Recompiles + re-profiles every selected valid version under a variant environment (e.g. a NEURON_CC_FLAGS value), checks hw parity still passes, and reports per-family speedup vs the stored baseline timing, with the noise band of both measurements. # on the trn2 host, after `source toolchain/env.sh` python tools/compare.py --name automatmult --env NEURON_CC_FLAGS=--auto-cast=matmult \ [--families a,b] [--domains attention,moe] [--workers 4] [--out compare_automatmult] IMPORTANT: the verdicts compare against the STORED baseline, measured on other cores in another session. On trn2 the same NEFF can be 10-40 % slower on one half of a device (eval_public/PLACEMENT.md), so follow up with tools/paired_profile.py (baseline + variant on the same cores) before trusting FASTER/SLOWER verdicts under ~10 %. Output: ///results/{hw_parity.json,timing.json,...} (a mirror tree, the dataset itself is never modified) and /report.md + report.json: family, version, shape, base_us, variant_us, speedup (= base/variant), noise band, verdict verdict: FASTER / SLOWER if |speedup-1| exceeds the combined noise band (max of the two noise_pct, floor 1 %), else SAME; PARITYFAIL if the variant no longer passes hw parity. python tools/compare.py --report # rebuild the report only """ import argparse, json, os, shutil, subprocess, sys ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, ROOT) import nkb # noqa: E402 def mirror(fam, v, out): dst = os.path.join(out, fam.domain, fam.name, v.label) if os.path.isdir(dst): return dst os.makedirs(os.path.dirname(dst), exist_ok=True) for f in ("family.yaml", "inputs.py", "reference.py"): p = os.path.join(fam.path, f) if not os.path.exists(os.path.join(os.path.dirname(dst), f)): shutil.copy(p, os.path.dirname(dst)) for extra in os.listdir(fam.path): # family-level adapters if extra.startswith("adapter") and extra.endswith(".py"): shutil.copy(os.path.join(fam.path, extra), os.path.dirname(dst)) shutil.copytree(v.path, dst, ignore=shutil.ignore_patterns("results", "__pycache__")) # sim parity is a property of the source, not the compiler: carry it over so `valid` works sp = os.path.join(v.path, "results", "sim_parity.json") if os.path.isfile(sp): os.makedirs(os.path.join(dst, "results"), exist_ok=True) shutil.copy(sp, os.path.join(dst, "results")) return dst def report(out, base_root): base = nkb.load_dataset(base_root) var = nkb.load_dataset(out) rows = [] for fname, vf in sorted(var.items()): bf = base.get(fname) if not bf: continue bv = {v.label: v for v in bf.versions} for v in vf.versions: b = bv.get(v.label) if not b: continue hp = v.results("hw_parity") for s in v.shapes: bt, vt = b.time_us(s), v.time_us(s) row = {"family": fname, "version": v.label, "shape": s, "base_us": bt, "variant_us": vt} if not hp or not hp.get("pass"): row["verdict"] = "PARITYFAIL" elif bt is None or vt is None: row["verdict"] = "MISSING" else: sp = bt / vt band = max(b.noise_pct(s) or 0, v.noise_pct(s) or 0, 1.0) / 100 row.update(speedup=round(sp, 4), band_pct=round(band * 100, 2), verdict="FASTER" if sp > 1 + band else "SLOWER" if sp < 1 - band else "SAME") rows.append(row) json.dump(rows, open(os.path.join(out, "report.json"), "w"), indent=1) import math sps = [r["speedup"] for r in rows if "speedup" in r] geo = math.exp(sum(math.log(x) for x in sps) / len(sps)) if sps else float("nan") cnt = {k: sum(1 for r in rows if r["verdict"] == k) for k in ("FASTER", "SAME", "SLOWER", "PARITYFAIL", "MISSING")} with open(os.path.join(out, "report.md"), "w") as f: f.write(f"# Variant report: {os.path.basename(out)}\n\n") f.write(f"{len(rows)} (version, shape) points; geomean speedup {geo:.4f}; " + ", ".join(f"{k} {v}" for k, v in cnt.items()) + "\n\n") f.write("| family | version | shape | base us | variant us | speedup | band % | verdict |\n|---|---|---|---|---|---|---|---|\n") for r in rows: f.write(f"| {r['family']} | {r['version']} | {r['shape']} | {r['base_us']} | {r['variant_us']} | " f"{r.get('speedup', '')} | {r.get('band_pct', '')} | {r['verdict']} |\n") print(f"report: {len(rows)} points, geomean {geo:.4f}, {cnt}") def main(): ap = argparse.ArgumentParser() ap.add_argument("--name"); ap.add_argument("--env", action="append", default=[]) ap.add_argument("--families", default=""); ap.add_argument("--domains", default="") ap.add_argument("--dataset", default=os.path.join(ROOT, "dataset")) ap.add_argument("--workers", type=int, default=0); ap.add_argument("--reps", type=int, default=2) ap.add_argument("--out", default=""); ap.add_argument("--report", default="") a = ap.parse_args() if a.report: return report(a.report, a.dataset) out = a.out or os.path.join(ROOT, f"compare_{a.name}") ds = nkb.load_dataset(a.dataset) fams = set(filter(None, a.families.split(","))); doms = set(filter(None, a.domains.split(","))) n = 0 for fam in ds.values(): if (fams and fam.name not in fams) or (doms and fam.domain not in doms): continue for v in fam.versions: if v.valid: mirror(fam, v, out); n += 1 print(f"{n} valid versions mirrored to {out}") env = dict(os.environ) for kv in a.env: k, _, val = kv.partition("=") env[k] = val json.dump({"name": a.name, "env": a.env}, open(os.path.join(out, "variant.json"), "w"), indent=1) subprocess.run([sys.executable, os.path.join(ROOT, "harness", "batch.py"), "--hw", out, "--workers", str(a.workers), "--reps", str(a.reps)], env=env) report(out, a.dataset) if __name__ == "__main__": main()