perf_gate.py 15 KB

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