From 6d34bc8781cfb0b81b1f6dfafc71ce0d3c1981be Mon Sep 17 00:00:00 2001 From: Chandler Carruth Date: Sat, 7 Nov 2026 03:40:03 +0000 Subject: [PATCH] TODO: Write PR description for Bencher BMF export and suite runner. Notes to mention: - Extends `scripts/bench_runner.py` with `--output=bmf`, `--output_file`, `--benchmark_prefix`, and `--no_extra_metrics` (routing Rich progress/log output to `stderr` when emitting structured JSON/BMF). - Exports `latency` in nanoseconds (`real_time` for `/real_time` or `--wall_time`, `cpu_time` otherwise) plus opted-in extra counters using non-parametric medians and `quantile_test` confidence intervals (omitting interval bounds when non-finite for small sample counts and enforcing `allow_nan=False`). - Adds `toolchain/benchmarking/bencher_suites.py` and `toolchain/benchmarking/run_bencher.py` (with unit tests) to configure `prelude_benchmark` and in-process `compile_benchmark` (`::` prefixes, `PRELUDE_MEM_METRICS` allowlist, continuous vs. nightly size filters, `--targets-file` intersection, strict BMF schema/allowlist validation, and PR vs. trunk threshold profiles). Assisted-by: Antigravity with Gemini --- scripts/bench_runner.py | 196 ++++++++- scripts/bench_runner_test.py | 176 ++++++++ toolchain/benchmarking/BUILD | 24 ++ toolchain/benchmarking/bencher_suites.py | 201 +++++++++ toolchain/benchmarking/run_bencher.py | 461 +++++++++++++++++++++ toolchain/benchmarking/run_bencher_test.py | 274 ++++++++++++ 6 files changed, 1314 insertions(+), 18 deletions(-) create mode 100755 scripts/bench_runner_test.py create mode 100644 toolchain/benchmarking/bencher_suites.py create mode 100755 toolchain/benchmarking/run_bencher.py create mode 100644 toolchain/benchmarking/run_bencher_test.py diff --git a/scripts/bench_runner.py b/scripts/bench_runner.py index 5baaae5da81c..95bf80a520c2 100755 --- a/scripts/bench_runner.py +++ b/scripts/bench_runner.py @@ -184,6 +184,11 @@ binary. type=str, help="A regex filter on the names of extra metrics to display.", ) + parser.add_argument( + "--no_extra_metrics", + action="store_true", + help="Disable collecting extra non-time metrics.", + ) parser.add_argument( "--alpha", default=0.05, @@ -196,16 +201,38 @@ compute the confidence intervals for individual metrics. ) parser.add_argument( "--output", - choices=["console", "json"], + choices=["console", "json", "bmf"], default="console", help=""" -Output format to use, note that `json` output doesn't do any analysis of the -results, and just dumps the aggregate JSON data from the repeated runs. +Output format to use. `json` dumps raw run data without analysis. `bmf` outputs +Bencher Metric Format medians and confidence intervals. """.strip(), ) + parser.add_argument( + "--output_file", + metavar="FILE", + type=Path, + help="Write `json` or `bmf` output to FILE instead of stdout.", + ) + parser.add_argument( + "--benchmark_prefix", + default="", + metavar="PREFIX", + type=str, + help="Prefix prepended to each benchmark name in `bmf` output.", + ) return parser.parse_args(args=args) +# Multipliers to convert Google Benchmark `time_unit` values into nanoseconds. +TIME_UNIT_TO_NS: dict[str, float] = { + "ns": 1.0, + "us": 1e3, + "ms": 1e6, + "s": 1e9, +} + + # Default arguments that will be passed even when arguments are passed with # `--benchmark_args` to the script. These can be undone by overriding them in # explicitly passed arguments. @@ -734,7 +761,9 @@ def run_benchmark_binary( runs_data = [] unique_stderr: list[bytes] = [] for _ in track( - range(num_runs), description=f"Running {binary_path.name}..." + range(num_runs), + description=f"Running {binary_path.name}...", + console=console, ): p = subprocess.run( run_cmd, @@ -855,13 +884,14 @@ def get_benchmark_names_and_metrics( ) sys.exit(1) - # Add any extra metrics from this benchmark. - for key in benchmark.keys(): - if key in metrics or key in IGNORED_BENCHMARK_KEYS: - continue - if metrics_filter and not re.search(metrics_filter, key): - continue - metrics.append(key) + # Add any extra metrics from this benchmark unless disabled. + if not parsed_args.no_extra_metrics: + for key in benchmark.keys(): + if key in metrics or key in IGNORED_BENCHMARK_KEYS: + continue + if metrics_filter and not re.search(metrics_filter, key): + continue + metrics.append(key) benchmark_names = sorted( list(benchmark_name_set), key=lambda name: benchmark_name_indices[name] @@ -1083,9 +1113,112 @@ def print_results_table( console.print(table) +def compute_bmf_metric(alpha: float, values: list[float]) -> dict[str, float]: + """Computes a Bencher Metric Format entry from repeated sample values. + + Returns a dictionary with `value` set to the sample median and, when at + least two runs were collected and a finite confidence interval is available, + `lower_value` and `upper_value` bounds at confidence level `1 - alpha`. + """ + median = float(np.median(values)) + if len(values) < 2: + return {"value": median} + + if all(v == values[0] for v in values): + return { + "value": median, + "lower_value": median, + "upper_value": median, + } + + median_ci = sp.stats.quantile_test(values, q=median).confidence_interval( + confidence_level=(1.0 - alpha) + ) + if math.isfinite(median_ci.low) and math.isfinite(median_ci.high): + return { + "value": median, + "lower_value": float(median_ci.low), + "upper_value": float(median_ci.high), + } + + return {"value": median} + + +def compute_bmf_results( + console: Console, + parsed_args: argparse.Namespace, + exp_runs: list[dict[str, Any]], +) -> dict[str, dict[str, dict[str, float]]]: + """Computes Bencher Metric Format (BMF) results across repeated runs. + + Exports `latency` in nanoseconds (`real_time` when `--wall_time` is set or + the benchmark uses `/real_time`, `cpu_time` otherwise) alongside any extra + metrics selected by `--extra_metrics_filter`. + """ + benchmark_names, selected_metrics = get_benchmark_names_and_metrics( + console, parsed_args, exp_runs, base_runs=[] + ) + extra_metrics = [ + m + for m in selected_metrics + if m not in ("cpu_time", "real_time", "iterations") + ] + + samples: dict[str, dict[str, list[float]]] = { + name: defaultdict(list) for name in benchmark_names + } + for run in exp_runs: + for b in run["benchmarks"]: + name = b["name"] + if name not in samples: + continue + + time_key = ( + "real_time" + if (parsed_args.wall_time or "/real_time" in name) + else "cpu_time" + ) + time_unit = b.get("time_unit", "ns") + if time_unit not in TIME_UNIT_TO_NS: + console.print( + f"ERROR: Unsupported time_unit `{time_unit}` for `{name}`." + ) + sys.exit(1) + samples[name]["latency"].append( + float(b[time_key]) * TIME_UNIT_TO_NS[time_unit] + ) + + for metric in extra_metrics: + if metric in b: + samples[name][metric].append(float(b[metric])) + + bmf: dict[str, dict[str, dict[str, float]]] = {} + for name in benchmark_names: + prefixed_name = f"{parsed_args.benchmark_prefix}{name}" + bmf[prefixed_name] = { + measure: compute_bmf_metric(parsed_args.alpha, vals) + for measure, vals in samples[name].items() + if vals + } + return bmf + + +def write_structured_output(data: Any, output_file: Optional[Path]) -> None: + """Writes JSON-serialized output to `output_file` or `stdout`.""" + serialized = json.dumps(data, indent=2, allow_nan=False) + "\n" + if output_file is not None: + output_file.parent.mkdir(parents=True, exist_ok=True) + output_file.write_text(serialized, encoding="utf-8") + else: + sys.stdout.write(serialized) + + def main() -> None: parsed_args = parse_args() - console = Console(theme=THEME) + use_stderr_console = ( + parsed_args.output != "console" or parsed_args.output_file is not None + ) + console = Console(theme=THEME, stderr=use_stderr_console) Quantity.set_prefs(spacer=" ", map_sf=Quantity.map_sf_to_greek) if parsed_args.base_benchmark and parsed_args.benchmark_comparable_re: @@ -1094,6 +1227,25 @@ def main() -> None: "comparisons." ) sys.exit(1) + if parsed_args.no_extra_metrics and parsed_args.extra_metrics_filter: + console.print( + "ERROR: Cannot combine `--no_extra_metrics` with " + "`--extra_metrics_filter`." + ) + sys.exit(1) + if parsed_args.output == "console" and parsed_args.output_file is not None: + console.print( + "ERROR: `--output_file` requires `--output=json` or `--output=bmf`." + ) + sys.exit(1) + if parsed_args.output == "bmf" and ( + parsed_args.base_benchmark or parsed_args.benchmark_comparable_re + ): + console.print( + "ERROR: `--output=bmf` does not support `--base_benchmark` or " + "`--benchmark_comparable_re`." + ) + sys.exit(1) # Run the benchmark(s) and collect the results into a data structure for # processing. @@ -1117,13 +1269,21 @@ def main() -> None: console, ) - # If JSON output is requested, just dump the data without further - # processing. + # If JSON output is requested, dump the raw run data without analysis. if parsed_args.output == "json": - console.log("Printing JSON results...") - console.print_json(json.dumps(exp_runs)) - if has_baseline: - console.print_json(json.dumps(base_runs)) + console.log("Writing JSON results...") + payload: Any = ( + {"exp_runs": exp_runs, "base_runs": base_runs} + if has_baseline + else exp_runs + ) + write_structured_output(payload, parsed_args.output_file) + return + + if parsed_args.output == "bmf": + console.log("Writing Bencher Metric Format (BMF) results...") + bmf = compute_bmf_results(console, parsed_args, exp_runs) + write_structured_output(bmf, parsed_args.output_file) return print_run_context(console, num_runs, exp_runs, has_baseline) diff --git a/scripts/bench_runner_test.py b/scripts/bench_runner_test.py new file mode 100755 index 000000000000..444a43926784 --- /dev/null +++ b/scripts/bench_runner_test.py @@ -0,0 +1,176 @@ +#!/usr/bin/env -S uv run --script + +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "numpy", +# "rich", +# "scipy", +# "quantiphy", +# ] +# /// + +"""Tests for BMF output and CLI behavior in bench_runner.py.""" + +__copyright__ = """ +Part of the Carbon Language project, under the Apache License v2.0 with LLVM +Exceptions. See /LICENSE for license information. +SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +""" + +import json +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +from rich.console import Console + +sys.path.append(str(Path(__file__).resolve().parent)) +import bench_runner # noqa: E402 + + +class BenchRunnerBmfTest(unittest.TestCase): + def test_compute_bmf_metric_bounds(self) -> None: + # Single sample omits confidence interval bounds. + self.assertEqual( + bench_runner.compute_bmf_metric(0.05, [42.0]), + {"value": 42.0}, + ) + + # Constant deterministic samples emit zero-width bounds. + self.assertEqual( + bench_runner.compute_bmf_metric(0.05, [1024.0, 1024.0, 1024.0]), + {"value": 1024.0, "lower_value": 1024.0, "upper_value": 1024.0}, + ) + + # Five distinct samples have undefined exact 95% binomial bounds; omit + # `lower_value`/`upper_value` rather than emitting `NaN`. + five = bench_runner.compute_bmf_metric( + 0.05, [10.0, 11.0, 12.0, 13.0, 14.0] + ) + self.assertEqual(five, {"value": 12.0}) + + # Seven distinct samples produce finite `lower_value` and `upper_value`. + seven = bench_runner.compute_bmf_metric( + 0.05, [10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0] + ) + self.assertEqual(seven["value"], 13.0) + self.assertLessEqual(seven["lower_value"], 13.0) + self.assertGreaterEqual(seven["upper_value"], 13.0) + + def test_compute_bmf_results_time_selection_and_filtering(self) -> None: + runs = [ + { + "benchmarks": [ + { + "name": "BM_CpuCase", + "family_index": 0, + "per_family_instance_index": 0, + "cpu_time": 2.5 + i * 0.1, + "real_time": 9.0, + "time_unit": "us", + "MemTotal": 4096.0, + "Bytes": 999.0, + }, + { + "name": "BM_WallCase/real_time", + "family_index": 1, + "per_family_instance_index": 0, + "cpu_time": 0.1, + "real_time": 1.2 + i * 0.1, + "time_unit": "ms", + }, + ] + } + for i in range(6) + ] + + console = Console(stderr=True) + args = bench_runner.parse_args( + [ + "--exp_benchmark=/bin/true", + "--output=bmf", + "--benchmark_prefix=suite::", + "--extra_metrics_filter=^MemTotal$", + ] + ) + bmf = bench_runner.compute_bmf_results(console, args, runs) + self.assertEqual( + list(bmf.keys()), + ["suite::BM_CpuCase", "suite::BM_WallCase/real_time"], + ) + + # `BM_CpuCase` converts `cpu_time` (`us` -> `ns`) and keeps only + # `MemTotal`. + cpu_entry = bmf["suite::BM_CpuCase"] + self.assertEqual(set(cpu_entry.keys()), {"latency", "MemTotal"}) + self.assertAlmostEqual(cpu_entry["latency"]["value"], 2750.0) + self.assertEqual(cpu_entry["MemTotal"]["value"], 4096.0) + + # `BM_WallCase/real_time` selects `real_time` (`ms` -> `ns`). + wall_entry = bmf["suite::BM_WallCase/real_time"] + self.assertEqual(set(wall_entry.keys()), {"latency"}) + self.assertAlmostEqual(wall_entry["latency"]["value"], 1_450_000.0) + + # `--no_extra_metrics` omits all non-time counters. + no_extra_args = bench_runner.parse_args( + [ + "--exp_benchmark=/bin/true", + "--output=bmf", + "--no_extra_metrics", + ] + ) + bmf_no_extra = bench_runner.compute_bmf_results( + console, no_extra_args, runs + ) + self.assertEqual(set(bmf_no_extra["BM_CpuCase"].keys()), {"latency"}) + + def test_cli_stdout_is_clean_json(self) -> None: + script_path = Path(__file__).resolve().parent / "bench_runner.py" + with tempfile.TemporaryDirectory() as tmp: + fake_bench = Path(tmp) / "fake_bench.sh" + fake_bench.write_text( + "#!/usr/bin/env bash\n" + "cat <<'EOF'\n" + '{"context": {"num_cpus": 4, "mhz_per_cpu": 3000, ' + '"caches": [], "load_avg": [0.1]}, "benchmarks": [' + '{"name": "BM_Test", "family_index": 0, ' + '"per_family_instance_index": 0, "cpu_time": 12.0, ' + '"real_time": 15.0, "time_unit": "ns", "Layout": 3.0}]}\n' + "EOF\n", + encoding="utf-8", + ) + fake_bench.chmod(0o755) + + proc = subprocess.run( + [ + str(script_path), + f"--exp_benchmark={fake_bench}", + "--runs=2", + "--output=bmf", + "--benchmark_prefix=fake::", + "--no_extra_metrics", + ], + capture_output=True, + text=True, + check=True, + ) + parsed = json.loads(proc.stdout) + self.assertEqual( + parsed, + { + "fake::BM_Test": { + "latency": { + "value": 12.0, + "lower_value": 12.0, + "upper_value": 12.0, + } + } + }, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/toolchain/benchmarking/BUILD b/toolchain/benchmarking/BUILD index f41aeda019d5..825d6d68e67c 100644 --- a/toolchain/benchmarking/BUILD +++ b/toolchain/benchmarking/BUILD @@ -6,6 +6,7 @@ # tolochain. Infrastructure libraries may be depended on by focused benchmarks # in various other parts of the toolchain. +load("@rules_python//python:defs.bzl", "py_binary", "py_library", "py_test") load("@rules_shell//shell:sh_test.bzl", "sh_test") load("//bazel/cc_rules:defs.bzl", "cc_binary", "cc_library", "cc_test") load("//bazel/cc_toolchains:defs.bzl", "cc_env") @@ -130,3 +131,26 @@ sh_test( args = ["--benchmark_dry_run"], env = cc_env(), ) + +py_library( + name = "bencher_suites", + srcs = ["bencher_suites.py"], +) + +py_binary( + name = "run_bencher", + srcs = ["run_bencher.py"], + python_version = "PY3", + deps = [":bencher_suites"], +) + +py_test( + name = "run_bencher_test", + size = "small", + srcs = ["run_bencher_test.py"], + python_version = "PY3", + deps = [ + ":bencher_suites", + ":run_bencher", + ], +) diff --git a/toolchain/benchmarking/bencher_suites.py b/toolchain/benchmarking/bencher_suites.py new file mode 100644 index 000000000000..80c5b45e47d3 --- /dev/null +++ b/toolchain/benchmarking/bencher_suites.py @@ -0,0 +1,201 @@ +"""Suite and threshold configuration for Bencher continuous benchmarking.""" + +__copyright__ = """ +Part of the Carbon Language project, under the Apache License v2.0 with LLVM +Exceptions. See /LICENSE for license information. +SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +""" + +import re +from dataclasses import dataclass +from enum import Enum +from pathlib import Path +from typing import Optional + + +class Tier(Enum): + """Execution tier for benchmark suites.""" + + CONTINUOUS = "continuous" + NIGHTLY = "nightly" + + +@dataclass(frozen=True) +class SuiteSpec: + """Configuration for a single Google Benchmark target.""" + + # Bazel label of the benchmark `cc_binary` (for example, `//pkg:name`). + label: str + # `--benchmark_filter` regex used on `trunk` pushes and pull requests. + continuous_filter: str + # `--benchmark_filter` regex used on full nightly sweeps. + nightly_filter: str + # Number of process invocations on continuous runs (`>= 6` yields finite + # 95% confidence intervals from `quantile_test`). + continuous_runs: int + # Number of process invocations on nightly runs. + nightly_runs: int + # `--benchmark_min_time` passed to each Google Benchmark invocation. + min_time: str = "0.05s" + # Explicit allowlist of non-time Google Benchmark counter names to export. + extra_metrics: tuple[str, ...] = () + + @property + def package_path(self) -> str: + """Returns the Bazel package path without leading slashes.""" + if not self.label.startswith("//") or ":" not in self.label: + raise ValueError(f"Expected canonical Bazel label: {self.label}") + pkg, _ = self.label[2:].split(":", 1) + return pkg + + @property + def target_name(self) -> str: + """Returns the short Bazel target name.""" + if not self.label.startswith("//") or ":" not in self.label: + raise ValueError(f"Expected canonical Bazel label: {self.label}") + _, name = self.label[2:].split(":", 1) + return name + + @property + def benchmark_prefix(self) -> str: + """Returns the `::` prefix prepended in BMF output.""" + return f"{self.target_name}::" + + @property + def bazel_bin_relpath(self) -> Path: + """Returns the relative path under `bazel-bin` for the built binary.""" + if self.package_path: + return Path("bazel-bin") / self.package_path / self.target_name + return Path("bazel-bin") / self.target_name + + def filter_for_tier(self, tier: Tier) -> str: + """Returns the `--benchmark_filter` regex for `tier`.""" + if tier == Tier.NIGHTLY: + return self.nightly_filter + return self.continuous_filter + + def runs_for_tier(self, tier: Tier) -> int: + """Returns the number of process runs for `tier`.""" + if tier == Tier.NIGHTLY: + return self.nightly_runs + return self.continuous_runs + + def extra_metrics_regex(self) -> Optional[str]: + """Returns an anchored regex matching `extra_metrics`, or `None`.""" + if not self.extra_metrics: + return None + alternation = "|".join(re.escape(m) for m in self.extra_metrics) + return f"^({alternation})$" + + def allowed_measures(self) -> frozenset[str]: + """Returns the complete set of Bencher measure names for this suite.""" + return frozenset(("latency", *self.extra_metrics)) + + +@dataclass(frozen=True) +class ThresholdSpec: + """Statistical threshold configuration for a Bencher measure.""" + + measure: str + test: str + min_sample_size: int + max_sample_size: int + upper_boundary: float + + def to_bencher_args(self) -> list[str]: + """Returns CLI flags for `bencher run`.""" + return [ + "--threshold-measure", + self.measure, + "--threshold-test", + self.test, + "--threshold-min-sample-size", + str(self.min_sample_size), + "--threshold-max-sample-size", + str(self.max_sample_size), + "--threshold-upper-boundary", + str(self.upper_boundary), + ] + + +# Deterministic memory counters reported by `prelude_benchmark`. +PRELUDE_MEM_METRICS: tuple[str, ...] = ( + "MemTotal", + "MemSemIR", + "MemSemIRInsts", + "MemSemIRInstLocs", + "MemSemIRConstantValues", + "MemSemIRInstBlocks", + "MemSemIRAllocator", +) + + +# Configured benchmark suites tracked in Bencher. +SUITES: tuple[SuiteSpec, ...] = ( + SuiteSpec( + label="//toolchain/benchmarking:prelude_benchmark", + continuous_filter=r"^BM_PreludeCompile/", + nightly_filter=r"^BM_PreludeCompile/", + continuous_runs=7, + nightly_runs=7, + min_time="0.05s", + extra_metrics=PRELUDE_MEM_METRICS, + ), + SuiteSpec( + label="//toolchain/benchmarking:compile_benchmark", + # Include both `Lang::Carbon` and `Lang::Cpp` in-process benchmarks at + # representative sizes on continuous runs, while skipping subprocess + # `BM_CompileExec*` variants. + continuous_filter=r"^BM_Compile(ApiFile|ImplFile).*/(256|1024|16384)$", + # Run all input sizes (`256..262144`) on nightly builds. + nightly_filter=r"^BM_Compile(ApiFile|ImplFile)", + continuous_runs=6, + nightly_runs=6, + min_time="0.05s", + extra_metrics=(), + ), +) + + +# TODO: Adding new features to the `Core` prelude or SemIR representations can +# inherently increase `Mem*` usage without being an unintended regression. All +# PR alerts are non-blocking, so keep an eye on whether 1% `Mem*` alerts are too +# noisy in routine prelude development and adjust these boundaries if needed. +_MEM_THRESHOLDS: tuple[ThresholdSpec, ...] = tuple( + ThresholdSpec( + measure=metric, + test="percentage", + min_sample_size=2, + max_sample_size=16, + upper_boundary=0.01, + ) + for metric in PRELUDE_MEM_METRICS +) + + +# Pull request thresholds flag clear (>15%) timing regressions and (>1%) +# deterministic memory increases early while avoiding shared-runner noise. +PR_THRESHOLDS: tuple[ThresholdSpec, ...] = ( + ThresholdSpec( + measure="latency", + test="percentage", + min_sample_size=5, + max_sample_size=32, + upper_boundary=0.15, + ), + *_MEM_THRESHOLDS, +) + + +# `trunk` and `nightly` thresholds use a rolling t-test window to track smaller +# compiler latency shifts over time alongside deterministic memory bounds. +TRUNK_THRESHOLDS: tuple[ThresholdSpec, ...] = ( + ThresholdSpec( + measure="latency", + test="t_test", + min_sample_size=10, + max_sample_size=64, + upper_boundary=0.995, + ), + *_MEM_THRESHOLDS, +) diff --git a/toolchain/benchmarking/run_bencher.py b/toolchain/benchmarking/run_bencher.py new file mode 100755 index 000000000000..576f3d240631 --- /dev/null +++ b/toolchain/benchmarking/run_bencher.py @@ -0,0 +1,461 @@ +#!/usr/bin/env -S uv run --script + +# /// script +# requires-python = ">=3.12" +# /// + +"""Builds, runs, and validates Bencher Metric Format (BMF) benchmark suites.""" + +__copyright__ = """ +Part of the Carbon Language project, under the Apache License v2.0 with LLVM +Exceptions. See /LICENSE for license information. +SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +""" + +import argparse +import json +import math +import pathlib +import subprocess +import sys +import tempfile +from pathlib import Path +from typing import Any, Iterable, Optional + +# Add repo root to sys.path to allow importing from toolchain.benchmarking. +_REPO_ROOT = pathlib.Path(__file__).resolve().parents[2] +sys.path.append(str(_REPO_ROOT)) +from toolchain.benchmarking.bencher_suites import ( # noqa: E402 + PR_THRESHOLDS, + SUITES, + TRUNK_THRESHOLDS, + SuiteSpec, + ThresholdSpec, + Tier, +) + +# Safety bound per report to stay well below Bencher Cloud's 65,535/day limit. +MAX_METRICS_PER_REPORT = 5000 +# Maximum benchmark name length accepted by `bencher_valid::BenchmarkName`. +MAX_BENCHMARK_NAME_LEN = 1024 + + +class BmfValidationError(ValueError): + """Raised when a BMF JSON payload fails structural or allowlist checks.""" + + +def normalize_target_pattern(pattern: str) -> str: + """Strips optional leading `@` repository prefix from a Bazel pattern.""" + trimmed = pattern.strip() + if trimmed.startswith("@//"): + return trimmed[1:] + return trimmed + + +def target_matches_patterns(label: str, patterns: Iterable[str]) -> bool: + """Returns true if canonical `label` matches any Bazel target pattern.""" + suite_spec = SuiteSpec( + label=label, + continuous_filter="", + nightly_filter="", + continuous_runs=1, + nightly_runs=1, + ) + pkg = suite_spec.package_path + + for raw_pat in patterns: + pat = normalize_target_pattern(raw_pat) + if not pat or pat.startswith("#"): + continue + if pat == label or pat in ("//...", "..."): + return True + if pat in (f"//{pkg}:all", f"//{pkg}:*"): + return True + if pat.startswith("//") and pat.endswith("/..."): + prefix_pkg = pat[2:-4] + if pkg == prefix_pkg or pkg.startswith(f"{prefix_pkg}/"): + return True + return False + + +def select_suites( + suites: Iterable[SuiteSpec], + suite_filters: Optional[list[str]] = None, + targets_file: Optional[Path] = None, +) -> list[SuiteSpec]: + """Filters `suites` by explicit `--suite` names and `--targets-file`.""" + selected = list(suites) + if suite_filters: + wanted = {normalize_target_pattern(s) for s in suite_filters} + selected = [ + s for s in selected if s.label in wanted or s.target_name in wanted + ] + + if targets_file is not None: + patterns = targets_file.read_text(encoding="utf-8").splitlines() + selected = [ + s for s in selected if target_matches_patterns(s.label, patterns) + ] + + return selected + + +def build_bench_runner_cmd( + repo_root: Path, + suite: SuiteSpec, + tier: Tier, + output_file: Path, + runs_override: Optional[int] = None, +) -> list[str]: + """Constructs the `scripts/bench_runner.py` command for `suite`.""" + runs = ( + runs_override + if runs_override is not None + else suite.runs_for_tier(tier) + ) + cmd = [ + str(repo_root / "scripts" / "bench_runner.py"), + f"--exp_benchmark={repo_root / suite.bazel_bin_relpath}", + f"--runs={runs}", + "--output=bmf", + f"--output_file={output_file}", + f"--benchmark_prefix={suite.benchmark_prefix}", + f"--benchmark_args=--benchmark_min_time={suite.min_time}", + f"--benchmark_args=--benchmark_filter={suite.filter_for_tier(tier)}", + ] + metrics_re = suite.extra_metrics_regex() + if metrics_re is not None: + cmd.append(f"--extra_metrics_filter={metrics_re}") + else: + cmd.append("--no_extra_metrics") + return cmd + + +def _is_finite_number(val: Any) -> bool: + """Returns true if `val` is a finite `int` or `float` (excluding `bool`).""" + return ( + isinstance(val, (int, float)) + and not isinstance(val, bool) + and math.isfinite(val) + ) + + +def validate_bmf( + data: Any, + suites: Iterable[SuiteSpec] = SUITES, + max_metrics: int = MAX_METRICS_PER_REPORT, +) -> int: + """Validates a BMF v0 dictionary against configured suites and bounds. + + Returns the total number of `(benchmark, measure)` metrics in `data`, or + raises `BmfValidationError` if validation fails. + """ + if not isinstance(data, dict) or not data: + raise BmfValidationError("BMF payload must be a non-empty JSON object.") + + allowed_by_prefix = { + s.benchmark_prefix: s.allowed_measures() for s in suites + } + metric_count = 0 + + for bench_name, measures in data.items(): + if ( + not isinstance(bench_name, str) + or not bench_name + or bench_name != bench_name.strip() + or len(bench_name) > MAX_BENCHMARK_NAME_LEN + ): + raise BmfValidationError(f"Invalid benchmark name: {bench_name!r}") + + matching_measures: Optional[frozenset[str]] = None + for prefix, allowed in allowed_by_prefix.items(): + if bench_name.startswith(prefix) and len(bench_name) > len(prefix): + matching_measures = allowed + break + if matching_measures is None: + raise BmfValidationError( + f"Benchmark {bench_name!r} does not match any configured " + "suite prefix." + ) + + if not isinstance(measures, dict) or not measures: + raise BmfValidationError( + f"Measures for {bench_name!r} must be a non-empty object." + ) + + for measure_name, metric_obj in measures.items(): + if measure_name not in matching_measures: + raise BmfValidationError( + f"Measure {measure_name!r} is not allowlisted for " + f"{bench_name!r}." + ) + if not isinstance(metric_obj, dict) or "value" not in metric_obj: + raise BmfValidationError( + f"Metric {bench_name!r}/{measure_name!r} missing `value`." + ) + extra_keys = set(metric_obj.keys()) - { + "value", + "lower_value", + "upper_value", + } + if extra_keys: + raise BmfValidationError( + f"Unexpected keys {sorted(extra_keys)} in " + f"{bench_name!r}/{measure_name!r}." + ) + for k, v in metric_obj.items(): + if not _is_finite_number(v): + raise BmfValidationError( + f"Non-finite value for {bench_name!r}/{measure_name!r}" + f".{k}: {v!r}" + ) + + val = float(metric_obj["value"]) + if "lower_value" in metric_obj: + low = float(metric_obj["lower_value"]) + if low > val: + raise BmfValidationError( + f"`lower_value` ({low}) > `value` ({val}) in " + f"{bench_name!r}/{measure_name!r}." + ) + if "upper_value" in metric_obj: + high = float(metric_obj["upper_value"]) + if high < val: + raise BmfValidationError( + f"`upper_value` ({high}) < `value` ({val}) in " + f"{bench_name!r}/{measure_name!r}." + ) + + metric_count += 1 + if metric_count > max_metrics: + raise BmfValidationError( + f"BMF metric count exceeds limit of {max_metrics}." + ) + + return metric_count + + +def merge_bmf_payloads( + payloads: Iterable[dict[str, Any]], + suites: Iterable[SuiteSpec] = SUITES, + max_metrics: int = MAX_METRICS_PER_REPORT, +) -> tuple[dict[str, Any], int]: + """Merges per-suite BMF dictionaries and validates the combined payload.""" + merged: dict[str, Any] = {} + for payload in payloads: + for bench_name, measures in payload.items(): + if bench_name in merged: + raise BmfValidationError( + f"Duplicate benchmark key across suites: {bench_name!r}" + ) + merged[bench_name] = measures + count = validate_bmf(merged, suites=suites, max_metrics=max_metrics) + return merged, count + + +def format_threshold_args(thresholds: Iterable[ThresholdSpec]) -> list[str]: + """Flattens `thresholds` into `bencher run` CLI arguments.""" + args: list[str] = [] + for spec in thresholds: + args.extend(spec.to_bencher_args()) + return args + + +def _write_github_output( + github_output: Optional[Path], has_benchmarks: bool, metric_count: int +) -> None: + """Appends `has_benchmarks` and `metric_count` to `$GITHUB_OUTPUT`.""" + if github_output is None: + return + with github_output.open("a", encoding="utf-8") as f: + f.write(f"has_benchmarks={'true' if has_benchmarks else 'false'}\n") + f.write(f"metric_count={metric_count}\n") + + +def _run_suites(parsed_args: argparse.Namespace) -> int: + """Builds and runs matched benchmark suites and writes merged BMF JSON.""" + tier = Tier(parsed_args.tier) + matched = select_suites( + SUITES, + suite_filters=parsed_args.suite, + targets_file=parsed_args.targets_file, + ) + if not matched: + print("No configured benchmark suites matched.", file=sys.stderr) + _write_github_output( + parsed_args.github_output, has_benchmarks=False, metric_count=0 + ) + return 0 + + labels = [s.label for s in matched] + build_cmd = [str(_REPO_ROOT / "scripts" / "run_bazel.py")] + if parsed_args.ci: + build_cmd.extend(["--attempts=5", "--jobs-on-last-attempt=4"]) + build_cmd.extend( + ["build", "-c", "opt", "--remote_download_toplevel", *labels] + ) + print(f"Building benchmark targets: {' '.join(labels)}", file=sys.stderr) + subprocess.run(build_cmd, cwd=_REPO_ROOT, check=True) + + payloads: list[dict[str, Any]] = [] + with tempfile.TemporaryDirectory() as tmp_dir: + tmp_path = Path(tmp_dir) + for suite in matched: + suite_out = tmp_path / f"{suite.target_name}.bmf.json" + cmd = build_bench_runner_cmd( + repo_root=_REPO_ROOT, + suite=suite, + tier=tier, + output_file=suite_out, + runs_override=parsed_args.runs_override, + ) + subprocess.run(cmd, cwd=_REPO_ROOT, check=True) + payloads.append(json.loads(suite_out.read_text(encoding="utf-8"))) + + merged, metric_count = merge_bmf_payloads( + payloads, suites=matched, max_metrics=parsed_args.max_metrics + ) + output_path: Path = parsed_args.output + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text( + json.dumps(merged, indent=2, allow_nan=False) + "\n", + encoding="utf-8", + ) + print( + f"Wrote {len(merged)} benchmarks ({metric_count} metrics) to " + f"{output_path}.", + file=sys.stderr, + ) + _write_github_output( + parsed_args.github_output, + has_benchmarks=True, + metric_count=metric_count, + ) + return 0 + + +def _validate_file(parsed_args: argparse.Namespace) -> int: + """Validates an existing BMF JSON file.""" + raw = parsed_args.file.read_text(encoding="utf-8") + try: + # Reject non-standard JSON constants (`NaN`, `Infinity`). + data = json.loads( + raw, + parse_constant=lambda c: (_ for _ in ()).throw( + BmfValidationError(f"Invalid JSON constant: {c}") + ), + ) + metric_count = validate_bmf(data, max_metrics=parsed_args.max_metrics) + except (json.JSONDecodeError, BmfValidationError) as exc: + print(f"BMF validation failed: {exc}", file=sys.stderr) + return 1 + + print( + f"Validated {len(data)} benchmarks ({metric_count} metrics) in " + f"{parsed_args.file}.", + file=sys.stderr, + ) + return 0 + + +def _print_threshold_args(parsed_args: argparse.Namespace) -> int: + """Prints one `bencher run` threshold CLI token per line.""" + specs = PR_THRESHOLDS if parsed_args.mode == "pr" else TRUNK_THRESHOLDS + for arg in format_threshold_args(specs): + print(arg) + return 0 + + +def parse_args(args: Optional[list[str]] = None) -> argparse.Namespace: + """Parses command-line arguments.""" + parser = argparse.ArgumentParser(description=__doc__) + subparsers = parser.add_subparsers(dest="subcommand", required=True) + + run_p = subparsers.add_parser( + "run", help="Build and execute configured benchmark suites." + ) + run_p.add_argument( + "--tier", + choices=[t.value for t in Tier], + default=Tier.CONTINUOUS.value, + help="Benchmark suite tier to execute.", + ) + run_p.add_argument( + "--output", + required=True, + type=Path, + help="Output path for merged BMF JSON.", + ) + run_p.add_argument( + "--targets-file", + type=Path, + help="Optional file of impacted Bazel targets/patterns to intersect.", + ) + run_p.add_argument( + "--suite", + action="append", + help="Optional target name or Bazel label filter (repeatable).", + ) + run_p.add_argument( + "--runs-override", + type=int, + help="Optional override for `--runs` across matched suites.", + ) + run_p.add_argument( + "--max-metrics", + type=int, + default=MAX_METRICS_PER_REPORT, + help="Maximum allowed metrics in the merged BMF report.", + ) + run_p.add_argument( + "--ci", + action="store_true", + help="Enable CI retry flags when building with `run_bazel.py`.", + ) + run_p.add_argument( + "--github-output", + type=Path, + help="Optional `$GITHUB_OUTPUT` file for `has_benchmarks` metadata.", + ) + + val_p = subparsers.add_parser( + "validate", help="Validate an existing BMF JSON file." + ) + val_p.add_argument( + "file", type=Path, help="Path to the BMF JSON file to validate." + ) + val_p.add_argument( + "--max-metrics", + type=int, + default=MAX_METRICS_PER_REPORT, + help="Maximum allowed metrics in the BMF file.", + ) + + thresh_p = subparsers.add_parser( + "threshold-args", + help="Print `bencher run` threshold CLI arguments (one per line).", + ) + thresh_p.add_argument( + "--mode", + choices=["pr", "trunk"], + required=True, + help="Threshold profile to emit.", + ) + + return parser.parse_args(args=args) + + +def main(args: Optional[list[str]] = None) -> int: + """Entry point for `run_bencher.py`.""" + parsed_args = parse_args(args=args) + if parsed_args.subcommand == "run": + return _run_suites(parsed_args) + if parsed_args.subcommand == "validate": + return _validate_file(parsed_args) + if parsed_args.subcommand == "threshold-args": + return _print_threshold_args(parsed_args) + raise AssertionError(f"Unhandled subcommand: {parsed_args.subcommand}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/toolchain/benchmarking/run_bencher_test.py b/toolchain/benchmarking/run_bencher_test.py new file mode 100644 index 000000000000..4088c379df47 --- /dev/null +++ b/toolchain/benchmarking/run_bencher_test.py @@ -0,0 +1,274 @@ +#!/usr/bin/env python3 + +"""Tests for bencher_suites.py and run_bencher.py.""" + +__copyright__ = """ +Part of the Carbon Language project, under the Apache License v2.0 with LLVM +Exceptions. See /LICENSE for license information. +SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +""" + +import json +import re +import tempfile +import unittest +from pathlib import Path + +from toolchain.benchmarking import bencher_suites, run_bencher +from toolchain.benchmarking.bencher_suites import ( + PRELUDE_MEM_METRICS, + SUITES, + Tier, +) +from toolchain.benchmarking.run_bencher import BmfValidationError + + +class BencherSuitesTest(unittest.TestCase): + def test_suite_properties_and_prefixes(self) -> None: + by_name = {s.target_name: s for s in SUITES} + self.assertEqual( + set(by_name.keys()), {"prelude_benchmark", "compile_benchmark"} + ) + + prelude = by_name["prelude_benchmark"] + self.assertEqual(prelude.benchmark_prefix, "prelude_benchmark::") + self.assertEqual( + prelude.bazel_bin_relpath, + Path("bazel-bin/toolchain/benchmarking/prelude_benchmark"), + ) + self.assertEqual(prelude.extra_metrics, PRELUDE_MEM_METRICS) + prelude_re = prelude.extra_metrics_regex() + assert prelude_re is not None + for m in PRELUDE_MEM_METRICS: + self.assertRegex(m, prelude_re) + self.assertNotRegex("Bytes", prelude_re) + self.assertNotRegex("MemOther", prelude_re) + + compile_suite = by_name["compile_benchmark"] + self.assertEqual(compile_suite.benchmark_prefix, "compile_benchmark::") + self.assertIsNone(compile_suite.extra_metrics_regex()) + self.assertEqual( + compile_suite.allowed_measures(), frozenset({"latency"}) + ) + + def test_compile_benchmark_filters_include_cpp_and_exclude_exec( + self, + ) -> None: + compile_suite = next( + s for s in SUITES if s.target_name == "compile_benchmark" + ) + cont_re = re.compile(compile_suite.filter_for_tier(Tier.CONTINUOUS)) + nightly_re = re.compile(compile_suite.filter_for_tier(Tier.NIGHTLY)) + + # Included in both continuous and nightly: Carbon and C++ at small/mid. + for case in ( + "BM_CompileApiFileDenseDecls/256", + "BM_CompileApiFileDenseDecls/256", + "BM_CompileImplFile/1024", + "BM_CompileImplFile/16384", + "BM_CompileApiFileRealisticHeader/1024", + ): + self.assertIsNotNone(cont_re.search(case), case) + self.assertIsNotNone(nightly_re.search(case), case) + + # Large sizes run only on nightly. + for large_case in ( + "BM_CompileImplFile/65536", + "BM_CompileImplFile/262144", + ): + self.assertIsNone(cont_re.search(large_case), large_case) + self.assertIsNotNone(nightly_re.search(large_case), large_case) + + # Subprocess `BM_CompileExec*` cases are skipped in all tiers. + for exec_case in ( + "BM_CompileExecApiFileDenseDecls" + "/256/real_time", + "BM_CompileExecApiFileDenseDecls" + "/1024/real_time", + ): + self.assertIsNone(cont_re.search(exec_case), exec_case) + self.assertIsNone(nightly_re.search(exec_case), exec_case) + + def test_runs_yield_finite_quantile_intervals(self) -> None: + for suite in SUITES: + self.assertGreaterEqual(suite.continuous_runs, 6) + self.assertGreaterEqual(suite.nightly_runs, 6) + + +class RunBencherTest(unittest.TestCase): + def test_target_matching_and_suite_selection(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + targets_path = Path(tmp) / "targets" + + # Unrelated target matches nothing. + targets_path.write_text("//common:map_test\n//scripts:no_op_test\n") + self.assertEqual( + run_bencher.select_suites(SUITES, targets_file=targets_path), + [], + ) + + # Exact target (with or without `@`) matches just that suite. + targets_path.write_text( + "@//toolchain/benchmarking:prelude_benchmark\n" + ) + matched = run_bencher.select_suites( + SUITES, targets_file=targets_path + ) + self.assertEqual( + [s.target_name for s in matched], ["prelude_benchmark"] + ) + + # Wildcard `//...` matches all configured suites. + targets_path.write_text("//...\n") + matched_all = run_bencher.select_suites( + SUITES, targets_file=targets_path + ) + self.assertEqual(len(matched_all), len(SUITES)) + + # Explicit `--suite` filter narrows further. + matched_one = run_bencher.select_suites( + SUITES, + suite_filters=["compile_benchmark"], + targets_file=targets_path, + ) + self.assertEqual( + [s.target_name for s in matched_one], ["compile_benchmark"] + ) + + def test_build_bench_runner_cmd_allowlist_flags(self) -> None: + by_name = {s.target_name: s for s in SUITES} + repo = Path("/repo") + out = Path("/tmp/out.json") + + prelude_cmd = run_bencher.build_bench_runner_cmd( + repo, by_name["prelude_benchmark"], Tier.CONTINUOUS, out + ) + self.assertIn("--benchmark_prefix=prelude_benchmark::", prelude_cmd) + self.assertTrue( + any(a.startswith("--extra_metrics_filter=^(") for a in prelude_cmd) + ) + self.assertNotIn("--no_extra_metrics", prelude_cmd) + + compile_cmd = run_bencher.build_bench_runner_cmd( + repo, + by_name["compile_benchmark"], + Tier.NIGHTLY, + out, + runs_override=2, + ) + self.assertIn("--benchmark_prefix=compile_benchmark::", compile_cmd) + self.assertIn("--runs=2", compile_cmd) + self.assertIn("--no_extra_metrics", compile_cmd) + self.assertFalse( + any(a.startswith("--extra_metrics_filter=") for a in compile_cmd) + ) + + def test_validate_and_merge_bmf(self) -> None: + prelude_bmf = { + "prelude_benchmark::BM_PreludeCompile/Nothing": { + "latency": { + "value": 50000000.0, + "lower_value": 49000000.0, + "upper_value": 51000000.0, + }, + "MemSemIR": { + "value": 8604581.0, + "lower_value": 8604581.0, + "upper_value": 8604581.0, + }, + } + } + compile_key = ( + "compile_benchmark::" + "BM_CompileImplFile/1024" + ) + compile_bmf = {compile_key: {"latency": {"value": 76655825.0}}} + + merged, count = run_bencher.merge_bmf_payloads( + [prelude_bmf, compile_bmf] + ) + self.assertEqual(len(merged), 2) + self.assertEqual(count, 3) + + # Reject duplicate benchmark keys. + with self.assertRaises(BmfValidationError): + run_bencher.merge_bmf_payloads([compile_bmf, compile_bmf]) + + # Reject unknown suite prefix. + with self.assertRaises(BmfValidationError): + run_bencher.validate_bmf( + {"unknown_suite::BM_Foo": {"latency": {"value": 1.0}}} + ) + + # Reject unallowlisted measure on compile_benchmark. + with self.assertRaises(BmfValidationError): + run_bencher.validate_bmf( + { + "compile_benchmark::BM_Foo": { + "Bytes": {"value": 100.0}, + } + } + ) + + # Reject bool, NaN, inverted bounds, and metric count overflow. + with self.assertRaises(BmfValidationError): + run_bencher.validate_bmf( + {"compile_benchmark::BM_Foo": {"latency": {"value": True}}} + ) + with self.assertRaises(BmfValidationError): + run_bencher.validate_bmf( + { + "compile_benchmark::BM_Foo": { + "latency": {"value": float("nan")} + } + } + ) + with self.assertRaises(BmfValidationError): + run_bencher.validate_bmf( + { + "compile_benchmark::BM_Foo": { + "latency": { + "value": 10.0, + "lower_value": 12.0, + "upper_value": 15.0, + } + } + } + ) + with self.assertRaises(BmfValidationError): + run_bencher.validate_bmf(prelude_bmf, max_metrics=1) + + def test_validate_cli_rejects_nan_json(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + bad = Path(tmp) / "bad.json" + bad.write_text( + '{"compile_benchmark::BM_Foo": {"latency": {"value": NaN}}}' + ) + self.assertEqual(run_bencher.main(["validate", str(bad)]), 1) + + good = Path(tmp) / "good.json" + good.write_text( + json.dumps( + {"compile_benchmark::BM_Foo": {"latency": {"value": 42.0}}} + ) + ) + self.assertEqual(run_bencher.main(["validate", str(good)]), 0) + + def test_threshold_args_profiles(self) -> None: + pr_args = run_bencher.format_threshold_args( + bencher_suites.PR_THRESHOLDS + ) + trunk_args = run_bencher.format_threshold_args( + bencher_suites.TRUNK_THRESHOLDS + ) + self.assertIn("percentage", pr_args) + self.assertIn("0.15", pr_args) + self.assertIn("t_test", trunk_args) + self.assertIn("0.995", trunk_args) + for mem_metric in PRELUDE_MEM_METRICS: + self.assertIn(mem_metric, pr_args) + self.assertIn(mem_metric, trunk_args) + + +if __name__ == "__main__": + unittest.main()