From e73f5439a21978fffaf9df568d019d8682f0e4d6 Mon Sep 17 00:00:00 2001 From: Ary Borenszweig Date: Fri, 27 Nov 2026 13:31:12 -0300 Subject: [PATCH] CI: benchmark bb at v6.1.0 and after each merged stack A workflow_dispatch workflow (bench.yml) that builds bb, bb-avm and the UltraHonk micro-benchmark at each point of .github/bench/points.json (v6.1.0, then PRs #1, #2 and #3), and times every point on the same hosted runner, taking turns, per column: aztec-packages' pinned Chonk flows, its micro-benchmark, and the rollup and AVM inputs of the bench-inputs-v6.1.0 release asset. Fastest of 3 runs, highest peak RSS; each point's proofs are checked by the original bb. A dispatched run publishes data.json, a page and aztec-packages style bench JSON per point to gh-pages. A pull request that changes the benchmarks runs them without publishing. --- .github/bench/bench.py | 419 ++++++++++++++++++++++++++++++++++++ .github/bench/index.html | 225 +++++++++++++++++++ .github/bench/points.json | 30 +++ .github/bench/test_bench.py | 232 ++++++++++++++++++++ .github/workflows/bench.yml | 252 ++++++++++++++++++++++ 5 files changed, 1158 insertions(+) create mode 100644 .github/bench/bench.py create mode 100644 .github/bench/index.html create mode 100644 .github/bench/points.json create mode 100644 .github/bench/test_bench.py create mode 100644 .github/workflows/bench.yml diff --git a/.github/bench/bench.py b/.github/bench/bench.py new file mode 100644 index 0000000..b303436 --- /dev/null +++ b/.github/bench/bench.py @@ -0,0 +1,419 @@ +#!/usr/bin/env python3 +"""bb-boost's benchmarks: time several bb builds ("points") on the same machine, taking turns. + + bench.py run --points points.json --bins DIR --column COLUMN --inputs DIR [--flows DIR] --out results.json + bench.py publish --points points.json --results DIR --out DIR [--run-url URL] + +`run` times one column's inputs with every point's binaries. Each repeat runs every input once per point, in a +rotating order, so no point always goes first. A point's time on an input is its fastest run, its memory the highest +peak RSS of its runs (aztec-golf's method). Each point's last proof is then checked with the first point's (the +original's) binary. + +`publish` merges the columns' results into data.json (read by index.html), one aztec-packages style bench JSON per +point (`[{name, value, unit}]`, as in its `bench-out/*.bench.json`), and a Markdown summary. +""" +from __future__ import annotations + +import argparse +import datetime +import json +import math +import os +import re +import shutil +import subprocess +import sys +import time +from dataclasses import dataclass, field +from pathlib import Path + +COLUMNS = ("client", "micro", "rollup", "avm") +COLUMN_TITLES = { + "client": "Client: aztec-packages' pinned Chonk flows (native)", + "micro": "Micro-benchmark: aztec-packages' UltraHonk proof of 2^20 gates", + "rollup": "Rollup: aztec-golf's season 2 inputs", + "avm": "AVM: aztec-golf's season 2 inputs", +} +MICRO = { + "ultra_honk": "construct_proof_ultrahonk_power_of_2/20$", + "ultra_honk_zk": "construct_proof_ultrahonk_zk_power_of_2/20$", +} +RUN_TIMEOUT_S = 40 * 60 + + +@dataclass +class Case: + """One input of a column, as `/`; `prefix` names its metrics.""" + + id: str + prefix: str + binary: str # bb, bb-avm or ultra_honk_bench + path: Path | None = None + args: list[str] = field(default_factory=list) # bb arguments before -o + vk: Path | None = None # client: the flow's VK, to verify + flags: list[str] = field(default_factory=list) # rollup: bb flags, to verify + avm_public_inputs: Path | None = None + + +def discover(column: str, inputs: Path | None, flows: Path | None) -> list[Case]: + cases: list[Case] = [] + if column == "client": + for d in sorted(p for p in flows.iterdir() if (p / "ivc-inputs.msgpack").is_file()): + vk = inputs / "client" / d.name / "vk" if inputs else None + cases.append(Case(f"client/{d.name}", f"aztec-packages/app-proving/{d.name}/native", "bb", d, + ["prove", "--scheme", "chonk", "--ivc_inputs_path", str(d / "ivc-inputs.msgpack")], + vk=vk if vk and vk.is_file() else None)) + elif column == "micro": + for name, filt in MICRO.items(): + cases.append(Case(f"micro/{name}", f"aztec-packages/bb-micro-bench/native/{name}", "ultra_honk_bench", + args=[f"--benchmark_filter={filt}"])) + elif column == "rollup": + for d in sorted(p for p in (inputs / "rollup").glob("*/*") if (p / "flags").is_file()): + circuit = re.sub(r"(RollupArtifact|Artifact)$", "", d.parent.name) + flags = (d / "flags").read_text().split() + requires = (d / "requires").read_text().strip() if (d / "requires").is_file() else "bb" + cases.append(Case(f"rollup/{circuit}", f"golf-inputs/rollup/{circuit}", requires, d, + ["prove", *flags, "-b", str(d / "bytecode.gz"), "-w", str(d / "witness.gz"), + "-k", str(d / "vk")], vk=d / "vk", flags=flags)) + elif column == "avm": + for d in sorted(p for p in (inputs / "avm").iterdir() if (p / "avm_inputs.bin").is_file()): + name = re.sub(r"-[0-9a-f]+$", "", d.name) + pub = d / "avm_public_inputs.bin" + cases.append(Case(f"avm/{name}", f"golf-inputs/avm/{name}", "bb-avm", d, + ["avm_prove", "--avm-inputs", str(d / "avm_inputs.bin")], + avm_public_inputs=pub if pub.is_file() else None)) + else: + raise ValueError(f"unknown column {column}") + ids = [c.id for c in cases] + if len(set(ids)) != len(ids): + raise ValueError(f"two inputs share a name in {column}: {ids}") + return cases + + +def rotation(n_points: int, repeat: int, case_index: int) -> list[int]: + """The order the points take on one input in one repeat: rotated by repeat + input, so the first slot moves.""" + k = (repeat + case_index) % n_points + return [(k + j) % n_points for j in range(n_points)] + + +def aggregate(runs: list[dict]) -> dict: + """{case: {point: {ms, mb, runs} or {error}}}: fastest time and highest peak RSS over a point's runs. + + A point with any failed run on an input has no numbers for it, only the first error.""" + out: dict[str, dict[str, dict]] = {} + for r in runs: + cell = out.setdefault(r["case"], {}).setdefault(r["point"], {"runs": 0}) + if "error" in cell: + continue + if r["exit"] != 0: + out[r["case"]][r["point"]] = {"error": r.get("error") or f"exit {r['exit']}"} + continue + cell["runs"] += 1 + cell["ms"] = r["ms"] if "ms" not in cell else min(cell["ms"], r["ms"]) + cell["mb"] = r["mb"] if "mb" not in cell else max(cell["mb"], r["mb"]) + if r.get("swapped"): + cell["swapped"] = True + return out + + +def geomean(xs: list[float]) -> float | None: + xs = [x for x in xs if x > 0 and math.isfinite(x)] + return math.exp(sum(map(math.log, xs)) / len(xs)) if xs else None + + +def column_summary(cases: list[dict], point_ids: list[str]) -> dict: + """Per point: the geometric mean over inputs of its time and memory as a ratio of the first point's. + + Only inputs where both the point and the first point have numbers count; `n` says how many.""" + base = point_ids[0] + out = {} + for p in point_ids: + t, m = [], [] + for c in cases: + b, v = c["values"].get(base, {}), c["values"].get(p, {}) + if "ms" in b and "ms" in v and b["ms"] > 0 and b["mb"] > 0: + t.append(v["ms"] / b["ms"]) + m.append(v["mb"] / b["mb"]) + out[p] = {"time_ratio": geomean(t), "memory_ratio": geomean(m), "n": len(t)} + return out + + +def bench_entries(case: dict, point: str) -> list[dict]: + """aztec-packages' bench JSON entries for one input at one point (its `seconds` metric is in ms).""" + v = case["values"].get(point, {}) + if "ms" not in v: + return [] + return [{"name": f"{case['prefix']}/seconds", "value": round(v["ms"], 3), "unit": "ms"}, + {"name": f"{case['prefix']}/memory", "value": round(v["mb"], 1), "unit": "MB"}] + + +def pct(ratio: float | None) -> str: + return "–" if ratio is None else f"{(ratio - 1) * 100:+.1f}%" + + +# ---------------------------------------------------------------- running + + +def swap_out_pages() -> int | None: + try: + for line in Path("/proc/vmstat").read_text().splitlines(): + if line.startswith("pswpout "): + return int(line.split()[1]) + except OSError: + pass + return None + + +def measure(cmd: list[str], env: dict, log: Path) -> tuple[int, float, float, bool]: + """Runs cmd; returns (exit code, wall ms, peak RSS MB of that process, whether the machine swapped).""" + swap0 = swap_out_pages() + with open(log, "wb") as f: + start = time.perf_counter() + proc = subprocess.Popen(cmd, env=env, stdout=f, stderr=subprocess.STDOUT) + deadline = start + RUN_TIMEOUT_S + while True: + pid, status, rusage = os.wait4(proc.pid, os.WNOHANG) + if pid: + break + if time.perf_counter() > deadline: + proc.kill() + pid, status, rusage = os.wait4(proc.pid, 0) + break + time.sleep(0.05) + wall_ms = (time.perf_counter() - start) * 1000 + code = os.waitstatus_to_exitcode(status) + proc.returncode = code # reaped by wait4 above + swap1 = swap_out_pages() + # ru_maxrss is kilobytes on Linux, bytes on macOS. + rss_mb = rusage.ru_maxrss / (1e6 if sys.platform == "darwin" else 1e3) + return code, wall_ms, rss_mb, swap0 is not None and swap1 is not None and swap1 > swap0 + + +def tail(path: Path, n: int = 15) -> str: + try: + return "\n".join(path.read_text(errors="replace").splitlines()[-n:]) + except OSError: + return "" + + +def prove_cmd(case: Case, bins: Path, out: Path) -> list[str]: + exe = str(bins / case.binary) + if case.binary == "ultra_honk_bench": + return [exe, *case.args, f"--benchmark_out={out / 'gbench.json'}", "--benchmark_out_format=json"] + return [exe, *case.args, "-o", str(out)] + + +def verify_cmd(case: Case, base_bins: Path, out: Path) -> list[str] | None: + if case.id.startswith("client/"): + if not case.vk: + return None + return [str(base_bins / "bb"), "verify", "--scheme", "chonk", "-p", str(out / "proof"), "-k", str(case.vk)] + if case.id.startswith("rollup/"): + return [str(base_bins / case.binary), "verify", *case.flags, "-k", str(case.vk), "-p", str(out / "proof"), + "-i", str(out / "public_inputs")] + if case.id.startswith("avm/") and case.avm_public_inputs: + return [str(base_bins / "bb-avm"), "avm_verify", "-p", str(out / "proof"), + "--avm-public-inputs", str(case.avm_public_inputs)] + return None # the micro-benchmark writes no proof; avm_prove verifies its own proof + + +def cmd_run(a) -> int: + points = json.loads(Path(a.points).read_text()) + pids = [p["id"] for p in points] + bins = Path(a.bins) + cases = discover(a.column, Path(a.inputs) if a.inputs else None, Path(a.flows) if a.flows else None) + skipped = [c.id for c in cases if c.id in a.skip] + cases = [c for c in cases if c.id not in a.skip] + work = Path(a.work) + env = dict(os.environ, HARDWARE_CONCURRENCY=str(a.threads)) + deadline = time.time() + a.deadline_minutes * 60 + results = {"column": a.column, "repeats": a.repeats, "threads": a.threads, "points": pids, + "machine": machine_info(), "skipped": skipped, "cases": [], "runs": [], "stopped_early": False} + runs: list[dict] = results["runs"] + + def save(): + agg = aggregate(runs) + results["cases"] = [{"id": c.id, "prefix": c.prefix, "values": agg.get(c.id, {}), + "verified": verified.get(c.id, {})} for c in cases] + Path(a.out).write_text(json.dumps(results, indent=1)) + + verified: dict[str, dict] = {} + for r in range(a.repeats): + for i, case in enumerate(cases): + if time.time() > deadline: + results["stopped_early"] = True + print(f"::warning::Deadline reached: stopped before repeat {r + 1} of {case.id}", flush=True) + break + for j in rotation(len(pids), r, i): + pid = pids[j] + out = work / f"{i:03d}" / pid + shutil.rmtree(out, ignore_errors=True) + out.mkdir(parents=True) + log = work / f"{i:03d}-{pid}.log" + code, ms, mb, swapped = measure(prove_cmd(case, bins / pid, out), env, log) + run = {"case": case.id, "point": pid, "repeat": r, "exit": code, "ms": ms, "mb": mb, + "swapped": swapped} + if code == 0 and case.binary == "ultra_honk_bench": + try: + run["ms"] = gbench_ms(json.loads((out / "gbench.json").read_text())) + except (OSError, ValueError, KeyError, IndexError) as e: + run["exit"], run["error"] = 1, f"no benchmark result: {e}" + if code != 0: + why = "killed (out of memory?)" if code == -9 else f"exit {code}" + run["error"] = f"{why}\n{tail(log)}" + runs.append(run) + status = "ok" if run["exit"] == 0 else run["error"].splitlines()[0] + print(f"[{r + 1}/{a.repeats}] {case.id} @ {pid}: {run['ms'] / 1000:.2f} s, {mb:.0f} MB" + f"{' (swapped)' if swapped else ''} {status}", flush=True) + save() + else: + continue + break + + # Each point's last proof, checked by the first point's binary (the original bb). + for i, case in enumerate(cases): + for pid in pids: + out = work / f"{i:03d}" / pid + cmd = verify_cmd(case, bins / pids[0], out) + if cmd is None or not (out / "proof").exists(): + continue + log = work / f"{i:03d}-{pid}-verify.log" + code, *_ = measure(cmd, env, log) + verified.setdefault(case.id, {})[pid] = code == 0 + print(f"verify {case.id} @ {pid}: {'ok' if code == 0 else 'FAILED'}", flush=True) + if code != 0: + print(tail(log), flush=True) + save() + bad = [f"{c} @ {p}" for c, v in verified.items() for p, ok in v.items() if not ok] + if bad: + print(f"::error::Proofs that don't verify: {', '.join(bad)}") + return 1 if bad else 0 + + +def gbench_ms(doc: dict) -> float: + b = doc["benchmarks"][0] + scale = {"ns": 1e-6, "us": 1e-3, "ms": 1.0, "s": 1e3}[b["time_unit"]] + return b["real_time"] * scale + + +def machine_info() -> dict: + info = {"cpus": os.cpu_count()} + try: + for line in Path("/proc/cpuinfo").read_text().splitlines(): + if line.startswith("model name"): + info["cpu"] = line.split(":", 1)[1].strip() + break + for line in Path("/proc/meminfo").read_text().splitlines(): + if line.startswith("MemTotal"): + info["memory_gb"] = round(int(line.split()[1]) / 1024 / 1024, 1) + except OSError: + pass + runner = os.environ.get("RUNNER_NAME") + if runner: + info["runner"] = runner + return info + + +# ---------------------------------------------------------------- publishing + + +def build_data(points: list[dict], results: list[dict], run_url: str | None, now: str) -> dict: + pids = [p["id"] for p in points] + order = {c: i for i, c in enumerate(COLUMNS)} + columns = [] + for res in sorted(results, key=lambda r: order.get(r["column"], 99)): + if res["points"] != pids: + raise ValueError(f"{res['column']} was timed for {res['points']}, not {pids}") + columns.append({ + "column": res["column"], "title": COLUMN_TITLES.get(res["column"], res["column"]), + "machine": res["machine"], "threads": res["threads"], "repeats": res["repeats"], + "skipped": res["skipped"], "stopped_early": res["stopped_early"], "cases": res["cases"], + "summary": column_summary(res["cases"], pids), + }) + return {"generated": now, "run_url": run_url, "points": points, "columns": columns} + + +def summary_markdown(data: dict) -> str: + pts = data["points"] + lines = ["# bb-boost benchmarks", ""] + if data.get("run_url"): + lines += [f"Run: {data['run_url']}", ""] + for col in data["columns"]: + m = col["machine"] + lines += [f"## {col['title']}", "", + f"{m.get('cpus')} CPUs ({m.get('cpu', '?')}), {m.get('memory_gb', '?')} GB; " + f"`HARDWARE_CONCURRENCY={col['threads']}`; fastest of {col['repeats']} runs, highest peak RSS." + + (" **Stopped early (time limit)**: some inputs have fewer runs." if col["stopped_early"] else "") + + (f" Skipped: {', '.join(col['skipped'])}." if col["skipped"] else ""), ""] + lines.append("| | " + " | ".join(p["label"] for p in pts) + " |") + lines.append("|---|" + "---:|" * len(pts)) + s = col["summary"] + lines.append("| **Time vs " + pts[0]["label"] + "** (geomean) | " + + " | ".join(f"{pct(s[p['id']]['time_ratio'])} (n={s[p['id']]['n']})" for p in pts) + " |") + lines.append("| **Memory vs " + pts[0]["label"] + "** | " + + " | ".join(pct(s[p["id"]]["memory_ratio"]) for p in pts) + " |") + for c in col["cases"]: + cells = [] + base = c["values"].get(pts[0]["id"], {}) + for p in pts: + v = c["values"].get(p["id"], {}) + if "ms" not in v: + cells.append("failed" if "error" in v else "–") + continue + cell = f"{v['ms'] / 1000:.2f} s, {v['mb'] / 1000:.2f} GB" + if p is not pts[0] and "ms" in base: + cell += f" ({pct(v['ms'] / base['ms'])})" + if c.get("verified", {}).get(p["id"]) is False: + cell += " **proof doesn't verify**" + if v.get("swapped"): + cell += " (swapped)" + cells.append(cell) + lines.append(f"| {c['id']} | " + " | ".join(cells) + " |") + lines.append("") + return "\n".join(lines) + + +def cmd_publish(a) -> int: + points = json.loads(Path(a.points).read_text()) + results = [json.loads(p.read_text()) for p in sorted(Path(a.results).rglob("results-*.json"))] + if not results: + print("::error::No results to publish") + return 1 + now = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + data = build_data(points, results, a.run_url, now) + out = Path(a.out) + out.mkdir(parents=True, exist_ok=True) + (out / "data.json").write_text(json.dumps(data, indent=1)) + for p in points: + entries = [e for col in data["columns"] for c in col["cases"] for e in bench_entries(c, p["id"])] + (out / f"{p['id']}.bench.json").write_text(json.dumps(entries, indent=1)) + (out / "summary.md").write_text(summary_markdown(data)) + return 0 + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = ap.add_subparsers(dest="cmd", required=True) + r = sub.add_parser("run") + r.add_argument("--points", required=True) + r.add_argument("--bins", required=True, help="one folder per point id, holding its binaries") + r.add_argument("--column", required=True, choices=COLUMNS) + r.add_argument("--inputs", help="the bench inputs (rollup/, avm/, client//vk)") + r.add_argument("--flows", help="the pinned Chonk flows") + r.add_argument("--skip", nargs="*", default=[], help="input ids to leave out, e.g. rollup/Root") + r.add_argument("--repeats", type=int, default=3) + r.add_argument("--threads", type=int, default=os.cpu_count()) + r.add_argument("--deadline-minutes", type=float, default=290) + r.add_argument("--work", default="bench-work") + r.add_argument("--out", required=True) + p = sub.add_parser("publish") + p.add_argument("--points", required=True) + p.add_argument("--results", required=True) + p.add_argument("--out", required=True) + p.add_argument("--run-url") + a = ap.parse_args(argv) + return cmd_run(a) if a.cmd == "run" else cmd_publish(a) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/bench/index.html b/.github/bench/index.html new file mode 100644 index 0000000..2a67e15 --- /dev/null +++ b/.github/bench/index.html @@ -0,0 +1,225 @@ + + + + + +bb-boost benchmarks + + + +
+

bb-boost benchmarks

+

Loading…

+
    +

    Each column was timed on its own GitHub-hosted runner, with every point taking turns on the same + machine: time is the fastest of the runs, memory the highest peak RSS. Compare points within a column; hosted + runners are small (4 CPUs, 16 GB), so absolute times are far from a many-core prover machine's. Changes are + against the first point; the column's summary is the geometric mean over its inputs.

    +
    + Tables show + + +
    +
    +

    Raw data: data.json, and per point in aztec-packages' bench format + ([{name, value, unit}]): . Each run's data stays under runs/<run id>/.

    +
    + + + + diff --git a/.github/bench/points.json b/.github/bench/points.json new file mode 100644 index 0000000..f9a7ba7 --- /dev/null +++ b/.github/bench/points.json @@ -0,0 +1,30 @@ +[ + { + "id": "base", + "label": "v6.1.0", + "title": "bb v6.1.0, as released by aztec-packages", + "ref": "806d6ca51baf4e5eeafd7d54691d59176dce249b", + "pr": null + }, + { + "id": "pr1", + "label": "+ #1 AVM", + "title": "Season 2 leaders (1/3): the AVM leader's stack", + "ref": "fd15e950e66ab081e2c01078f30c15d923d034d6", + "pr": 1 + }, + { + "id": "pr2", + "label": "+ #2 rollup", + "title": "Season 2 leaders (2/3): the rollup leader's stack", + "ref": "812cd13d50bfb8cb25a17b7723bfbb163d5ea2fd", + "pr": 2 + }, + { + "id": "pr3", + "label": "+ #3 client-WASM", + "title": "Season 2 leaders (3/3): the client-WASM leader's stack", + "ref": "eb054124f0c70937d5db3401fad980a09f640d8f", + "pr": 3 + } +] diff --git a/.github/bench/test_bench.py b/.github/bench/test_bench.py new file mode 100644 index 0000000..3bf684c --- /dev/null +++ b/.github/bench/test_bench.py @@ -0,0 +1,232 @@ +#!/usr/bin/env python3 +"""Tests for bench.py: python3 -m unittest discover -s .github/bench""" +import contextlib +import io +import json +import math +import os +import stat +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent)) +import bench # noqa: E402 + + +def run(case, point, repeat, ms, mb, exit=0, **kw): + return {"case": case, "point": point, "repeat": repeat, "exit": exit, "ms": ms, "mb": mb, **kw} + + +class Aggregate(unittest.TestCase): + def test_fastest_time_and_highest_memory(self): + # p0: times 300, 200, 250 -> fastest 200 (mean 250, last 250); memory 10, 30, 20 -> highest 30 (last 20). + # p1: times 100, 150, 90 -> fastest 90, on another repeat than p0's; memory 50, 40, 45 -> highest 50 (first). + runs = [run("A", "p0", 0, 300, 10), run("A", "p1", 0, 100, 50), + run("A", "p0", 1, 200, 30), run("A", "p1", 1, 150, 40), + run("A", "p0", 2, 250, 20), run("A", "p1", 2, 90, 45)] + agg = bench.aggregate(runs) + self.assertEqual(agg["A"]["p0"], {"runs": 3, "ms": 200, "mb": 30}) + self.assertEqual(agg["A"]["p1"], {"runs": 3, "ms": 90, "mb": 50}) + + def test_a_failed_run_drops_the_points_numbers(self): + # One good run, then a kill: no numbers, the error kept; a later good run doesn't bring them back. + runs = [run("A", "p0", 0, 100, 10), run("A", "p0", 1, 0, 0, exit=-9, error="killed (out of memory?)"), + run("A", "p0", 2, 50, 5)] + self.assertEqual(bench.aggregate(runs)["A"]["p0"], {"error": "killed (out of memory?)"}) + + def test_failure_of_one_point_leaves_the_others(self): + runs = [run("A", "p0", 0, 100, 10), run("A", "p1", 0, 0, 0, exit=1)] + agg = bench.aggregate(runs) + self.assertEqual(agg["A"]["p0"]["ms"], 100) + self.assertEqual(agg["A"]["p1"], {"error": "exit 1"}) + + def test_swapping_is_flagged(self): + runs = [run("A", "p0", 0, 100, 10, swapped=False), run("A", "p0", 1, 120, 10, swapped=True)] + self.assertTrue(bench.aggregate(runs)["A"]["p0"]["swapped"]) + + +class Rotation(unittest.TestCase): + def test_rotates_by_repeat_and_input(self): + self.assertEqual(bench.rotation(4, 0, 0), [0, 1, 2, 3]) + self.assertEqual(bench.rotation(4, 1, 0), [1, 2, 3, 0]) + self.assertEqual(bench.rotation(4, 0, 2), [2, 3, 0, 1]) + self.assertEqual(bench.rotation(4, 2, 3), [1, 2, 3, 0]) # (2 + 3) % 4 = 1 + + def test_every_point_goes_first_once_over_n_inputs(self): + firsts = [bench.rotation(4, 1, i)[0] for i in range(4)] + self.assertEqual(sorted(firsts), [0, 1, 2, 3]) + + def test_each_order_holds_every_point_once(self): + for r in range(3): + for i in range(5): + self.assertEqual(sorted(bench.rotation(4, r, i)), [0, 1, 2, 3]) + + +class Summary(unittest.TestCase): + CASES = [ + {"id": "A", "prefix": "x/A", "values": {"p0": {"ms": 200, "mb": 100}, "p1": {"ms": 100, "mb": 100}}}, + {"id": "B", "prefix": "x/B", "values": {"p0": {"ms": 400, "mb": 200}, "p1": {"ms": 400, "mb": 50}}}, + {"id": "C", "prefix": "x/C", "values": {"p0": {"ms": 1000, "mb": 10}, "p1": {"error": "exit 1"}}}, + {"id": "D", "prefix": "x/D", "values": {"p0": {"error": "exit 1"}, "p1": {"ms": 5, "mb": 5}}}, + ] + + def test_geometric_mean_of_ratios_over_inputs_both_have(self): + s = bench.column_summary(self.CASES, ["p0", "p1"]) + # p1 time: A 100/200 = 0.5, B 400/400 = 1.0; C (p1 failed) and D (base failed) don't count. + # geomean = sqrt(0.5 * 1.0) = 0.70710678 (the arithmetic mean would be 0.75). + self.assertAlmostEqual(s["p1"]["time_ratio"], math.sqrt(0.5), places=9) + # p1 memory: A 100/100 = 1.0, B 50/200 = 0.25 -> sqrt(0.25) = 0.5. + self.assertAlmostEqual(s["p1"]["memory_ratio"], 0.5, places=9) + self.assertEqual(s["p1"]["n"], 2) + # The base against itself: A, B and C, all 1. + self.assertEqual(s["p0"], {"time_ratio": 1.0, "memory_ratio": 1.0, "n": 3}) + + def test_no_common_inputs(self): + s = bench.column_summary(self.CASES[2:3], ["p0", "p1"]) + self.assertEqual(s["p1"], {"time_ratio": None, "memory_ratio": None, "n": 0}) + + def test_pct(self): + self.assertEqual(bench.pct(math.sqrt(0.5)), "-29.3%") # (0.7071 - 1) * 100 = -29.29 + self.assertEqual(bench.pct(1.0951), "+9.5%") + self.assertEqual(bench.pct(None), "–") + + def test_geomean(self): + self.assertAlmostEqual(bench.geomean([2, 8]), 4.0) # sqrt(16) + self.assertIsNone(bench.geomean([])) + self.assertIsNone(bench.geomean([0.0, -1.0])) + + +class Output(unittest.TestCase): + def test_bench_entries_use_aztec_packages_names_and_units(self): + case = {"prefix": "golf-inputs/rollup/Root", "values": {"p0": {"ms": 1234.56789, "mb": 15700.04}}} + self.assertEqual(bench.bench_entries(case, "p0"), [ + {"name": "golf-inputs/rollup/Root/seconds", "value": 1234.568, "unit": "ms"}, + {"name": "golf-inputs/rollup/Root/memory", "value": 15700.0, "unit": "MB"}]) + self.assertEqual(bench.bench_entries(case, "p1"), []) + + def test_gbench_time_units(self): + self.assertAlmostEqual(bench.gbench_ms({"benchmarks": [{"real_time": 1234.5, "time_unit": "us"}]}), 1.2345) + self.assertAlmostEqual(bench.gbench_ms({"benchmarks": [{"real_time": 4847.5, "time_unit": "ms"}]}), 4847.5) + self.assertAlmostEqual(bench.gbench_ms({"benchmarks": [{"real_time": 2.0, "time_unit": "s"}]}), 2000.0) + + def test_build_data_orders_columns_and_checks_points(self): + pts = [{"id": "p0", "label": "base"}, {"id": "p1", "label": "+1"}] + res = lambda col, ids=("p0", "p1"): {"column": col, "points": list(ids), "machine": {}, "threads": 4, + "repeats": 3, "skipped": [], "stopped_early": False, + "cases": Summary.CASES[:2]} + data = bench.build_data(pts, [res("avm"), res("client")], None, "now") + self.assertEqual([c["column"] for c in data["columns"]], ["client", "avm"]) + with self.assertRaises(ValueError): + bench.build_data(pts, [res("avm", ("p1", "p0"))], None, "now") + md = bench.summary_markdown(data) + self.assertIn("| **Time vs base** (geomean) | +0.0% (n=2) | -29.3% (n=2) |", md) + self.assertIn("| A | 0.20 s, 0.10 GB | 0.10 s, 0.10 GB (-50.0%) |", md) + + +class Discover(unittest.TestCase): + def test_names(self): + with tempfile.TemporaryDirectory() as t: + t = Path(t) + for circuit, req in (("RootRollupArtifact", "bb"), ("PublicTxBaseRollupArtifact", "bb-avm"), + ("InboxParity4Artifact", "bb"), ("PublicChonkVerifier", "bb")): + d = t / "in" / "rollup" / circuit / "abc123" + d.mkdir(parents=True) + (d / "flags").write_text("--scheme ultra_honk --disable_zk\n") + (d / "requires").write_text(req + "\n") + a = t / "in" / "avm" / "megabulk-b3775dcaea13" + a.mkdir(parents=True) + (a / "avm_inputs.bin").write_bytes(b"x") + for flow in ("f1", "f2"): + (t / "flows" / flow).mkdir(parents=True) + (t / "flows" / flow / "ivc-inputs.msgpack").write_bytes(b"x") + (t / "in" / "client" / "f1").mkdir(parents=True) + (t / "in" / "client" / "f1" / "vk").write_bytes(b"k") + + rollup = {c.id: c for c in bench.discover("rollup", t / "in", None)} + self.assertEqual(sorted(rollup), ["rollup/InboxParity4", "rollup/PublicChonkVerifier", + "rollup/PublicTxBase", "rollup/Root"]) + self.assertEqual(rollup["rollup/PublicTxBase"].binary, "bb-avm") + self.assertEqual(rollup["rollup/Root"].prefix, "golf-inputs/rollup/Root") + self.assertEqual(rollup["rollup/Root"].args[:4], ["prove", "--scheme", "ultra_honk", "--disable_zk"]) + avm = bench.discover("avm", t / "in", None) + self.assertEqual([(c.id, c.prefix, c.avm_public_inputs) for c in avm], + [("avm/megabulk", "golf-inputs/avm/megabulk", None)]) + client = bench.discover("client", t / "in", t / "flows") + self.assertEqual([c.prefix for c in client], ["aztec-packages/app-proving/f1/native", + "aztec-packages/app-proving/f2/native"]) + self.assertEqual([c.vk is not None for c in client], [True, False]) + self.assertEqual([c.id for c in bench.discover("micro", None, None)], + ["micro/ultra_honk", "micro/ultra_honk_zk"]) + + +FAKE_BB = """#!/usr/bin/env python3 +# A fake bb: `prove ... -o OUT` sleeps SLEEP s, writes PROOF to OUT/proof; `verify ... -p P` checks P says good +# (or, if LENIENT, accepts anything, as a broken bb might). +import sys, time +args = sys.argv[1:] +if args[0] == "verify": + sys.exit(0 if {lenient} or open(args[args.index("-p") + 1]).read() == "good" else 1) +if {fail}: + print("boom"); sys.exit(3) +time.sleep({sleep}) +out = args[args.index("-o") + 1] +open(out + "/proof", "w").write("{proof}") +open(out + "/public_inputs", "w").write("") +""" + + +class RunEndToEnd(unittest.TestCase): + def test_run_times_every_point_and_checks_proofs_with_the_first(self): + with tempfile.TemporaryDirectory() as t: + t = Path(t) + d = t / "in" / "rollup" / "TxMergeRollupArtifact" / "abc" + d.mkdir(parents=True) + (d / "flags").write_text("--scheme ultra_honk\n") + for name in ("vk", "bytecode.gz", "witness.gz"): + (d / name).write_bytes(b"x") + # p0: the original; p1: faster; p2: fast but its proof is wrong, and its own verifier accepts it; p3: fails. + fakes = {"p0": (0.2, "good", False, False), "p1": (0.05, "good", False, False), + "p2": (0.01, "bad", False, True), "p3": (0, "good", True, False)} + for pid, (sleep, proof, fail, lenient) in fakes.items(): + (t / "bins" / pid).mkdir(parents=True) + exe = t / "bins" / pid / "bb" + exe.write_text(FAKE_BB.format(sleep=sleep, proof=proof, fail=fail, lenient=lenient)) + exe.chmod(exe.stat().st_mode | stat.S_IEXEC) + (t / "points.json").write_text(json.dumps([{"id": p} for p in fakes])) + out = t / "results-rollup.json" + with contextlib.redirect_stdout(io.StringIO()) as printed: # keep its ::error:: line out of CI logs + code = bench.main(["run", "--points", str(t / "points.json"), "--bins", str(t / "bins"), + "--column", "rollup", "--inputs", str(t / "in"), "--repeats", "2", + "--threads", "2", "--work", str(t / "work"), "--out", str(out)]) + self.assertIn("::error::Proofs that don't verify: rollup/TxMerge @ p2", printed.getvalue()) + self.assertEqual(code, 1) # p2's proof doesn't verify + res = json.loads(out.read_text()) + self.assertEqual(len(res["runs"]), 8) # 1 input x 4 points x 2 repeats + # Repeat 0 starts with p0, repeat 1 with p1. + self.assertEqual([r["point"] for r in res["runs"]], ["p0", "p1", "p2", "p3", "p1", "p2", "p3", "p0"]) + (case,) = res["cases"] + self.assertEqual(case["id"], "rollup/TxMerge") + v = case["values"] + self.assertGreaterEqual(v["p0"]["ms"], 200) + self.assertLess(v["p1"]["ms"], v["p0"]["ms"]) + self.assertEqual(v["p0"]["runs"], 2) + self.assertTrue(v["p3"]["error"].startswith("exit 3\n")) + self.assertIn("boom", v["p3"]["error"]) + self.assertEqual(case["verified"], {"p0": True, "p1": True, "p2": False}) + + def test_measure_reports_the_childs_peak_memory(self): + with tempfile.TemporaryDirectory() as t: + code, ms, mb, _ = bench.measure( + [sys.executable, "-c", "b = bytearray(200 * 1000 * 1000); b[::4096] = b'x' * len(b[::4096])"], + dict(os.environ), Path(t) / "log") + self.assertEqual(code, 0) + self.assertGreater(mb, 200) # at least the 200 MB it touched + self.assertLess(mb, 400) + code, *_ = bench.measure([sys.executable, "-c", "raise SystemExit(7)"], dict(os.environ), Path(t) / "l2") + self.assertEqual(code, 7) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/bench.yml b/.github/workflows/bench.yml new file mode 100644 index 0000000..3cacae9 --- /dev/null +++ b/.github/workflows/bench.yml @@ -0,0 +1,252 @@ +# Benchmarks: bb at each point of .github/bench/points.json (v6.1.0, then each merged leader's stack), timed in turns +# on the same machine, per column. Run by hand (Actions > bench > Run workflow); a dispatched run publishes its +# results to the gh-pages branch (GitHub Pages). A pull request that changes the benchmarks runs them without +# publishing. +# +# Inputs: +# - client: aztec-packages' pinned Chonk flows (barretenberg/cpp/scripts/chonk-inputs.hash), native; +# - micro: aztec-packages' UltraHonk micro-benchmark (2^20 gates, with and without ZK); +# - rollup, avm: the release asset bench-inputs-v6.1.0 (aztec-golf's season 2 public rollup and AVM inputs; see its +# README.md). Root is skipped by default: the original peaks near 16 GB, a hosted runner's whole memory. +# +# Hosted runners have 4 CPUs and 16 GB, so the numbers are far from those of a many-core prover machine; compare +# points within a column, not columns or runs (each column runs on its own machine). Swap is turned off while timing, +# so an input that doesn't fit fails instead of being timed while swapping. +name: bench + +on: + workflow_dispatch: + inputs: + columns: + description: Columns to time (space-separated, of client micro rollup avm) + default: client micro rollup avm + skip: + description: Inputs to leave out (space-separated ids such as rollup/Root, or none) + default: rollup/Root + repeats: + description: Runs per input and point + default: "3" + publish: + description: Publish the results to GitHub Pages + type: boolean + default: true + pull_request: + paths: + - .github/workflows/bench.yml + - .github/bench/** + +permissions: + contents: read + +concurrency: + group: bench-${{ github.ref }} + cancel-in-progress: true + +env: + ZIG_VERSION: 0.15.1 + ZIG_SHA256: c61c5da6edeea14ca51ecd5e4520c6f4189ef5250383db33d01848293bfafe05 + INPUTS_URL: https://github.com/AztecProtocol/bb-boost/releases/download/bench-inputs-v6.1.0/bb-boost-bench-inputs-v6.1.0.tar.gz + INPUTS_SHA256: 710f42309b8aff61d31f8568a7683f8b18e6f502f95b45a898912c7c92e7e0cc + COREPACK_ENABLE_DOWNLOAD_PROMPT: "0" + +jobs: + setup: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + outputs: + points: ${{ steps.config.outputs.points }} + columns: ${{ steps.config.outputs.columns }} + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + sparse-checkout: .github/bench + - name: Test the benchmark script + run: python3 -m unittest discover -s .github/bench -v + - name: Points and columns + id: config + env: + COLUMNS: ${{ inputs.columns || 'client micro rollup avm' }} + run: | + echo "points=$(jq -c . .github/bench/points.json)" >> "$GITHUB_OUTPUT" + echo "columns=$(python3 -c 'import json, os; c = os.environ["COLUMNS"].split(); assert c and set(c) <= {"client", "micro", "rollup", "avm"}, c; print(json.dumps(c))')" >> "$GITHUB_OUTPUT" + + transpiler: + # The AVM transpiler (linked into bb-avm) is the same at every point: built once, from the first. + needs: setup + runs-on: ubuntu-24.04 + timeout-minutes: 60 + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ fromJSON(needs.setup.outputs.points)[0].ref }} + - name: Noir (the transpiler's dependency) + run: git submodule update --init --depth 1 noir/noir-repo + - name: Build libavm_transpiler.a + working-directory: avm-transpiler + run: cargo build --release --locked --lib + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: bench-avm-transpiler + path: avm-transpiler/target/release/libavm_transpiler.a + retention-days: 3 + + build: + # Like bb.yml's binaries job, at each point, plus the micro-benchmark. + needs: [setup, transpiler] + runs-on: ubuntu-24.04 + timeout-minutes: 360 + strategy: + fail-fast: true + matrix: + point: ${{ fromJSON(needs.setup.outputs.points) }} + name: build ${{ matrix.point.id }} + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ matrix.point.ref }} + - name: Disk and swap + run: | + sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache/CodeQL + sudo swapoff -a && sudo rm -f /mnt/swapfile /swapfile + sudo fallocate -l 16G /mnt/swapfile && sudo chmod 600 /mnt/swapfile && sudo mkswap /mnt/swapfile && sudo swapon /mnt/swapfile + free -g; df -h / /mnt + - name: Tools (Zig, Ninja, clang-format, Yarn) + run: | + curl -fsSL -o /tmp/zig.tar.xz "https://ziglang.org/download/${ZIG_VERSION}/zig-x86_64-linux-${ZIG_VERSION}.tar.xz" + echo "${ZIG_SHA256} /tmp/zig.tar.xz" | sha256sum -c - + sudo mkdir -p /opt/zig && sudo tar -xJf /tmp/zig.tar.xz -C /opt/zig --strip-components=1 + echo /opt/zig >> "$GITHUB_PATH" + sudo apt-get update -q && sudo apt-get install -y -q ninja-build clang-format-20 + corepack enable + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: bench-avm-transpiler + path: avm-transpiler/target/release + - name: Configure + working-directory: barretenberg/cpp + run: cmake --preset clang20 + - name: Build bb, bb-avm and ultra_honk_bench + working-directory: barretenberg/cpp + run: cmake --build --preset clang20 --parallel "$(nproc)" --target bb bb-avm ultra_honk_bench + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: bench-bin-${{ matrix.point.id }} + path: | + barretenberg/cpp/build/bin/bb + barretenberg/cpp/build/bin/bb-avm + barretenberg/cpp/build/bin/ultra_honk_bench + retention-days: 7 + + time: + needs: [setup, build] + runs-on: ubuntu-24.04 + timeout-minutes: 355 + strategy: + fail-fast: false + matrix: + column: ${{ fromJSON(needs.setup.outputs.columns) }} + name: time ${{ matrix.column }} + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + sparse-checkout: | + .github/bench + barretenberg/crs + barretenberg/cpp/scripts/chonk-inputs.hash + sparse-checkout-cone-mode: false + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + pattern: bench-bin-* + path: bins + - name: Binaries + # bins/bench-bin-/ -> bins// + run: | + for d in bins/bench-bin-*; do mv "$d" "bins/${d#bins/bench-bin-}"; done + chmod +x bins/*/* + ls -l bins/* + - name: CRS + run: barretenberg/crs/bootstrap.sh + - name: Pinned Chonk flows + if: matrix.column == 'client' + run: | + hash=$(tr -d ' \r\n' < barretenberg/cpp/scripts/chonk-inputs.hash) + [[ "$hash" =~ ^[a-f0-9]{16}$ ]] || { echo "::error::Bad chonk-inputs.hash: $hash"; exit 1; } + curl -fsSL -o /tmp/chonk-inputs.tar.gz "https://aztec-ci-artifacts.s3.us-east-2.amazonaws.com/protocol/bb-chonk-inputs-$hash.tar.gz" + [ "$(sha256sum /tmp/chonk-inputs.tar.gz | cut -c1-16)" = "$hash" ] || { echo "::error::Pinned Chonk inputs don't match $hash"; exit 1; } + mkdir -p flows && tar -xzf /tmp/chonk-inputs.tar.gz -C flows + ls flows + - name: Bench inputs + if: matrix.column != 'micro' + run: | + curl -fsSL -o /tmp/inputs.tar.gz "$INPUTS_URL" + echo "${INPUTS_SHA256} /tmp/inputs.tar.gz" | sha256sum -c - + mkdir -p inputs && tar -xzf /tmp/inputs.tar.gz -C inputs --strip-components=1 + - name: Machine + # No swap while timing: an input that doesn't fit in memory fails rather than being timed while swapping. + run: | + sudo swapoff -a + nproc; free -m; lscpu | grep -E 'Model name|Thread|Core|Socket' + - name: Time ${{ matrix.column }} + env: + SKIP: ${{ inputs.skip || 'rollup/Root' }} + REPEATS: ${{ inputs.repeats || '3' }} + run: | + skip=(); [ "$SKIP" = none ] || read -ra skip <<< "$SKIP" + args=(); [ -d inputs ] && args+=(--inputs inputs); [ -d flows ] && args+=(--flows flows) + python3 .github/bench/bench.py run --points .github/bench/points.json --bins bins \ + --column ${{ matrix.column }} "${args[@]}" --skip "${skip[@]}" --repeats "$REPEATS" \ + --out results-${{ matrix.column }}.json + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + if: ${{ !cancelled() }} + with: + name: bench-results-${{ matrix.column }} + path: results-${{ matrix.column }}.json + if-no-files-found: ignore + retention-days: 90 + + publish: + needs: time + if: ${{ !cancelled() }} + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + contents: write + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + sparse-checkout: .github/bench + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + pattern: bench-results-* + path: results + - name: Merge the results + run: | + python3 .github/bench/bench.py publish --points .github/bench/points.json --results results --out site \ + --run-url "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" + cat site/summary.md >> "$GITHUB_STEP_SUMMARY" + cp .github/bench/index.html site/ + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: bench-site + path: site + retention-days: 90 + - name: Publish to gh-pages + if: github.event_name == 'workflow_dispatch' && inputs.publish + env: + GH_TOKEN: ${{ github.token }} + run: | + remote="https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" + if git ls-remote --exit-code --heads "$remote" gh-pages >/dev/null; then + git clone --depth 1 --branch gh-pages "$remote" pages + else + git init -b gh-pages pages && git -C pages remote add origin "$remote" + fi + mkdir -p "pages/runs/${GITHUB_RUN_ID}" + cp site/index.html site/data.json site/*.bench.json pages/ + cp site/data.json site/*.bench.json "pages/runs/${GITHUB_RUN_ID}/" + touch pages/.nojekyll + cd pages + git add -A + git -c user.name="github-actions[bot]" -c user.email="41898282+github-actions[bot]@users.noreply.github.com" \ + commit -m "Benchmarks from run ${GITHUB_RUN_ID} (${GITHUB_SHA::10})" + git push origin gh-pages