4
0

perf_gate.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. #!/usr/bin/env python3
  2. """Big-project performance gate: collect, compare, update (round perfgate190id, community slice B12).
  3. scripts/perf-gate.sh runs the measurements into a results folder; this script reads it.
  4. perf_gate.py collect <results dir> -> <dir>/results.json (every metric, best of the runs)
  5. perf_gate.py compare <results dir> <baseline.json> -> <dir>/summary.md; exit 1 on a regression, and the
  6. cells to measure again in <dir>/retry.txt
  7. perf_gate.py update <results dir> <baseline.json> -> writes the baseline from these results (keeps its
  8. thresholds)
  9. perf_gate.py ab <results dir> -> <dir>/summary-ab.md: the interleaved A/B of perf-gate.sh ab
  10. (<dir>/base vs <dir>/new, median vs median); exit 1 on a
  11. regression
  12. Files in the results folder (written by perf-gate.sh):
  13. calib-<n>.txt perfbench calibrate (GATE scenario=calibrate calib_ms=...)
  14. bench-<cell>-<n>.txt perfbench <scenario> --gate (one GATE line); <cell> = <scenario>@<block>
  15. paint-<project>-<n>.txt LYNX --paintbench report (open line, "<view>, whole frame: median X ms ...")
  16. open-<project>-<n>.txt LYNX --opentime report (key=value lines)
  17. perfgen.txt LYNX --perfgen report (save_ms / load_ms per project)
  18. Metrics are "lower is better". With several runs of a cell the best (lowest) value counts: noise on a shared machine
  19. only ever adds time. Times are divided by the run's calibration (a fixed piece of work, perfbench calibrate), so a
  20. faster or slower machine moves both alike; memory and instruction counts are compared as they are.
  21. A baseline keeps one set of numbers per CPU model ("machines"; CI runners come with several): a run compares with
  22. its own model's numbers, or with the default set and every threshold widened by cross_machine_factor (1.5). With
  23. PERF_GATE_ADD_MACHINE=1, update only adds this run's CPU model; with PERF_GATE_ONLY_METRICS=paint_instr (names, comma
  24. separated) it only adds those metrics of this run to its model's numbers and keeps every other number.
  25. Paint cells (rollup 0.1.30 step 9): --paintbench also reports, on Linux where the CPU counter can be read, the
  26. instructions the message thread retires per whole frame ("paint_instr"). Drawn by the software renderer, the same pixels
  27. retire nearly the same instructions on every run, while the frame's time divided by the (calculation-bound)
  28. calibration moves with the runner's memory system: one CPU model's frames came out 20 … 50 % "slower" than another's
  29. for the same code. Where the run and the baseline both have a cell's instruction count, the count gates it (tight
  30. threshold) and the time is reported only ("slower (time only)"); elsewhere the time gates, as before.
  31. Wall-clock cells and their instruction counts (rollup 0.1.31 step 5, round 190ok's proposal, ROLLUP031-S4-CELLS.md): one
  32. stored run of a ~5 ms edit or of a CPU share moves +-12 ... 25 % on the same binary minutes apart, so a baseline's lucky
  33. run set bars that later runs missed by 40-100 %. Now (1) a bench cell's cpu_norm is held to its instr_per_sample and the
  34. edit_norm to its edit_instr (perfbench counts the 12 edits' instructions) the way paint_norm is held to paint_instr: when
  35. both sides counted the cell's instructions and the count stayed within its limit, a slower time is reported, not failed
  36. ("slower (time only)"); a time failure counts when its instruction cell moved too, or (2) when an interleaved A/B against
  37. main confirms it: `perf-gate.sh ab` runs main's perfbench (BASE_PERFBENCH) and this one alternately, >= 5 rounds
  38. (main, new, new, main, ...), and compares the MEDIANS of each side's runs (`perf_gate.py ab`), every wall-clock cell
  39. included. Cells without an instruction count (build / rebuild / import, save / load, open) gate on time as before.
  40. A metric regresses when it is worse than the baseline by more than its relative threshold AND by more than its
  41. absolute floor (small values are noisy in absolute terms). Missing metrics that the baseline has fail too (a step
  42. that stopped working). Metrics without a baseline are reported as new and never fail.
  43. """
  44. import json
  45. import os
  46. import re
  47. import sys
  48. from collections import defaultdict
  49. # default thresholds: (relative, absolute floor in the metric's own unit after normalisation)
  50. DEFAULT_THRESHOLDS = {
  51. "instr_per_sample": [0.04, 50.0],
  52. "cpu_norm": [0.20, 0.05], # CPU % of a core / calibration ms
  53. "build_norm": [0.30, 0.2],
  54. "rebuild_norm": [0.30, 0.2],
  55. "edit_norm": [0.30, 0.05],
  56. "edit_instr": [0.05, 50000.0], # instructions of one edit's snapshot, median of 12 (rollup 0.1.31 step 5)
  57. "import_norm": [0.30, 0.2],
  58. "rss_mb": [0.10, 12.0],
  59. "paint_norm": [0.30, 0.03],
  60. "paint_instr": [0.05, 20000.0], # instructions per whole frame (rollup step 9: the stable paint measure)
  61. "open_norm": [0.30, 0.2],
  62. "open_rss_mb": [0.10, 24.0],
  63. "save_norm": [0.30, 0.2],
  64. "load_norm": [0.30, 0.2],
  65. "opentime_load_norm": [0.30, 40.0],
  66. "opentime_rss_mb": [0.12, 32.0],
  67. "idle_cpu_pct": [0.50, 1.5],
  68. }
  69. NUM = r"(-?[0-9.]+)"
  70. def kv(line):
  71. return dict(re.findall(r"(\w+)=(\S+)", line))
  72. def calibration(d):
  73. vals = []
  74. for f in sorted(os.listdir(d)):
  75. if f.startswith("calib-"):
  76. for line in open(os.path.join(d, f), errors="replace"):
  77. if line.startswith("GATE "):
  78. vals.append(float(kv(line)["calib_ms"]))
  79. if not vals:
  80. sys.exit("perf_gate: no calibration in " + d)
  81. vals.sort()
  82. return vals[len(vals) // 2], vals
  83. # the instruction cell that holds a wall-clock cell (rollup 0.1.31 step 5: cpu_norm and edit_norm, as paint_norm)
  84. COUNTED_BY = {"cpu_norm": "instr_per_sample", "edit_norm": "edit_instr", "paint_norm": "paint_instr"}
  85. def collect(d, pick=min):
  86. calib, calibs = calibration(d)
  87. runs = defaultdict(list) # metric -> values
  88. info = {}
  89. def add(key, value):
  90. if value is not None and value == value and value >= 0:
  91. runs[key].append(value)
  92. for f in sorted(os.listdir(d)):
  93. p = os.path.join(d, f)
  94. m = re.match(r"bench-(.+)-\d+\.txt$", f)
  95. if m:
  96. cell = m.group(1)
  97. for line in open(p, errors="replace"):
  98. if not line.startswith("GATE "):
  99. continue
  100. g = kv(line)
  101. base = "bench/" + cell + "/"
  102. add(base + "cpu_norm", float(g["cpu_pct"]) / calib)
  103. if float(g["instr_per_sample"]) > 0:
  104. add(base + "instr_per_sample", float(g["instr_per_sample"]))
  105. if cell.endswith("@256"): # (the project's load: once per scenario is enough)
  106. add(base + "build_norm", float(g["build_ms"]) / calib)
  107. add(base + "rebuild_norm", float(g["rebuild_ms"]) / calib)
  108. if "edit_ms" in g:
  109. add(base + "edit_norm", float(g["edit_ms"]) / calib)
  110. if float(g.get("edit_instr", -1)) > 0:
  111. add(base + "edit_instr", float(g["edit_instr"]))
  112. add(base + "import_norm", float(g["import_ms"]) / calib)
  113. add(base + "rss_mb", float(g["rss_mb"]))
  114. info["hash/" + cell] = g["hash"]
  115. continue
  116. m = re.match(r"paint-(.+)-\d+\.txt$", f)
  117. if m:
  118. proj = m.group(1)
  119. text = open(p, errors="replace").read()
  120. if "result=OK" not in text:
  121. continue
  122. om = re.search(r"^open: " + NUM + r" ms wall, " + NUM + r" ms message thread CPU, working set " + NUM + " MB", text, re.M)
  123. if om:
  124. add("app/" + proj + "/open_norm", float(om.group(1)) / calib)
  125. add("app/" + proj + "/open_rss_mb", float(om.group(3)))
  126. for vm in re.finditer(r"^([a-z ]+), whole frame: median " + NUM + r" ms(.*)$", text, re.M):
  127. add("paint/" + proj + "/" + vm.group(1).replace(" ", "_") + "/paint_norm", float(vm.group(2)) / calib)
  128. im = re.search(r", instructions median ([0-9]+)", vm.group(3))
  129. if im:
  130. add("paint/" + proj + "/" + vm.group(1).replace(" ", "_") + "/paint_instr", float(im.group(1)))
  131. continue
  132. m = re.match(r"open-(.+)-\d+\.txt$", f)
  133. if m:
  134. proj = m.group(1)
  135. g = dict(line.strip().split("=", 1) for line in open(p, errors="replace") if "=" in line)
  136. if g.get("result") != "OK":
  137. continue
  138. # (from the process' start to the project loaded: the start-up file is opened before the window's probe
  139. # starts, so "loaded - window" would miss a slow open)
  140. add("opentime/" + proj + "/opentime_load_norm", 1000.0 * float(g["loaded_s"]) / calib)
  141. add("opentime/" + proj + "/opentime_rss_mb", float(g["working_set_mb"]))
  142. add("opentime/" + proj + "/idle_cpu_pct", float(g["idle_cpu_pct"]))
  143. continue
  144. if f == "perfgen.txt":
  145. for line in open(p, errors="replace"):
  146. pm = re.match(r"(\w+): (.*)", line)
  147. if pm and "save_ms=" in line:
  148. g = kv(pm.group(2))
  149. add("project/" + pm.group(1) + "/save_norm", float(g["save_ms"]) / calib)
  150. add("project/" + pm.group(1) + "/load_norm", float(g["load_ms"]) / calib)
  151. info["lynx_hash/" + pm.group(1)] = g.get("text_hash", "")
  152. metrics = {k: pick(v) for k, v in runs.items()}
  153. return {"calib_ms": calib, "calib_runs": calibs, "metrics": metrics, "runs": dict(runs), "info": info,
  154. "machine": open(os.path.join(d, "machine.txt")).read().strip() if os.path.exists(os.path.join(d, "machine.txt")) else ""}
  155. def threshold_for(key, thresholds):
  156. name = key.rsplit("/", 1)[1]
  157. # a baseline may override per metric name or per full key
  158. return thresholds.get(key) or thresholds.get(name) or DEFAULT_THRESHOLDS.get(name, [0.25, 0.0])
  159. def cpu_model(machine):
  160. # "Linux x86_64, AMD EPYC 9V45 96-Core Processor, 4 threads, 0d442d6" -> the CPU model
  161. parts = machine.split(", ")
  162. return parts[1] if len(parts) > 2 else machine
  163. def cell_of(key):
  164. parts = key.split("/")
  165. if parts[0] == "bench":
  166. return "bench:" + parts[1]
  167. if parts[0] in ("paint", "app"):
  168. return "paint:" + parts[1]
  169. if parts[0] == "opentime":
  170. return "open:" + parts[1]
  171. return "perfgen"
  172. def fmt(v):
  173. return ("%.4g" % v) if abs(v) < 1000 else "%.0f" % v
  174. def compare(d, baseline_path, show=False):
  175. res = collect(d)
  176. json.dump(res, open(os.path.join(d, "results.json"), "w"), indent=1, sort_keys=True)
  177. base = json.load(open(baseline_path))
  178. thresholds = dict(DEFAULT_THRESHOLDS)
  179. thresholds.update(base.get("thresholds", {}))
  180. # a baseline measured on this CPU model compares as it is; another model's (CI runners differ) with the thresholds
  181. # widened by cross_machine_factor
  182. model = cpu_model(res["machine"])
  183. own = base.get("machines", {}).get(model)
  184. bm, cm = (own if own else base.get("metrics", {})), res["metrics"]
  185. factor = 1.0 if own else float(base.get("cross_machine_factor", 1.5))
  186. rows, failed, retry = [], [], set()
  187. project_of = lambda key: key.split("/")[1].split("@")[0]
  188. projects_run = {project_of(k) for k in cm}
  189. for key in sorted(set(bm) | set(cm)):
  190. rel, floor = threshold_for(key, thresholds)
  191. rel *= factor
  192. if key not in cm and project_of(key) not in projects_run: # (a project this run left out: FL=0, no FL install)
  193. rows.append((key, fmt(bm[key]), "not run", "", "skipped"))
  194. continue
  195. if key not in cm and key.endswith("/instr_per_sample"): # (the CPU counter is not always readable in a VM)
  196. rows.append((key, fmt(bm[key]), "n/a", "", "not measured (no CPU counter)"))
  197. continue
  198. if key not in cm:
  199. rows.append((key, fmt(bm[key]), "missing", "", "FAIL (missing)"))
  200. failed.append(key)
  201. retry.add(cell_of(key))
  202. continue
  203. if key not in bm:
  204. rows.append((key, "", fmt(cm[key]), "", "new"))
  205. continue
  206. b, c = bm[key], cm[key]
  207. delta = (c - b) / b if b > 0 else 0.0
  208. worse = c > b * (1.0 + rel) and c - b > floor
  209. verdict = "FAIL" if worse else ("better" if c < b * (1.0 - rel) and b - c > floor else "ok")
  210. # (a wall-clock cell whose instructions both sides counted: the count gates it, its time is reported only; a paint
  211. # cell always so since rollup 0.1.30 step 9, a CPU share or an edit while its count stayed in its limit: step 5)
  212. name = key.rsplit("/", 1)[1]
  213. counted = key[: -len(name)] + COUNTED_BY.get(name, "")
  214. if name in COUNTED_BY and counted in bm and counted in cm and worse:
  215. crel, cfloor = threshold_for(counted, thresholds)
  216. count_moved = cm[counted] > bm[counted] * (1.0 + crel * factor) and cm[counted] - bm[counted] > cfloor
  217. if name == "paint_norm" or not count_moved:
  218. worse, verdict = False, "slower (time only: the instruction count gates this cell; perf-gate.sh ab to confirm)"
  219. if worse:
  220. failed.append(key)
  221. retry.add(cell_of(key))
  222. rows.append((key, fmt(b), fmt(c), "%+.1f%%" % (100.0 * delta), verdict + " (limit +%.0f%%)" % (100 * rel)))
  223. out = ["# Performance gate: %s" % ("FAILED" if failed else "passed"), "",
  224. ("Compared with this CPU model's own baseline (%s)." % model) if own else
  225. ("No baseline for this CPU model (%s): the default one, thresholds × %.1f." % (model, factor)), "",
  226. "Baseline `%s` (%s, calibration %.2f ms); this run: %s, calibration %.2f ms (runs %s)." % (
  227. os.path.basename(baseline_path), base.get("machine", "?"), base.get("calib_ms", 0), res["machine"], res["calib_ms"],
  228. ", ".join("%.2f" % x for x in res["calib_runs"])), "",
  229. "Times are divided by the calibration (\\_norm); lower is better; best of the runs.", "",
  230. "| metric | baseline | now | change | verdict |", "|---|---|---|---|---|"]
  231. out += ["| %s |" % " | ".join(r) for r in rows]
  232. if failed:
  233. out += ["", "**Regressed:** " + ", ".join(failed)]
  234. changed = [k for k, v in res["info"].items() if k.startswith("hash/") and base.get("info", {}).get(k) not in (None, v)]
  235. if changed:
  236. out += ["", "Output hash changed (not a performance failure; a sound change must be intended): " + ", ".join(changed)]
  237. text = "\n".join(out) + "\n"
  238. open(os.path.join(d, "summary.md"), "w").write(text)
  239. open(os.path.join(d, "retry.txt"), "w").write("\n".join(sorted(retry)) + ("\n" if retry else ""))
  240. if show:
  241. print(text)
  242. return 1 if failed else 0
  243. def update(d, baseline_path, show=False):
  244. res = collect(d)
  245. json.dump(res, open(os.path.join(d, "results.json"), "w"), indent=1, sort_keys=True)
  246. old = json.load(open(baseline_path)) if os.path.exists(baseline_path) else {}
  247. only = [n for n in os.environ.get("PERF_GATE_ONLY_METRICS", "").split(",") if n]
  248. if only and old:
  249. # (rollup step 9) PERF_GATE_ONLY_METRICS=paint_instr,...: only those metrics of this run go into its CPU model's
  250. # numbers (and the default set when it is that model's or the model has none): every other number stays as it was
  251. new = dict(old)
  252. model = cpu_model(res["machine"])
  253. picked = {k: v for k, v in res["metrics"].items() if k.rsplit("/", 1)[1] in only}
  254. machines = {m: dict(v) for m, v in old.get("machines", {}).items()}
  255. if model in machines:
  256. machines[model].update(picked)
  257. if model not in machines or cpu_model(old.get("machine", "")) == model:
  258. new["metrics"] = dict(old.get("metrics", {}), **picked)
  259. new["machines"] = machines
  260. json.dump(new, open(baseline_path, "w"), indent=1, sort_keys=True)
  261. open(baseline_path, "a").write("\n")
  262. if show:
  263. print("perf_gate: added %d %s metrics of %s to %s" % (len(picked), ",".join(only), model, baseline_path))
  264. return 0
  265. machines = dict(old.get("machines", {}))
  266. machines[cpu_model(res["machine"])] = res["metrics"]
  267. keep_default = os.environ.get("PERF_GATE_ADD_MACHINE") == "1" and old.get("metrics") # (only add this CPU model)
  268. new = {"profile": old.get("profile", os.path.splitext(os.path.basename(baseline_path))[0]),
  269. "machine": old["machine"] if keep_default else res["machine"], "calib_ms": old["calib_ms"] if keep_default else res["calib_ms"],
  270. "metrics": old["metrics"] if keep_default else res["metrics"], "info": res["info"],
  271. "machines": machines, "thresholds": old.get("thresholds", {})}
  272. for k in ("note", "cross_machine_factor"):
  273. if k in old:
  274. new[k] = old[k]
  275. json.dump(new, open(baseline_path, "w"), indent=1, sort_keys=True)
  276. open(baseline_path, "a").write("\n")
  277. if show:
  278. print("perf_gate: wrote %s (%d metrics)" % (baseline_path, len(res["metrics"])))
  279. return 0
  280. def median(v):
  281. v = sorted(v)
  282. n = len(v)
  283. return v[n // 2] if n % 2 else 0.5 * (v[n // 2 - 1] + v[n // 2])
  284. def ab(d, show=False):
  285. """Rollup 0.1.31 step 5 (round 190ok's proposal): main (<d>/base) and this build (<d>/new) measured alternately in one
  286. session by perf-gate.sh ab; each metric is the median of its side's runs and the new one fails past the metric's
  287. threshold, every wall-clock cell included (this comparison is the A/B that confirms a time failure)."""
  288. b, n = collect(os.path.join(d, "base"), pick=median), collect(os.path.join(d, "new"), pick=median)
  289. thresholds = dict(DEFAULT_THRESHOLDS)
  290. rows, failed = [], []
  291. for key in sorted(set(b["metrics"]) | set(n["metrics"])):
  292. if key not in b["metrics"] or key not in n["metrics"]:
  293. rows.append((key, fmt(b["metrics"].get(key, -1)), fmt(n["metrics"].get(key, -1)), "", "one side only"))
  294. continue
  295. bv, nv = b["metrics"][key], n["metrics"][key]
  296. rel, floor = threshold_for(key, thresholds)
  297. worse = nv > bv * (1.0 + rel) and nv - bv > floor
  298. runs = "%d / %d" % (len(b["runs"].get(key, [])), len(n["runs"].get(key, [])))
  299. if worse:
  300. failed.append(key)
  301. verdict = "FAIL" if worse else ("better" if nv < bv * (1.0 - rel) and bv - nv > floor else "ok")
  302. rows.append((key, fmt(bv), fmt(nv), "%+.1f%%" % (100.0 * (nv - bv) / bv if bv > 0 else 0.0), "%s (limit +%.0f%%, runs %s)" % (verdict, 100 * rel, runs)))
  303. out = ["# Performance A/B (interleaved): %s" % ("FAILED" if failed else "passed"), "",
  304. "main: %s, calibration median %.2f ms (runs %s)" % (b["machine"], b["calib_ms"], ", ".join("%.2f" % x for x in b["calib_runs"])),
  305. "new: %s, calibration median %.2f ms (runs %s)" % (n["machine"], n["calib_ms"], ", ".join("%.2f" % x for x in n["calib_runs"])), "",
  306. "Median of each side's runs; times divided by the side's median calibration; lower is better.", "",
  307. "| metric | main | new | change | verdict |", "|---|---|---|---|---|"]
  308. out += ["| %s |" % " | ".join(r) for r in rows]
  309. if failed:
  310. out += ["", "**Regressed (A/B):** " + ", ".join(failed)]
  311. text = "\n".join(out) + "\n"
  312. open(os.path.join(d, "summary-ab.md"), "w").write(text)
  313. if show:
  314. print(text)
  315. return 1 if failed else 0
  316. if __name__ == "__main__":
  317. if len(sys.argv) < 3 or sys.argv[1] not in ("collect", "compare", "update", "ab"):
  318. sys.exit(__doc__)
  319. if sys.argv[1] == "ab":
  320. sys.exit(ab(sys.argv[2], show=True))
  321. if sys.argv[1] == "collect":
  322. r = collect(sys.argv[2])
  323. json.dump(r, open(os.path.join(sys.argv[2], "results.json"), "w"), indent=1, sort_keys=True)
  324. print(json.dumps(r["metrics"], indent=1, sort_keys=True))
  325. sys.exit(0)
  326. sys.exit((compare if sys.argv[1] == "compare" else update)(sys.argv[2], sys.argv[3], show=True))