diff --git a/.github/elide/README.md b/.github/elide/README.md index c7f77a185b..dcbdb189fe 100644 --- a/.github/elide/README.md +++ b/.github/elide/README.md @@ -49,6 +49,20 @@ meso benchmarks and benchmarks of real packages on a native standalone and repor and on pull requests that carry the label `perf:bench`. `codspeed-bench` is the driver that runs the benchmarks and writes the results. +The suites of `codspeed-bench` that the workflow runs: + +| Suite | What it measures | Files | +|---|---|---| +| `micro-native` | C API micro benchmarks, warmed up | upstream's `micro`, table in `mx_graalpython_bench_param.py` | +| `meso` | pure Python benchmarks, warmed up | upstream's `meso`, table in `mx_graalpython_bench_param.py` | +| `packages` | real packages, warmed up (see "Package benchmarks") | the fork's `packages` | +| `interp` | some `meso` benchmarks without the JIT compiler (see "Interpreter, start-up and memory") | the fork's `interp` table, upstream's `meso` files | +| `startup` | fresh processes: start-up, imports, a first run | the fork's `startup` | +| `memory` | peak RSS (and wall time) of fresh processes holding data | the fork's `memory` | + +CodSpeed compares the fastest iteration of each row with the base branch. The workflow also writes +the peak RSS of every benchmark to the run's summary page (`walltime-summary.md`). + The standalone and the packages' wheels are built on the pool. The measurement runs on the benchmark runner with the label `linux-amd64-bench`, which is shared between repositories, so only the measurement runs there. @@ -65,6 +79,8 @@ merges from upstream cannot conflict with it: | `pydantic-json` | `validate_json` and `dump_json` of a list of nested models with a discriminated union, and `model_dump_json`/`model_validate_json` per model | | `pydantic-models` | `model_validate` from dicts and `model_dump`, `model_validate_json` and `model_dump_json`, of nested models with a field validator | | `orjson-roundtrip` | `dumps` and `loads` of a nested document, also indented with sorted keys, and `dumps` of dataclasses | +| `orjson-loads` | the `loads` of `orjson-roundtrip`, on the same document | +| `orjson-dumps` | the `dumps` of `orjson-roundtrip`, on the same document: compact, indented with sorted keys, and dataclasses | | `pandas-csv` | `read_csv` of an in-memory CSV (dates, a categorical column), a filter, `to_csv`, a groupby | | `pandas-str` | `Series.str` methods (strip, lower, contains, extract, split, replace, title) and `to_datetime` | | `pandas-groupby-merge` | merges of a fact table with two dimension tables, groupby aggregations, `pivot_table`, a grouped rank | @@ -138,6 +154,74 @@ a network (`package-venv`) and runs every package benchmark for four iterations; virtual environment in the job's temporary directory and runs the suite with that environment's interpreter (`--suite-python`). +### Interpreter, start-up and memory + +Three more suites of `codspeed-bench`, each with a `benchmarks.txt` in its own folder next to +`packages`; like the package benchmarks, their files carry no copyright header. Their sizes are estimates for the benchmark host; a resize is a change of one line in +`benchmarks.txt` and starts a new history on CodSpeed, because the size is part of the name. + +`interp` runs some of upstream's `meso` benchmarks (richards3, bm-float, nbody3, raytrace-simple, +fannkuchredux3, fasta3) with Truffle compilation switched off, `--experimental-options +--engine.Compilation=false`: the speed of code that is not compiled, which is what most code runs at +before the compiler gets to it. Its table names the files in `meso` and gives sizes much smaller than +those of `meso`, for iterations of about 0.2 to 1 s. The options belong to the suite: the driver +gives them to every benchmark of it, also when reporting to CodSpeed, where `--python-arg` is +refused. The rows are `interp/[]`, next to `meso/[]`. + +`startup` is in the harness format, but one iteration starts fresh processes of the interpreter +(`sys.executable`, with the interpreter options of the harness process, from `sys.orig_argv`), one +after the other, and waits for each; the workload argument is the number of processes, so that an +iteration takes at least about 0.3 s: + +| Benchmark | What each process does | +|---|---| +| `pass` | `-c pass` | +| `stdlib-imports` | imports json, re, decimal, datetime, collections, pathlib, argparse, logging, subprocess, typing, dataclasses and asyncio (`memory/stdlib-imports.py`) | +| `first-run` | a small pure Python workload, once (`startup/first-run.py` as a script), and checks its result | + +`memory` is not in the harness format. Its benchmarks are scripts: every iteration runs one in a +fresh process, ` .py `, and the driver takes the wall time of the whole +process and its peak RSS (`ru_maxrss` from `wait4`). The scripts mirror upstream's `heap` benchmarks, +which sleep 3 s per process for upstream's memory sampling, without the sleep: + +| Benchmark | What the process holds when it exits | +|---|---| +| `idle` | nothing; the interpreter after start-up (`heap/post-startup.py`) | +| `stdlib-imports` | the modules of `startup/stdlib-imports` | +| `objects` | a list of 1,000,000 instances of a class with two attributes (`heap/allocate-objects.py`) | +| `dicts` | a list of 1,000,000 dicts with two string keys | +| `strings` | a list of 1,000,000 distinct strings of up to 7 characters | + +The peak RSS includes everything the process allocated on the way, garbage included, and depends on +GraalPy's heap sizing; that is what a user of the interpreter pays for. + +#### Peak RSS on CodSpeed + +CodSpeed takes only times, so every benchmark of `memory` gives two rows there: + +- `memory/[]`, the wall time of one process, from the start of the interpreter to its + exit, and +- `memory/[][peak-rss: 1 ms = 1 MiB]`, whose "time" is the peak RSS of one process: + 1 ms on CodSpeed is 1 MiB, so 300 ms is 300 MiB. The value is the median over the processes of the + second half of the iterations (the ones whose durations are the samples of the first row), the + same in every round, so its spread is zero and "faster" means "smaller". + +Both are in the same result file. `walltime-summary.json` keeps the peak RSS rows apart from the +times, under `memory`, each with `"kind": "memory"`, the unit (KiB), the row it belongs to (`of`) and +the peak RSS of every process; `measured` keeps the times as before, with `rss_kb_per_process` and +`peak_rss_kb` added for the benchmarks of `memory`. + +`walltime-summary.md`, written next to it and appended to the run's summary page, lists the peak RSS +of every benchmark of every suite. For a harness benchmark it is that of the whole harness process +over all iterations, including the compiler's memory; for `startup` on Linux it is the larger of the +harness process and the processes it started (`wait4` counts the children a process waited for); +for `memory` it is the value of the peak RSS row. + +To compare with CPython on the same machine, `--no-suite-options` leaves out the options of +`interp` (the rows then measure CPython's interpreter on the same sizes), for example +`python3 .github/elide/codspeed-bench --python python3 --no-suite-options --label cpython --suite interp startup memory --output `. +It is refused when reporting to CodSpeed. + ### Diagnosing noisy rows A manual run of `elide-codspeed.yml` with the input `diagnose` set measures without reporting to diff --git a/.github/elide/codspeed-bench b/.github/elide/codspeed-bench index 1b2d53280d..8e8a49b55e 100755 --- a/.github/elide/codspeed-bench +++ b/.github/elide/codspeed-bench @@ -10,8 +10,11 @@ # # --python-arg passes options to the interpreter, for diagnostic runs (codspeed-diagnose); such runs # are never reported to CodSpeed. +# +# The suite "memory" does not use the harness: every iteration is a fresh process of a script, and +# its duration and peak RSS are taken from that process. Each of its benchmarks gets a second +# CodSpeed result whose "time" is the peak RSS, 1 ms per MiB (MEMORY_SUFFIX). -#!/usr/bin/env python3 import argparse import importlib.util import json @@ -37,15 +40,27 @@ SUITES = { "meso": ("MESO_BENCHMARKS", "meso"), "micro": ("MICRO_BENCHMARKS", "micro"), } -# The fork's suites: suite name -> directory under BENCH_REL. Upstream's table file is not edited, so -# the directory has its own table, benchmarks.txt. +# The fork's suites: suite name -> directory under BENCH_REL and how its benchmarks run. Upstream's +# table file is not edited, so the directory has its own table, benchmarks.txt. OWN_SUITES = { # Benchmarks of real packages. They need an interpreter that has the packages of # requirements.txt in that directory installed, see --suite-python. - "packages": "packages", + "packages": {"directory": "packages"}, + # Some of the meso benchmarks on smaller sizes with Truffle compilation switched off: the speed + # of the interpreter alone. Its table names the files in meso. The options are part of what the + # suite measures, so unlike --python-arg they are also given when reporting to CodSpeed. + "interp": {"directory": "interp", "python_args": ["--experimental-options", "--engine.Compilation=false"]}, + # Every iteration starts fresh processes of the interpreter and waits for them. + "startup": {"directory": "startup"}, + # Scripts run without the harness, one fresh process per iteration. + "memory": {"directory": "memory", "process": True}, } DEFAULT_SUITES = ["micro-native", "meso"] +# Appended to the name of the second result of a benchmark of the suite "memory", which carries the +# peak RSS of its processes as a time. +MEMORY_SUFFIX = "[peak-rss: 1 ms = 1 MiB]" + # The second half of the iterations are the samples, so this gives at least four. MIN_ITERATIONS = 8 @@ -108,23 +123,28 @@ def split_args(harness_args): return iterations, options, workload -def benchmarks(suites, pattern): +def benchmarks(suites, pattern, suite_options=True): for suite in suites: + config = OWN_SUITES.get(suite, {}) if suite in OWN_SUITES: - directory, table = OWN_SUITES[suite], load_own_table(OWN_SUITES[suite]) + directory, table = config["directory"], load_own_table(config["directory"]) else: directory, table = SUITES[suite][1], load_table(SUITES[suite][0]) for name, harness_args in table.items(): + # A name with a directory is a file in that directory under BENCH_REL, e.g. meso/richards3. + other_directory, _, name = name.rpartition("/") ident = "%s/%s" % (suite, name) if pattern and not re.search(pattern, ident): continue iterations, options, workload = split_args(list(harness_args)) - rel = "%s/%s/%s.py" % (BENCH_REL, directory, name) + rel = "%s/%s/%s.py" % (BENCH_REL, other_directory or directory, name) # The identity CodSpeed keeps the history under. The workload size is part of it, the # iteration count is not. uri = "%s::%s%s" % (rel, ident, "[%s]" % ",".join(workload) if workload else "") yield {"id": ident, "suite": suite, "uri": uri, "file": os.path.join(REPO, rel), - "iterations": iterations, "options": options, "workload": workload} + "iterations": iterations, "options": options, "workload": workload, + "python_args": config.get("python_args", []) if suite_options else [], + "process": config.get("process", False)} def quantile(values, p): @@ -152,20 +172,25 @@ def walltime_stats(durations_s): } -def run_one(python, bench, min_iterations, max_iterations, timeout, python_args=(), log=None): - """-> (status, durations in seconds, pid, output tail, peak RSS of the process in KiB)""" - iterations = max(bench["iterations"], min_iterations) - if max_iterations: - iterations = min(iterations, max_iterations) - cmd = ([python] + list(python_args) + [HARNESS, bench["file"], "-i", str(iterations)] + bench["options"] - + bench["workload"]) - # With CI set the harness stops early once long iterations look stable; every iteration is wanted here. - env = {k: v for k, v in os.environ.items() if k != "CI"} - # Some C API benchmarks call functions that the public headers do not declare. GCC 14 and - # clang 16 made that an error; it was a warning when the benchmarks were written. - env["CFLAGS"] = (env.get("CFLAGS", "") + " -Wno-error=implicit-function-declaration").strip() - proc = subprocess.Popen(cmd, cwd=os.path.dirname(bench["file"]), env=env, stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, text=True, errors="replace") +def memory_stats(rss_kb, rounds): + """Walltime statistics that carry a peak RSS instead of a time, 1 ms per MiB, the same in every round.""" + ns = rss_kb / 1024 * 1e6 + return { + "min_ns": ns, "max_ns": ns, "mean_ns": ns, "stdev_ns": 0.0, + "q1_ns": ns, "median_ns": ns, "q3_ns": ns, + "rounds": rounds, "total_time": ns * rounds / 1e9, + "iqr_outlier_rounds": 0, "stdev_outlier_rounds": 0, + "iter_per_round": 1, "warmup_iters": 0, + } + + +def spawn(cmd, cwd, env, timeout): + """Runs one process. -> (status or None after exit 0, output, pid, peak RSS in KiB, wall time in seconds) + + On Linux the peak RSS is the maximum of the process and of the children it waited for.""" + started = time.monotonic() + proc = subprocess.Popen(cmd, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, + errors="replace") # The process is reaped with wait4 for its resource usage: getrusage(RUSAGE_CHILDREN) would give # the maximum over all benchmarks run so far. timed_out = threading.Event() @@ -187,40 +212,102 @@ def run_one(python, bench, min_iterations, max_iterations, timeout, python_args= finally: timer.cancel() proc.stdout.close() - max_rss_kb = usage.ru_maxrss # KiB on Linux, bytes on macOS + elapsed = time.monotonic() - started + # KiB on Linux, bytes on macOS + rss_kb = usage.ru_maxrss // 1024 if sys.platform == "darwin" else usage.ru_maxrss + if timed_out.is_set(): + return "timeout after %ds" % timeout, out, proc.pid, rss_kb, elapsed + if proc.returncode != 0: + return "exit %d" % proc.returncode, out, proc.pid, rss_kb, elapsed + return None, out, proc.pid, rss_kb, elapsed + + +def run_one(python, bench, min_iterations, max_iterations, timeout, python_args=(), log=None): + """-> (status, durations in seconds, pid, output tail, peak RSS in KiB of each process) + + A benchmark of the harness is one process; one of the suite "memory" is one process per iteration.""" + iterations = max(bench["iterations"], min_iterations) + if max_iterations: + iterations = min(iterations, max_iterations) + interpreter = [python] + bench["python_args"] + list(python_args) + # With CI set the harness stops early once long iterations look stable; every iteration is wanted here. + env = {k: v for k, v in os.environ.items() if k != "CI"} + # Some C API benchmarks call functions that the public headers do not declare. GCC 14 and + # clang 16 made that an error; it was a warning when the benchmarks were written. + env["CFLAGS"] = (env.get("CFLAGS", "") + " -Wno-error=implicit-function-declaration").strip() + cwd = os.path.dirname(bench["file"]) + if bench["process"]: + # The duration is the whole life of the process, from the start of the interpreter to its exit. + cmd = interpreter + [bench["file"]] + bench["workload"] + durations, rss, outputs, pid = [], [], [], None + for _ in range(iterations): + status, out, pid, rss_kb, elapsed = spawn(cmd, cwd, env, timeout) + outputs.append(out) + rss.append(rss_kb) + if status: + break + durations.append(elapsed) + out = "".join(outputs) + else: + cmd = interpreter + [HARNESS, bench["file"], "-i", str(iterations)] + bench["options"] + bench["workload"] + status, out, pid, rss_kb, _ = spawn(cmd, cwd, env, timeout) + rss = [rss_kb] if log: with open(log, "w") as f: f.write(" ".join(cmd) + "\n" + out) - if timed_out.is_set(): - return "timeout after %ds" % timeout, [], proc.pid, out[-3000:], max_rss_kb - if proc.returncode != 0: - return "exit %d" % proc.returncode, [], proc.pid, out[-3000:], max_rss_kb - # Full precision; the per-iteration lines are rounded to a millisecond. - match = re.search(r"^### RAW DURATIONS: \[([^\]]*)\]", out, re.M) - durations = [float(x) for x in match.group(1).split(",")] if match and match.group(1).strip() else [] + if status: + return status, [], pid, out[-3000:], rss + if not bench["process"]: + # Full precision; the per-iteration lines are rounded to a millisecond. + match = re.search(r"^### RAW DURATIONS: \[([^\]]*)\]", out, re.M) + durations = [float(x) for x in match.group(1).split(",")] if match and match.group(1).strip() else [] if len(durations) != iterations: - return "%d of %d iterations reported" % (len(durations), iterations), [], proc.pid, out[-3000:], max_rss_kb + return "%d of %d iterations reported" % (len(durations), iterations), [], pid, out[-3000:], rss if any(not math.isfinite(d) or d <= 0 for d in durations): - return "non-positive duration", [], proc.pid, out[-3000:], max_rss_kb - return "ok", durations, proc.pid, "", max_rss_kb + return "non-positive duration", [], pid, out[-3000:], rss + return "ok", durations, pid, "", rss + + +def memory_result(bench, rss): + """-> (name of the peak RSS result, peak RSS in KiB): the median over the processes whose durations are + the samples, the second half.""" + return bench["uri"] + MEMORY_SUFFIX, statistics.median(rss[len(rss) // 2:]) -def write_result(folder, bench, stats, pid): +def write_result(folder, bench, stats, pid, memory=None): + """memory: (uri, statistics) of a second result in the same file.""" results = os.path.join(folder, "results") os.makedirs(results, exist_ok=True) + config = {"warmup_time_ns": None, "min_round_time_ns": None, "max_time_ns": None, "max_rounds": None} + entries = [(bench["uri"], stats)] + ([memory] if memory else []) report = { "creator": dict(CREATOR, pid=pid), "instrument": {"type": "walltime"}, - "benchmarks": [{ - "name": bench["uri"].split("::", 1)[1], "uri": bench["uri"], - "config": {"warmup_time_ns": None, "min_round_time_ns": None, "max_time_ns": None, "max_rounds": None}, - "stats": stats, - }], + "benchmarks": [{"name": uri.split("::", 1)[1], "uri": uri, "config": config, "stats": s} + for uri, s in entries], } with open(os.path.join(results, "%d.json" % pid), "w") as f: json.dump(report, f) +def markdown_table(summary, label): + """The peak RSS of every benchmark, for the job summary of the workflow run.""" + lines = ["### Peak RSS%s" % (" (%s)" % label if label else ""), "", + "CodSpeed only shows times. The peak RSS of a harness benchmark is that of its whole process, all" + " iterations; in the suite memory it is the median over the processes of the second half" + " of the iterations, each a fresh process.", "", + "| benchmark | median s | min s | peak RSS MiB | of |", "|---|---:|---:|---:|---|"] + for uri, data in summary["measured"].items(): + per_process = "rss_kb_per_process" in data + rss_kb = data["peak_rss_kb"] if per_process else data["max_rss_kb"] + lines.append("| `%s` | %.4f | %.4f | %.1f | %s |" % ( + uri.split("::", 1)[1], data["median_ns"] / 1e9, data["min_ns"] / 1e9, rss_kb / 1024, + "one process" if per_process else "harness process")) + if summary["failed"]: + lines += ["", "Failed: " + ", ".join("`%s`" % ident for ident in summary["failed"])] + return "\n".join(lines) + "\n" + + def main(): parser = argparse.ArgumentParser(description="Report GraalPy harness benchmarks to CodSpeed (walltime).") parser.add_argument("--python", required=True, help="interpreter to measure") @@ -232,6 +319,9 @@ def main(): parser.add_argument("--python-arg", action="append", default=[], metavar="ARG", help="option for the interpreter, before the harness, e.g. --python-arg=--vm.XX:+PrintGC; " "repeatable. Not allowed when reporting to CodSpeed") + parser.add_argument("--no-suite-options", action="store_true", + help="leave out the interpreter options that belong to a suite (those of interp), e.g. to " + "run the suites on CPython; not allowed when reporting to CodSpeed") parser.add_argument("--label", help="name of this configuration in the output and walltime-summary.json") parser.add_argument("--log-dir", help="directory for the complete output of every benchmark process") parser.add_argument("--min-iterations", type=int, default=MIN_ITERATIONS) @@ -261,17 +351,20 @@ def main(): absolute = lambda path: os.path.abspath(path) if os.path.exists(path) else path args.python = absolute(args.python) pythons = {suite: absolute(path) for suite, path in pythons.items()} - selected = list(benchmarks(args.suite, args.bench)) + selected = list(benchmarks(args.suite, args.bench, not args.no_suite_options)) if not selected: parser.error("no benchmark selected") if args.list: for bench in selected: - print(bench["uri"], "(skipped: %s)" % SKIP[bench["id"]] if bench["id"] in SKIP else "") + notes = bench["python_args"] + (["(skipped: %s)" % SKIP[bench["id"]]] if bench["id"] in SKIP else []) + print(" ".join([bench["uri"]] + notes)) return 0 folder = os.environ.get("CODSPEED_PROFILE_FOLDER") if folder and args.python_arg: parser.error("--python-arg changes what is measured: not allowed with CODSPEED_PROFILE_FOLDER set") + if folder and args.no_suite_options: + parser.error("--no-suite-options changes what is measured: not allowed with CODSPEED_PROFILE_FOLDER set") if args.log_dir: os.makedirs(args.log_dir, exist_ok=True) if args.label: @@ -279,7 +372,7 @@ def main(): flush=True) if not folder: print("CODSPEED_PROFILE_FOLDER is not set: nothing is reported to CodSpeed", flush=True) - failed, measured, summary = [], 0, {} + failed, measured, summary, memory = [], 0, {}, {} print("%-48s %10s %10s %7s %s" % ("benchmark", "median s", "stdev s", "rounds", "status"), flush=True) for bench in selected: if bench["id"] in SKIP: @@ -287,29 +380,45 @@ def main(): continue started = time.monotonic() log = os.path.join(args.log_dir, bench["id"].replace("/", "__") + ".log") if args.log_dir else None - status, durations, pid, tail, max_rss_kb = run_one(pythons.get(bench["suite"], args.python), bench, - args.min_iterations, args.max_iterations, args.timeout, - args.python_arg, log) + status, durations, pid, tail, rss = run_one(pythons.get(bench["suite"], args.python), bench, + args.min_iterations, args.max_iterations, args.timeout, + args.python_arg, log) if status != "ok": failed.append(bench["id"]) print("%-48s %10s %10s %7s FAILED: %s" % (bench["id"], "-", "-", "-", status), flush=True) print(tail, flush=True) continue stats = walltime_stats(durations) - if folder: - write_result(folder, bench, stats, pid) # The summary also keeps every iteration's duration, which CodSpeed does not take. - summary[bench["uri"]] = dict(stats, durations_s=durations, max_rss_kb=max_rss_kb) + summary[bench["uri"]] = dict(stats, durations_s=durations, max_rss_kb=max(rss)) + if bench["process"]: + memory_uri, rss_kb = memory_result(bench, rss) + summary[bench["uri"]].update(rss_kb_per_process=rss, peak_rss_kb=rss_kb) + # Kept apart from the times: a peak RSS that CodSpeed takes as a time, 1 ms per MiB. + memory[memory_uri] = {"kind": "memory", "metric": "peak RSS", "unit": "KiB", + "codspeed_scale": "1 ms = 1 MiB", "of": bench["uri"], "peak_rss_kb": rss_kb, + "rss_kb_per_process": rss} + else: + rss_kb = max(rss) + if folder: + write_result(folder, bench, stats, pid, + (memory_uri, memory_stats(rss_kb, stats["rounds"])) if bench["process"] else None) measured += 1 - print("%-48s %10.4f %10.4f %7d ok (%ds)" % (bench["id"], stats["median_ns"] / 1e9, stats["stdev_ns"] / 1e9, - stats["rounds"], time.monotonic() - started), flush=True) + print("%-48s %10.4f %10.4f %7d ok (%ds, %d MiB)" % (bench["id"], stats["median_ns"] / 1e9, + stats["stdev_ns"] / 1e9, stats["rounds"], + time.monotonic() - started, rss_kb / 1024), flush=True) if args.output: os.makedirs(args.output, exist_ok=True) with open(os.path.join(args.output, "walltime-summary.json"), "w") as f: - result = {"measured": summary, "failed": failed} + result = {"measured": summary, "memory": memory, "failed": failed} if args.label or args.python_arg: result.update(label=args.label, python_args=args.python_arg) + suite_options = {b["suite"]: b["python_args"] for b in selected if b["python_args"]} + if suite_options: + result.update(suite_python_args=suite_options) json.dump(result, f, indent=1) + with open(os.path.join(args.output, "walltime-summary.md"), "w") as f: + f.write(markdown_table(result, args.label)) print("%d measured, %d failed%s" % (measured, len(failed), ": " + ", ".join(failed) if failed else "")) if not measured: return 1 diff --git a/.github/workflows/elide-codspeed.yml b/.github/workflows/elide-codspeed.yml index bc330c613d..142c4f3deb 100644 --- a/.github/workflows/elide-codspeed.yml +++ b/.github/workflows/elide-codspeed.yml @@ -1,7 +1,10 @@ name: CodSpeed benchmarks # Steady-state wall time of the C API micro benchmarks, the pure Python meso benchmarks and # benchmarks of real packages (pydantic, orjson, pandas, numpy, lxml) on a native standalone, -# reported to CodSpeed (https://app.codspeed.io/elide-dev/graalpython). +# reported to CodSpeed (https://app.codspeed.io/elide-dev/graalpython). Also some meso benchmarks +# without the JIT compiler (interp), the start-up of fresh processes (startup) and the peak RSS of +# fresh processes (memory), which CodSpeed shows as a time, 1 ms per MiB. The run's summary page has +# the peak RSS of every benchmark. # # Wall time needs a dedicated machine, so the measurement runs on the self-hosted benchmark runner # linux-amd64-bench. The repository variable @@ -263,6 +266,13 @@ jobs: python3 .github/elide/codspeed-bench --python "$GRAALPY" \ --bench '^micro-native/(c-instantiate-large|c-to-c|c-call-method-obj-args)$' + # Four iterations each, so that an option the build does not know or a failing benchmark + # fails here and not on the benchmark host. + - name: Run the interpreter, start-up and memory benchmarks briefly + run: | + python3 .github/elide/codspeed-bench --python "$RUNNER_TEMP/GRAALPY_NATIVE_STANDALONE/bin/graalpy" \ + --suite interp startup memory --max-iterations 4 + # Four iterations each: every iteration checks its result. - name: Run the package benchmarks briefly run: | @@ -332,10 +342,18 @@ jobs: python3 .github/elide/codspeed-bench --python "${{ runner.temp }}/GRAALPY_NATIVE_STANDALONE/bin/graalpy" --suite-python packages="${{ runner.temp }}/venv/bin/python" - --suite micro-native meso packages + --suite micro-native meso packages interp startup memory --output "${{ env.BENCH_OUTPUT }}" --defer-failures + # CodSpeed only takes times: the peak RSS of every benchmark goes to the run's summary page. + - name: Peak RSS table + if: ${{ !cancelled() }} + run: | + if [ -f "$BENCH_OUTPUT/walltime-summary.md" ]; then + cat "$BENCH_OUTPUT/walltime-summary.md" >> "$GITHUB_STEP_SUMMARY" + fi + # A failed benchmark does not stop the others from being reported, but it fails the job. - name: Fail on failed benchmarks run: | @@ -352,7 +370,9 @@ jobs: uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0 with: name: codspeed-walltime-${{ github.run_attempt }} - path: ${{ env.BENCH_OUTPUT }}/*.json + path: | + ${{ env.BENCH_OUTPUT }}/*.json + ${{ env.BENCH_OUTPUT }}/*.md retention-days: 14 if-no-files-found: warn diff --git a/graalpython/com.oracle.graal.python.benchmarks/python/interp/benchmarks.txt b/graalpython/com.oracle.graal.python.benchmarks/python/interp/benchmarks.txt new file mode 100644 index 0000000000..ea091581de --- /dev/null +++ b/graalpython/com.oracle.graal.python.benchmarks/python/interp/benchmarks.txt @@ -0,0 +1,18 @@ +# The benchmarks of the suite "interp" of .github/elide/codspeed-bench: some of upstream's meso +# benchmarks, run with Truffle compilation switched off (--engine.Compilation=false, given by the +# driver to every benchmark of the suite), so that they measure the interpreter alone. One line per +# benchmark: the file under graalpython/com.oracle.graal.python.benchmarks/python without .py, +# followed by its harness arguments (-i iterations, then the workload arguments). +# +# The sizes are much smaller than those of the suite "meso", so that an iteration takes about 0.2 to +# 1 s without the compiler. On CodSpeed a row is interp/[], next to meso/[] +# of the compiled run. Without the compiler there is little warm-up, so ten iterations are enough; +# the second half is reported. +# +# file harness arguments +meso/richards3 -i 10 1 # classes, attribute access, method calls +meso/bm-float -i 10 4 # float arithmetic, math functions, object allocation +meso/nbody3 -i 10 30000 # float loops over lists and tuples +meso/raytrace-simple -i 10 50 50 # a ray tracer: objects, attributes, method calls, floats +meso/fannkuchredux3 -i 10 8 # list slicing and reversal, integer loops +meso/fasta3 -i 10 50000 # list indexing, bisect, string slices diff --git a/graalpython/com.oracle.graal.python.benchmarks/python/memory/benchmarks.txt b/graalpython/com.oracle.graal.python.benchmarks/python/memory/benchmarks.txt new file mode 100644 index 0000000000..beefe7d348 --- /dev/null +++ b/graalpython/com.oracle.graal.python.benchmarks/python/memory/benchmarks.txt @@ -0,0 +1,16 @@ +# The benchmarks of the suite "memory" of .github/elide/codspeed-bench. Unlike the other suites they +# are scripts, not harness benchmarks: every iteration runs the script in a fresh process of the +# interpreter, ` .py `, and the driver takes the wall time and +# the peak RSS of that process (wait4). Each benchmark gives two rows on CodSpeed: the wall time of +# a process, memory/[], and its peak RSS as a time, 1 ms per MiB, +# memory/[][peak-rss: 1 ms = 1 MiB]. +# +# One line per script in this folder, followed by -i (the number of processes; the second half is +# reported) and the workload arguments, which are part of the name on CodSpeed. +# +# name harness arguments +idle -i 8 +stdlib-imports -i 8 +objects -i 8 1000000 +dicts -i 8 1000000 +strings -i 8 1000000 diff --git a/graalpython/com.oracle.graal.python.benchmarks/python/memory/dicts.py b/graalpython/com.oracle.graal.python.benchmarks/python/memory/dicts.py new file mode 100644 index 0000000000..eb2e782ba7 --- /dev/null +++ b/graalpython/com.oracle.graal.python.benchmarks/python/memory/dicts.py @@ -0,0 +1,7 @@ +# Holds the argument's number of small dicts, two string keys each, in a list. Run as a script by +# .github/elide/codspeed-bench, see benchmarks.txt. +import sys + +n = int(sys.argv[1]) +dicts = [{"name": "foo", "value": i} for i in range(n)] +assert len(dicts) == n and dicts[-1]["value"] == n - 1 diff --git a/graalpython/com.oracle.graal.python.benchmarks/python/memory/idle.py b/graalpython/com.oracle.graal.python.benchmarks/python/memory/idle.py new file mode 100644 index 0000000000..fb16a604d8 --- /dev/null +++ b/graalpython/com.oracle.graal.python.benchmarks/python/memory/idle.py @@ -0,0 +1,2 @@ +# The interpreter after start-up, with nothing run: the same as heap/post-startup.py without its +# sleep. Run as a script by .github/elide/codspeed-bench, see benchmarks.txt. diff --git a/graalpython/com.oracle.graal.python.benchmarks/python/memory/objects.py b/graalpython/com.oracle.graal.python.benchmarks/python/memory/objects.py new file mode 100644 index 0000000000..dfa9fec194 --- /dev/null +++ b/graalpython/com.oracle.graal.python.benchmarks/python/memory/objects.py @@ -0,0 +1,15 @@ +# Holds the argument's number of instances of a small class with two attributes in a list: the +# workload of heap/allocate-objects.py, without its sleep. Run as a script by +# .github/elide/codspeed-bench, see benchmarks.txt. +import sys + + +class MyObject: + def __init__(self, name, value): + self.name = name + self.value = value + + +n = int(sys.argv[1]) +objects = [MyObject("foo", i) for i in range(n)] +assert len(objects) == n and objects[-1].value == n - 1 diff --git a/graalpython/com.oracle.graal.python.benchmarks/python/memory/stdlib-imports.py b/graalpython/com.oracle.graal.python.benchmarks/python/memory/stdlib-imports.py new file mode 100644 index 0000000000..4471cea547 --- /dev/null +++ b/graalpython/com.oracle.graal.python.benchmarks/python/memory/stdlib-imports.py @@ -0,0 +1,15 @@ +# The interpreter after importing a fixed set of standard library modules. Run as a script by +# .github/elide/codspeed-bench, see benchmarks.txt; startup/stdlib-imports.py starts it as a process +# too, so both suites import the same set. +import argparse +import asyncio +import collections +import dataclasses +import datetime +import decimal +import json +import logging +import pathlib +import re +import subprocess +import typing diff --git a/graalpython/com.oracle.graal.python.benchmarks/python/memory/strings.py b/graalpython/com.oracle.graal.python.benchmarks/python/memory/strings.py new file mode 100644 index 0000000000..085a90693f --- /dev/null +++ b/graalpython/com.oracle.graal.python.benchmarks/python/memory/strings.py @@ -0,0 +1,7 @@ +# Holds the argument's number of distinct short strings (up to seven ASCII characters) in a list. +# Run as a script by .github/elide/codspeed-bench, see benchmarks.txt. +import sys + +n = int(sys.argv[1]) +strings = ["s%d" % i for i in range(n)] +assert len(strings) == n and strings[-1] == "s%d" % (n - 1) diff --git a/graalpython/com.oracle.graal.python.benchmarks/python/packages/benchmarks.txt b/graalpython/com.oracle.graal.python.benchmarks/python/packages/benchmarks.txt index d795106661..b1902069dc 100644 --- a/graalpython/com.oracle.graal.python.benchmarks/python/packages/benchmarks.txt +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/benchmarks.txt @@ -10,6 +10,8 @@ pydantic-json -i 40 8000 pydantic-models -i 40 10000 orjson-roundtrip -i 40 2500 +orjson-loads -i 40 2500 +orjson-dumps -i 40 2500 pandas-csv -i 40 50000 pandas-str -i 40 20000 pandas-groupby-merge -i 40 150000 diff --git a/graalpython/com.oracle.graal.python.benchmarks/python/packages/orjson-dumps.py b/graalpython/com.oracle.graal.python.benchmarks/python/packages/orjson-dumps.py new file mode 100644 index 0000000000..d14af54dcf --- /dev/null +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/orjson-dumps.py @@ -0,0 +1,78 @@ +# orjson: the serialising half of orjson-roundtrip.py, on the same document: dumps of the nested +# document tree, also with OPT_INDENT_2 | OPT_SORT_KEYS, and dumps of a list of dataclasses. +# +# Run with harness.py by .github/elide/codspeed-bench, see .github/elide/README.md. The argument is +# the number of users in the document. One iteration does the work ROUNDS times. +import dataclasses +import importlib.util +import math +import os + +import orjson + +# number of users -> result of one round; the dumps parts of the result of orjson-roundtrip.py +EXPECTED = { + 2500: (4290716, 1962336, 316515), +} +ROUNDS = 4 +REL_TOL = 1e-9 + +# The document of orjson-roundtrip.py, built by its own function. +_spec = importlib.util.spec_from_file_location( + "orjson_roundtrip", os.path.join(os.path.dirname(os.path.abspath(__file__)), "orjson-roundtrip.py")) +_roundtrip = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(_roundtrip) +make_doc = _roundtrip.make_doc + + +@dataclasses.dataclass +class Event: + t: int + kind: str + value: int + + +DOC = None +EVENTS = None +_first = [] + + +def _check(size, result): + """Fails the benchmark on a wrong result. Floats differ in the last digits between platforms.""" + expected = EXPECTED.get(size) + if expected is None: + if not _first: + _first.append(result) + print("### no expected result for size %d, the first iteration gave %r" % (size, result)) + expected = _first[0] + if len(result) != len(expected) or not all( + math.isclose(r, e, rel_tol=REL_TOL) if isinstance(e, float) else r == e + for r, e in zip(result, expected)): + raise AssertionError("wrong result for size %d: %r, expected %r" % (size, result, expected)) + + +def __setup__(size=2500): + global DOC, EVENTS + DOC = make_doc(size, 11) + EVENTS = [Event(e["t"], e["kind"], e["value"]) for u in DOC["users"] for e in u["events"]] + + +def one_round(size): + dumped = 0 + for _ in range(4): + dumped += len(orjson.dumps(DOC)) + pretty = len(orjson.dumps(DOC, option=orjson.OPT_INDENT_2 | orjson.OPT_SORT_KEYS)) + events = len(orjson.dumps(EVENTS)) + result = (dumped, pretty, events) + _check(size, result) + return result + + +def measure(size): + for _ in range(ROUNDS): + result = one_round(size) + return result + + +def __benchmark__(size=2500): + return measure(size) diff --git a/graalpython/com.oracle.graal.python.benchmarks/python/packages/orjson-loads.py b/graalpython/com.oracle.graal.python.benchmarks/python/packages/orjson-loads.py new file mode 100644 index 0000000000..af1968a8bc --- /dev/null +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/orjson-loads.py @@ -0,0 +1,68 @@ +# orjson: the parsing half of orjson-roundtrip.py, on the same document: loads of the serialised +# nested document tree, five times per round as there. +# +# Run with harness.py by .github/elide/codspeed-bench, see .github/elide/README.md. The argument is +# the number of users in the document. One iteration does the work ROUNDS times. +import importlib.util +import math +import os + +import orjson + +# number of users -> result of one round; the loads parts of the result of orjson-roundtrip.py +EXPECTED = { + 2500: (10000, 6334, 11078071.56), +} +ROUNDS = 4 +REL_TOL = 1e-9 + +# The document of orjson-roundtrip.py, built by its own function. +_spec = importlib.util.spec_from_file_location( + "orjson_roundtrip", os.path.join(os.path.dirname(os.path.abspath(__file__)), "orjson-roundtrip.py")) +_roundtrip = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(_roundtrip) +make_doc = _roundtrip.make_doc + +BLOB = b"" +_first = [] + + +def _check(size, result): + """Fails the benchmark on a wrong result. Floats differ in the last digits between platforms.""" + expected = EXPECTED.get(size) + if expected is None: + if not _first: + _first.append(result) + print("### no expected result for size %d, the first iteration gave %r" % (size, result)) + expected = _first[0] + if len(result) != len(expected) or not all( + math.isclose(r, e, rel_tol=REL_TOL) if isinstance(e, float) else r == e + for r, e in zip(result, expected)): + raise AssertionError("wrong result for size %d: %r, expected %r" % (size, result, expected)) + + +def __setup__(size=2500): + global BLOB + BLOB = orjson.dumps(make_doc(size, 11)) + + +def one_round(size): + loaded = 0 + for _ in range(4): + loaded += len(orjson.loads(BLOB)["users"]) + doc = orjson.loads(BLOB) + tags = sum(len(u["tags"]) for u in doc["users"]) + balance = sum(u["balance"] for u in doc["users"]) + result = (loaded, tags, balance) + _check(size, result) + return result + + +def measure(size): + for _ in range(ROUNDS): + result = one_round(size) + return result + + +def __benchmark__(size=2500): + return measure(size) diff --git a/graalpython/com.oracle.graal.python.benchmarks/python/startup/benchmarks.txt b/graalpython/com.oracle.graal.python.benchmarks/python/startup/benchmarks.txt new file mode 100644 index 0000000000..52b2275dc3 --- /dev/null +++ b/graalpython/com.oracle.graal.python.benchmarks/python/startup/benchmarks.txt @@ -0,0 +1,12 @@ +# The benchmarks of the suite "startup" of .github/elide/codspeed-bench: one line per benchmark file +# in this folder, followed by its harness arguments (-i iterations, then the workload arguments). +# +# One iteration starts the workload argument's number of fresh processes of the interpreter, one +# after the other, so that it takes at least about 0.3 s; the argument is part of the name on +# CodSpeed. Every process starts cold, so there is no warm-up to wait for in them; the first half of +# the iterations is still not reported, as in the other suites. +# +# name harness arguments +pass -i 10 10 # -c pass +stdlib-imports -i 10 3 # imports of a fixed set of standard library modules +first-run -i 10 3 # a small pure Python workload, run once diff --git a/graalpython/com.oracle.graal.python.benchmarks/python/startup/first-run.py b/graalpython/com.oracle.graal.python.benchmarks/python/startup/first-run.py new file mode 100644 index 0000000000..65b4c53e85 --- /dev/null +++ b/graalpython/com.oracle.graal.python.benchmarks/python/startup/first-run.py @@ -0,0 +1,82 @@ +# First run: one iteration starts the argument's number of fresh processes of the interpreter, one +# after the other, each of which runs a small pure Python workload once (objects and method calls, +# string formatting and splitting, dicts, sorting, generators, closures, exceptions) and checks its +# result; the time is start-up plus the first, cold execution of the code, with no warm-up. +# +# Run with harness.py by .github/elide/codspeed-bench, see benchmarks.txt. The processes run this +# file as a script, with the interpreter options of the harness process (those before the harness +# on its command line). +import subprocess +import sys + +EXPECTED = (750.0, ("w0", 20), 1000, 21171191, 2000) + + +def workload(): + class Vec: + def __init__(self, x, y): + self.x = x + self.y = y + + def add(self, other): + return Vec(self.x + other.x, self.y + other.y) + + def scale(self, factor): + return Vec(self.x * factor, self.y * factor) + + points = [Vec(i, -i) for i in range(200)] + velocity = Vec(0.5, 0.25) + for _ in range(50): + points = [p.add(velocity.scale(0.1)) for p in points] + position = round(sum(p.x + p.y for p in points), 6) + + text = " ".join("w%d" % (i * 7919 % 1000) for i in range(20000)) + counts = {} + for word in text.split(): + counts[word] = counts.get(word, 0) + 1 + top = sorted(counts.items(), key=lambda item: (-item[1], item[0])) + + def primes(limit): + composite = set() + for i in range(2, limit): + if i not in composite: + yield i + composite.update(range(i * i, limit, i)) + + def counter(): + count = 0 + + def increment(): + nonlocal count + count += 1 + return count + return increment + + missing = counter() + table = {} + for i in range(2000): + try: + table[i] + except KeyError: + missing() + return position, top[0], len(counts), sum(primes(20000)), missing() - 1 + + +def interpreter(): + """The command line of this interpreter up to the script, with its options. GraalPy itself passes on + only a few options to a process of sys.executable (--experimental-options and some for its backends), + which the process then gets twice.""" + return [sys.executable] + sys.orig_argv[1:len(sys.orig_argv) - len(sys.argv)] + + +def __benchmark__(processes=3): + cmd = interpreter() + [__file__] + for _ in range(processes): + subprocess.run(cmd, stdin=subprocess.DEVNULL, check=True) + return processes + + +if __name__ == "__main__": + result = workload() + if result != EXPECTED: + sys.exit("wrong result %r, expected %r" % (result, EXPECTED)) diff --git a/graalpython/com.oracle.graal.python.benchmarks/python/startup/pass.py b/graalpython/com.oracle.graal.python.benchmarks/python/startup/pass.py new file mode 100644 index 0000000000..006c1522e2 --- /dev/null +++ b/graalpython/com.oracle.graal.python.benchmarks/python/startup/pass.py @@ -0,0 +1,21 @@ +# Start-up: one iteration starts the argument's number of fresh processes of the interpreter that +# run `-c pass`, one after the other, and waits for each. +# +# Run with harness.py by .github/elide/codspeed-bench, see benchmarks.txt. The processes get the +# interpreter options of the harness process (those before the harness on its command line). +import subprocess +import sys + + +def interpreter(): + """The command line of this interpreter up to the script, with its options. GraalPy itself passes on + only a few options to a process of sys.executable (--experimental-options and some for its backends), + which the process then gets twice.""" + return [sys.executable] + sys.orig_argv[1:len(sys.orig_argv) - len(sys.argv)] + + +def __benchmark__(processes=10): + cmd = interpreter() + ["-c", "pass"] + for _ in range(processes): + subprocess.run(cmd, stdin=subprocess.DEVNULL, check=True) + return processes diff --git a/graalpython/com.oracle.graal.python.benchmarks/python/startup/stdlib-imports.py b/graalpython/com.oracle.graal.python.benchmarks/python/startup/stdlib-imports.py new file mode 100644 index 0000000000..1b094d9de7 --- /dev/null +++ b/graalpython/com.oracle.graal.python.benchmarks/python/startup/stdlib-imports.py @@ -0,0 +1,27 @@ +# Start-up and imports: one iteration starts the argument's number of fresh processes of the +# interpreter that import a fixed set of standard library modules (json, re, decimal, datetime, +# collections, pathlib, argparse, logging, subprocess, typing, dataclasses, asyncio), one after the +# other, and waits for each. The processes run memory/stdlib-imports.py, the script of the +# benchmark memory/stdlib-imports, so both import the same set. +# +# Run with harness.py by .github/elide/codspeed-bench, see benchmarks.txt. The processes get the +# interpreter options of the harness process (those before the harness on its command line). +import os +import subprocess +import sys + +SCRIPT = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "memory", "stdlib-imports.py") + + +def interpreter(): + """The command line of this interpreter up to the script, with its options. GraalPy itself passes on + only a few options to a process of sys.executable (--experimental-options and some for its backends), + which the process then gets twice.""" + return [sys.executable] + sys.orig_argv[1:len(sys.orig_argv) - len(sys.argv)] + + +def __benchmark__(processes=3): + cmd = interpreter() + [SCRIPT] + for _ in range(processes): + subprocess.run(cmd, stdin=subprocess.DEVNULL, check=True) + return processes