diff --git a/.github/elide/README.md b/.github/elide/README.md index 1675e8d873..c7f77a185b 100644 --- a/.github/elide/README.md +++ b/.github/elide/README.md @@ -2,7 +2,8 @@ This repository is a fork of [oracle/graalpython](https://github.com/oracle/graalpython). Everything the fork adds to CI is in this folder and in workflow files named `elide-*.yml`. GitHub only reads -workflows from `.github/workflows`, so the workflow files cannot live here. +workflows from `.github/workflows`, so the workflow files cannot live here. The package benchmarks +live with GraalPy's other benchmarks, in a folder of their own (see "Package benchmarks"). The fork does not edit upstream's files, so merging from upstream cannot conflict with its CI. The one exception is listed at the end. @@ -42,14 +43,120 @@ work on GitHub. The comments in the workflow say why. ## Benchmarks -`elide-codspeed.yml` measures the wall time of GraalPy's C API micro benchmarks and pure Python -meso benchmarks on a native standalone and reports it to CodSpeed +`elide-codspeed.yml` measures the wall time of GraalPy's C API micro benchmarks, its pure Python +meso benchmarks and benchmarks of real packages on a native standalone and reports it to CodSpeed (https://app.codspeed.io/elide-dev/graalpython). It runs on pushes to `develop` and `elide-*.x`, and on pull requests that carry the label `perf:bench`. `codspeed-bench` is the driver that runs the benchmarks and writes the results. -The standalone is 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. +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. + +### Package benchmarks + +The suite `packages` of `codspeed-bench` measures pydantic, orjson, pandas, numpy and lxml. Its +files are next to upstream's benchmarks, in the fork's own folder +`graalpython/com.oracle.graal.python.benchmarks/python/packages`, which upstream does not have, so +merges from upstream cannot conflict with it: + +| Benchmark | What one iteration does | +|---|---| +| `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 | +| `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 | +| `pandas-apply` | `DataFrame.apply(axis=1)`, `Series.apply` and `Series.map` with Python functions, `iterrows`, `itertuples` | +| `numpy-small-ops` | a particle simulation on many 3-element arrays from a Python loop | +| `numpy-vectorized` | ufuncs, reductions, sort, percentile, an FFT and a small linear solve on large arrays | +| `lxml-xpath` | parse, XPath queries, edits and serialization of an XML document, and `lxml.html` parsing of a table | + +Each file is in the format of upstream's `harness.py`, like the files in `meso` and `micro`: +`__setup__(size)` builds the input from a fixed seed and is not measured, `__benchmark__(size)` is +one measured iteration and calls `measure(size)`. Some benchmarks repeat the work `ROUNDS` times +per iteration on smaller data. That was meant to make their iterations on GraalPy steadier, and it +did not: orjson-roundtrip, pandas-csv, pandas-str, pandas-groupby-merge and lxml-xpath still vary +by up to a factor of ten from one iteration to the next. A diagnose run (see "Diagnosing noisy rows") +traced the variation to garbage collection pauses, which take 40 to 70% of an iteration on these +rows, from two causes in GraalPy's memory management: + +- On orjson-roundtrip, pandas-csv, pandas-str and lxml-xpath the heap that survives a full + collection grows with every iteration (by 20 to 110 MB per iteration), although the benchmarks + keep nothing between iterations; it is only released after the last iteration. Collections + therefore take longer and longer (up to 7.6 s), and an iteration is slow when one falls into it. +- On pandas-groupby-merge, native allocations reach GraalPy's native memory limit + (`--python.InitialNativeMemory`, 256 MB) more often in every iteration, and each time GraalPy + forces full collections, up to 65 in one iteration, until it doubles the limit. Durations follow + the iteration number (17 s at iteration 10, 16 s at iteration 22, about 1 s after each doubling). + +The rows measure GraalPy's default behaviour, so they keep this variation until it is fixed. + +Every iteration (or round) compares its result +with `EXPECTED[size]` in the file and fails the benchmark when it differs; floats are compared with a +relative tolerance, because they differ in the last digits between platforms. Unlike upstream's +`macro` benchmarks, the files do not call `ensure_packages`: the packages are installed before the +run, from the wheels built on the pool. + +The fork does not edit upstream's benchmark table, `mx.graalpython/mx_graalpython_bench_param.py`, +so the folder has its own, `benchmarks.txt`: the benchmarks with their harness arguments (iterations +and size). The size is part of the name on CodSpeed, for example +`graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-csv.py::packages/pandas-csv[200000]`. + +The files are written for the fork and carry no copyright header. Upstream's style job, which this +CI does not run (see below), would flag them for the missing Oracle header. + +To add a benchmark: + +1. Write `.py` in the `packages` folder and add a line to its `benchmarks.txt`. Size it so that an + iteration takes about 0.2 to 3 s on GraalPy, and give it enough iterations that the second half, + which is what is reported, is warmed up (40 for the current ones). +2. Run it with CPython, for example + `python graalpython/com.oracle.graal.python.benchmarks/python/harness.py graalpython/com.oracle.graal.python.benchmarks/python/packages/.py -i 4 ` + with the `python` of a virtual environment that has the folder's `requirements.txt` installed. For a size + without an entry in `EXPECTED`, the first iteration prints its result and the others are compared + with it; copy it into `EXPECTED`. +3. `python3 .github/elide/codspeed-bench --python --suite packages --bench ` + runs it as the workflow does. +4. A new package goes into the folder's `requirements.txt` with all its dependencies pinned. + A package with compiled code also needs a build line in the `wheels` job of `elide-codspeed.yml`. + +The versions are pinned in the folder's `requirements.txt`. The compiled packages are built +from source with GraalPy's pip, which applies GraalPy's patch for the version from +`graalpython/lib-graalpython/patches/metadata.toml`; a new version needs a patch there or none at +all. A version change changes the measurement, so make it in a pull request of its own. + +The `wheels` job builds the wheels on the pool with the standalone of the run, every run, without a +cache: numpy without an external BLAS or LAPACK (numpy's own slower fallback routines, which is why +the linear algebra in `numpy-vectorized` is small), pandas against that numpy, lxml with libxml2 and +libxslt linked in statically, pydantic-core and orjson with a Rust toolchain installed into the +job's temporary directory. The pure Python packages come from PyPI as wheels. The job fails when a +wheel needs a shared library other than glibc, libstdc++ and libgcc_s, because the benchmark host +has only its base libraries and nothing can be installed there. `check` installs the wheels without +a network (`package-venv`) and runs every package benchmark for four iterations; `walltime` installs them into a +virtual environment in the job's temporary directory and runs the suite with that environment's +interpreter (`--suite-python`). + +### Diagnosing noisy rows + +A manual run of `elide-codspeed.yml` with the input `diagnose` set measures without reporting to +CodSpeed. Instead of `walltime`, its job `diagnose` runs the benchmarks selected by the input +`bench` on the benchmark host once per interpreter option set named in `variants`, with the number +of iterations of `iterations`: + +```sh +gh workflow run elide-codspeed.yml --ref -f diagnose=true -f variants=gc-log,default +``` + +The option sets are the lines of `codspeed-diagnose.txt` (`all` runs every line). `codspeed-diagnose` +runs `codspeed-bench` once per set with the set's options (`--python-arg`) and keeps, in the +artifact `codspeed-diagnose-`: every iteration's duration and the peak RSS of each +benchmark process (`/walltime-summary.json`), the complete output of each process with the GC +log (`/.log`), the collections per iteration (`diagnose-summary.json`) and the tables +(`diagnose.md`, also on the run's summary page). `check` starts the interpreter once with every set +first, so that an option the build does not know fails on the pool. `codspeed-bench` refuses +`--python-arg` when it would report to CodSpeed. ## Runners diff --git a/.github/elide/codspeed-bench b/.github/elide/codspeed-bench index 4128568034..1b2d53280d 100755 --- a/.github/elide/codspeed-bench +++ b/.github/elide/codspeed-bench @@ -7,6 +7,9 @@ # samples. One CodSpeed walltime result file is written per benchmark to # $CODSPEED_PROFILE_FOLDER/results. Without that variable (a local run) nothing is reported. --output # keeps a copy of all statistics in one file, whether or not CodSpeed takes them. +# +# --python-arg passes options to the interpreter, for diagnostic runs (codspeed-diagnose); such runs +# are never reported to CodSpeed. #!/usr/bin/env python3 import argparse @@ -15,9 +18,11 @@ import json import math import os import re +import signal import statistics import subprocess import sys +import threading import time import types @@ -32,6 +37,13 @@ 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. +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", +} DEFAULT_SUITES = ["micro-native", "meso"] # The second half of the iterations are the samples, so this gives at least four. @@ -64,6 +76,17 @@ def load_table(name): return getattr(module, name) +def load_own_table(directory): + """Reads benchmarks.txt of a suite of the fork: lines of a name and its harness arguments.""" + table = {} + with open(os.path.join(REPO, BENCH_REL, directory, "benchmarks.txt")) as f: + for line in f: + fields = line.split("#", 1)[0].split() + if fields: + table[fields[0]] = fields[1:] + return table + + def split_args(harness_args): """-> (iterations, other harness options, workload arguments)""" iterations, options, workload = 1, [], [] @@ -87,8 +110,11 @@ def split_args(harness_args): def benchmarks(suites, pattern): for suite in suites: - table, directory = SUITES[suite] - for name, harness_args in load_table(table).items(): + if suite in OWN_SUITES: + directory, table = OWN_SUITES[suite], load_own_table(OWN_SUITES[suite]) + else: + directory, table = SUITES[suite][1], load_table(SUITES[suite][0]) + for name, harness_args in table.items(): ident = "%s/%s" % (suite, name) if pattern and not re.search(pattern, ident): continue @@ -97,8 +123,8 @@ def benchmarks(suites, pattern): # 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, "uri": uri, "file": os.path.join(REPO, rel), "iterations": iterations, - "options": options, "workload": workload} + yield {"id": ident, "suite": suite, "uri": uri, "file": os.path.join(REPO, rel), + "iterations": iterations, "options": options, "workload": workload} def quantile(values, p): @@ -126,10 +152,13 @@ def walltime_stats(durations_s): } -def run_one(python, bench, min_iterations, timeout): - """-> (status, durations in seconds, pid, output tail)""" +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) - cmd = [python, HARNESS, bench["file"], "-i", str(iterations)] + bench["options"] + bench["workload"] + 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 @@ -137,22 +166,43 @@ def run_one(python, bench, min_iterations, timeout): 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") + # 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() + + def kill(): + # Not proc.kill(): that may reap the process before wait4 does. + timed_out.set() + try: + os.kill(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + + timer = threading.Timer(timeout, kill) + timer.start() try: - out, _ = proc.communicate(timeout=timeout) - except subprocess.TimeoutExpired: - proc.kill() - out, _ = proc.communicate() - return "timeout after %ds" % timeout, [], proc.pid, out[-3000:] + out = proc.stdout.read() + _, status, usage = os.wait4(proc.pid, 0) + proc.returncode = os.waitstatus_to_exitcode(status) + finally: + timer.cancel() + proc.stdout.close() + max_rss_kb = usage.ru_maxrss # KiB on Linux, bytes on macOS + 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:] + 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 len(durations) != iterations: - return "%d of %d iterations reported" % (len(durations), iterations), [], proc.pid, out[-3000:] + return "%d of %d iterations reported" % (len(durations), iterations), [], proc.pid, out[-3000:], max_rss_kb if any(not math.isfinite(d) or d <= 0 for d in durations): - return "non-positive duration", [], proc.pid, out[-3000:] - return "ok", durations, proc.pid, "" + return "non-positive duration", [], proc.pid, out[-3000:], max_rss_kb + return "ok", durations, proc.pid, "", max_rss_kb def write_result(folder, bench, stats, pid): @@ -174,9 +224,19 @@ def write_result(folder, bench, stats, pid): def main(): parser = argparse.ArgumentParser(description="Report GraalPy harness benchmarks to CodSpeed (walltime).") parser.add_argument("--python", required=True, help="interpreter to measure") - parser.add_argument("--suite", nargs="+", choices=sorted(SUITES), default=DEFAULT_SUITES) + parser.add_argument("--suite-python", action="append", default=[], metavar="SUITE=PATH", + help="interpreter for the benchmarks of one suite instead of --python, e.g. a " + "virtual environment of it with the packages the suite needs; repeatable") + parser.add_argument("--suite", nargs="+", choices=sorted(SUITES) + sorted(OWN_SUITES), default=DEFAULT_SUITES) parser.add_argument("--bench", help="regular expression matched against suite/name") + 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("--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) + parser.add_argument("--max-iterations", type=int, + help="run at most this many iterations per benchmark, for a quick check") parser.add_argument("--timeout", type=int, default=900, help="seconds per benchmark process") parser.add_argument("--output", help="directory for walltime-summary.json") parser.add_argument("--defer-failures", action="store_true", @@ -188,10 +248,19 @@ def main(): parser.error("--defer-failures needs --output") if args.min_iterations < 4: parser.error("--min-iterations must be at least 4: two samples are the minimum") + if args.max_iterations is not None and args.max_iterations < 4: + parser.error("--max-iterations must be at least 4: two samples are the minimum") - if os.path.exists(args.python): - # Each benchmark runs in its own directory. - args.python = os.path.abspath(args.python) + pythons = {} + for item in args.suite_python: + suite, _, path = item.partition("=") + if suite not in SUITES and suite not in OWN_SUITES or not path: + parser.error("--suite-python takes SUITE=PATH with a known suite: %s" % item) + pythons[suite] = path + # Each benchmark runs in its own directory. + 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)) if not selected: parser.error("no benchmark selected") @@ -201,6 +270,13 @@ def main(): 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 args.log_dir: + os.makedirs(args.log_dir, exist_ok=True) + if args.label: + print("configuration %s: interpreter options %s" % (args.label, " ".join(args.python_arg) or "none"), + flush=True) if not folder: print("CODSPEED_PROFILE_FOLDER is not set: nothing is reported to CodSpeed", flush=True) failed, measured, summary = [], 0, {} @@ -210,7 +286,10 @@ def main(): print("%-48s %10s %10s %7s skipped: %s" % (bench["id"], "-", "-", "-", SKIP[bench["id"]]), flush=True) continue started = time.monotonic() - status, durations, pid, tail = run_one(args.python, bench, args.min_iterations, args.timeout) + 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) if status != "ok": failed.append(bench["id"]) print("%-48s %10s %10s %7s FAILED: %s" % (bench["id"], "-", "-", "-", status), flush=True) @@ -219,14 +298,18 @@ def main(): stats = walltime_stats(durations) if folder: write_result(folder, bench, stats, pid) - summary[bench["uri"]] = stats + # 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) 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) if args.output: os.makedirs(args.output, exist_ok=True) with open(os.path.join(args.output, "walltime-summary.json"), "w") as f: - json.dump({"measured": summary, "failed": failed}, f, indent=1) + result = {"measured": summary, "failed": failed} + if args.label or args.python_arg: + result.update(label=args.label, python_args=args.python_arg) + json.dump(result, f, indent=1) print("%d measured, %d failed%s" % (measured, len(failed), ": " + ", ".join(failed) if failed else "")) if not measured: return 1 diff --git a/.github/elide/codspeed-diagnose b/.github/elide/codspeed-diagnose new file mode 100755 index 0000000000..980e36ff3b --- /dev/null +++ b/.github/elide/codspeed-diagnose @@ -0,0 +1,279 @@ +#!/usr/bin/env python3 +# Runs benchmarks once per interpreter option set of codspeed-diagnose.txt with codspeed-bench and +# relates every iteration's duration to the garbage collections in it. Used by the diagnose job of +# .github/workflows/elide-codspeed.yml; runs on CPython. Nothing is reported to CodSpeed. +# +# For each option set the output directory gets /walltime-summary.json (every iteration's +# duration and the peak RSS of each benchmark process) and /.log (the complete output +# of the process, with the GC log for sets that have --vm.XX:+PrintGC). diagnose-summary.json has the +# collections per iteration, diagnose.md the tables. +import argparse +import json +import math +import os +import re +import statistics +import subprocess +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +DRIVER = os.path.join(HERE, "codspeed-bench") +VARIANTS = os.path.join(HERE, "codspeed-diagnose.txt") +GC_LOG = "--vm.XX:+PrintGC" + +ITERATION = re.compile(r"### iteration=(\d+), name=\S+, duration=([\d.]+)") +# [0.160s] GC(1) Pause Full GC (java.lang.System.gc()) 66.17M->58.03M 42.525ms +GC = re.compile(r"\[([\d.]+)s\] GC\((\d+)\) Pause (Incremental|Full) GC \((.*?)\) ([\d.]+)M->([\d.]+)M ([\d.]+)ms") +BARRIER = re.compile(r"exceeding native_memory_gc_barrier \((\d+)\)") +ENLARGE = re.compile(r"enlarging native_memory_gc_barrier to (\d+)") +SYSTEM_GC = "java.lang.System.gc()" + + +def read_variants(path): + variants = {} + with open(path) as f: + for line in f: + fields = line.split("#", 1)[0].split() + if fields: + variants[fields[0]] = fields[1:] + return variants + + +def interpreter_args(options): + """Logged sets also run unbuffered, so that GC lines and iteration lines keep their order.""" + return (["-u"] if GC_LOG in options else []) + options + + +def environment(options): + env = dict(os.environ) + env.pop("GRAALPY_BENCH_REPORT_LIVE", None) + if GC_LOG in options: + env["GRAALPY_BENCH_REPORT_LIVE"] = "1" + return env + + +def preflight(python, variants, names): + """Starts the interpreter once per option set: an option this build does not know fails here.""" + failed = [] + for name in names: + cmd = [python] + interpreter_args(variants[name]) + ["-c", "import sys; print(sys.version)"] + try: + proc = subprocess.run(cmd, capture_output=True, text=True, timeout=180) + ok, out = proc.returncode == 0, proc.stdout + proc.stderr + except subprocess.TimeoutExpired: + ok, out = False, "timeout" + print("%-16s %s %s" % (name, "ok" if ok else "FAILED", out.strip().splitlines()[-1:] if out.strip() else ""), + flush=True) + if not ok: + print(out[-2000:], flush=True) + failed.append(name) + return failed + + +def parse_log(text): + """-> one dict per iteration line: the collections and native memory events since the previous one.""" + # What happens before the first iteration starts (imports, __setup__) is not counted. + start = text.find("### start benchmark") + text = text[start:] if start >= 0 else text + events = sorted([(m.start(), "it", m) for m in ITERATION.finditer(text)] + + [(m.start(), "gc", m) for m in GC.finditer(text)] + + [(m.start(), "barrier", m) for m in BARRIER.finditer(text)] + + [(m.start(), "enlarge", m) for m in ENLARGE.finditer(text)], key=lambda e: e[0]) + + def fresh(): + return {"incremental": 0, "incremental_ms": 0.0, "full_alloc": 0, "full_alloc_ms": 0.0, + "system_gc": 0, "system_gc_ms": 0.0, "barrier": 0, "enlarged_to": None, "heap_after_mb": None} + + iterations, current = [], fresh() + for _, kind, m in events: + if kind == "it": + current["iteration"] = int(m.group(1)) + iterations.append(current) + current = fresh() + elif kind == "gc": + pause = float(m.group(7)) + if m.group(3) == "Incremental": + current["incremental"] += 1 + current["incremental_ms"] += pause + elif m.group(4) == SYSTEM_GC: + current["system_gc"] += 1 + current["system_gc_ms"] += pause + else: + current["full_alloc"] += 1 + current["full_alloc_ms"] += pause + current["heap_after_mb"] = float(m.group(6)) + elif kind == "barrier": + current["barrier"] += 1 + else: + current["enlarged_to"] = int(m.group(1)) + for it in iterations: + it["pause_ms"] = it["incremental_ms"] + it["full_alloc_ms"] + it["system_gc_ms"] + return iterations + + +def quantile(values, p): + values = sorted(values) + position = p * (len(values) - 1) + low = int(position) + high = min(low + 1, len(values) - 1) + return values[low] + (position - low) * (values[high] - values[low]) + + +def five(values): + return {"median": quantile(values, .5), "q1": quantile(values, .25), "q3": quantile(values, .75), + "min": min(values), "max": max(values)} + + +def correlation(xs, ys): + if len(xs) < 3 or statistics.pstdev(xs) == 0 or statistics.pstdev(ys) == 0: + return None + mx, my = statistics.fmean(xs), statistics.fmean(ys) + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) + return cov / math.sqrt(sum((x - mx) ** 2 for x in xs) * sum((y - my) ** 2 for y in ys)) + + +def analyse(output, names, variants): + results = {} + for name in names: + path = os.path.join(output, name, "walltime-summary.json") + if not os.path.exists(path): + results[name] = {"error": "no walltime-summary.json"} + continue + summary = json.load(open(path)) + rows = {} + for uri, data in summary["measured"].items(): + ident = uri.split("::", 1)[1].split("[", 1)[0] + durations = data["durations_s"] + warmup = len(durations) // 2 + samples = durations[warmup:] + row = {"iterations": len(durations), "durations_s": durations, "samples": five(samples), + "max_rss_mb": data["max_rss_kb"] / 1024} + log = os.path.join(output, name, ident.replace("/", "__") + ".log") + if GC_LOG in variants[name] and os.path.exists(log): + gcs = parse_log(open(log, errors="replace").read()) + row["gc"] = gcs + if len(gcs) == len(durations): + s = gcs[warmup:] + pauses = [g["pause_ms"] / 1000 for g in s] + row["gc_samples"] = { + "system_gc_per_iteration": statistics.fmean(g["system_gc"] for g in s), + "system_gc_s_per_iteration": statistics.fmean(g["system_gc_ms"] for g in s) / 1000, + "full_alloc_per_iteration": statistics.fmean(g["full_alloc"] for g in s), + "pause_s_per_iteration": statistics.fmean(pauses), + "barrier_per_iteration": statistics.fmean(g["barrier"] for g in s), + "pause_share": sum(pauses) / sum(samples), + "corr_duration_pause": correlation(samples, pauses), + "corr_duration_system_gc": correlation(samples, [g["system_gc"] for g in s]), + "corr_duration_barrier": correlation(samples, [g["barrier"] for g in s]), + "without_pause": five([d - p for d, p in zip(samples, pauses)]), + } + else: + row["gc_error"] = "%d iteration lines in the log, %d durations" % (len(gcs), len(durations)) + rows[ident] = row + results[name] = {"options": variants[name], "rows": rows, "failed": summary["failed"]} + return results + + +def fmt(x, digits=2): + return "-" if x is None else "%.*f" % (digits, x) + + +def markdown(results, names): + lines = ["## Iteration durations (second half of the iterations), seconds", "", + "| Row | Option set | median | q1 | q3 | min | max | peak RSS MB |", "|---|---|---|---|---|---|---|---|"] + idents = sorted({i for n in names for i in results[n].get("rows", {})}) + for ident in idents: + for name in names: + row = results[name].get("rows", {}).get(ident) + if row is None: + failed = ident in results[name].get("failed", []) + lines.append("| %s | %s | %s | | | | | |" % (ident, name, "FAILED" if failed else "not run")) + continue + s = row["samples"] + lines.append("| %s | %s | %s | %s | %s | %s | %s | %.0f |" % ( + ident, name, fmt(s["median"]), fmt(s["q1"]), fmt(s["q3"]), fmt(s["min"]), fmt(s["max"]), row["max_rss_mb"])) + lines += ["", "## Collections per iteration (second half), logged option sets", "", + "System.gc: full collections forced by GraalPy (native memory limit, background task); full alloc: " + "full collections of the GC policy; limit: crossings of the native memory limit; corr: correlation of " + "the iteration's duration with its total GC pause; without pause: duration minus all GC pauses.", "", + "| Row | Option set | System.gc | System.gc s | full alloc | pause s | pause share | limit | corr | " + "without pause median | q1 | q3 | min | max |", "|---|---|---|---|---|---|---|---|---|---|---|---|---|---|"] + for ident in idents: + for name in names: + row = results[name].get("rows", {}).get(ident) + if not row or "gc_samples" not in row: + if row and "gc_error" in row: + lines.append("| %s | %s | %s |" % (ident, name, row["gc_error"])) + continue + g, w = row["gc_samples"], row["gc_samples"]["without_pause"] + lines.append("| %s | %s | %.1f | %s | %.1f | %s | %.0f%% | %.1f | %s | %s | %s | %s | %s | %s |" % ( + ident, name, g["system_gc_per_iteration"], fmt(g["system_gc_s_per_iteration"]), + g["full_alloc_per_iteration"], fmt(g["pause_s_per_iteration"]), 100 * g["pause_share"], + g["barrier_per_iteration"], fmt(g["corr_duration_pause"]), fmt(w["median"]), fmt(w["q1"]), + fmt(w["q3"]), fmt(w["min"]), fmt(w["max"]))) + lines += ["", "## Every iteration: duration s (System.gc collections, limit crossings, GC pause s)", ""] + for name in names: + for ident, row in sorted(results[name].get("rows", {}).items()): + if "gc" not in row or len(row["gc"]) != len(row["durations_s"]): + continue + cells = ["%.2f(%d,%d,%.2f)" % (d, g["system_gc"], g["barrier"], g["pause_ms"] / 1000) + for d, g in zip(row["durations_s"], row["gc"])] + lines.append("- %s, %s: %s" % (ident, name, " ".join(cells))) + return "\n".join(lines) + "\n" + + +def main(): + parser = argparse.ArgumentParser(description="Run benchmarks under several interpreter option sets.") + parser.add_argument("--python", required=True, help="interpreter (a virtual environment's python)") + parser.add_argument("--suite", default="packages") + parser.add_argument("--bench", required=True, help="regular expression matched against suite/name") + parser.add_argument("--variants", default="all", help="comma-separated names from codspeed-diagnose.txt") + parser.add_argument("--iterations", type=int, default=30) + parser.add_argument("--timeout", type=int, default=600, help="seconds per benchmark process") + parser.add_argument("--output", required=True) + parser.add_argument("--preflight", action="store_true", help="only start the interpreter with each option set") + parser.add_argument("--analyse-only", action="store_true", help="only analyse an existing output directory") + args = parser.parse_args() + if os.environ.get("CODSPEED_PROFILE_FOLDER"): + parser.error("not to be run under CodSpeed: nothing measured here may be reported") + + variants = read_variants(VARIANTS) + names = list(variants) if args.variants == "all" else [v.strip() for v in args.variants.split(",") if v.strip()] + unknown = [n for n in names if n not in variants] + if unknown: + parser.error("unknown option sets %s; known: %s" % (", ".join(unknown), ", ".join(variants))) + + if args.preflight: + failed = preflight(args.python, variants, names) + return 1 if failed else 0 + + os.makedirs(args.output, exist_ok=True) + if not args.analyse_only: + for name in names: + out = os.path.join(args.output, name) + cmd = [sys.executable, DRIVER, "--python", args.python, "--suite", args.suite, "--bench", args.bench, + "--min-iterations", str(args.iterations), "--max-iterations", str(args.iterations), + "--timeout", str(args.timeout), "--label", name, "--output", out, "--log-dir", out, + "--defer-failures"] + cmd += ["--python-arg=%s" % a for a in interpreter_args(variants[name])] + print("::group::%s" % name, flush=True) + status = subprocess.call(cmd, env=environment(variants[name])) + print("::endgroup::", flush=True) + print("%s: exit status %d" % (name, status), flush=True) + # Written after every option set, so that a cancelled job still leaves the tables so far. + results = analyse(args.output, names[:names.index(name) + 1], variants) + json.dump(results, open(os.path.join(args.output, "diagnose-summary.json"), "w"), indent=1) + results = analyse(args.output, names, variants) + json.dump(results, open(os.path.join(args.output, "diagnose-summary.json"), "w"), indent=1) + text = markdown(results, names) + with open(os.path.join(args.output, "diagnose.md"), "w") as f: + f.write(text) + print(text) + if os.environ.get("GITHUB_STEP_SUMMARY"): + with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as f: + f.write(text) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/elide/codspeed-diagnose.txt b/.github/elide/codspeed-diagnose.txt new file mode 100644 index 0000000000..b90f5e40d9 --- /dev/null +++ b/.github/elide/codspeed-diagnose.txt @@ -0,0 +1,20 @@ +# Interpreter option sets for codspeed-diagnose: one line per set, a name followed by the options +# given to the interpreter before the harness. Run in the order listed (or the order given with +# --variants). Nothing measured with these is reported to CodSpeed. +# +# A set with --vm.XX:+PrintGC also runs with -u and live iteration reports, so that every GC line in +# the output comes after the iteration lines that precede it in time; the GC lines between two +# iteration lines belong to the second iteration. The logger python.capi.PythonCextBuiltins at +# level CONFIG prints one line each time a native allocation crosses the native memory limit +# (--python.InitialNativeMemory), after which GraalPy forces up to seven full collections. +# "default" is run exactly as the benchmark job runs, without any of this. +# +# name options +gc-log --vm.XX:+PrintGC --log.python.capi.PythonCextBuiltins.level=CONFIG +no-explicit-gc --vm.XX:+DisableExplicitGC --vm.XX:+PrintGC --log.python.capi.PythonCextBuiltins.level=CONFIG +no-bg-task --experimental-options --python.BackgroundGCTask=false --vm.XX:+PrintGC --log.python.capi.PythonCextBuiltins.level=CONFIG +default +native-8g --experimental-options --python.BackgroundGCTask=false --python.InitialNativeMemory=8589934592 --vm.XX:+PrintGC --log.python.capi.PythonCextBuiltins.level=CONFIG +# The serial GC's default policy (Adaptive2) only takes a maximum young generation size; the policy +# BySpaceAndTime keeps the young generation at that size. Changes the policy and the size together. +young-1g --experimental-options --python.BackgroundGCTask=false --vm.XX:InitialCollectionPolicy=BySpaceAndTime --vm.Xmn1g --vm.XX:+PrintGC --log.python.capi.PythonCextBuiltins.level=CONFIG diff --git a/.github/elide/package-venv b/.github/elide/package-venv new file mode 100755 index 0000000000..39ea5ffc34 --- /dev/null +++ b/.github/elide/package-venv @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Creates a virtual environment of a GraalPy standalone and installs the packages of the suite +# "packages" into it from a folder of wheels, without a network. Used by +# .github/workflows/elide-codspeed.yml. +# +# usage: package-venv +set -euo pipefail + +graalpy=$1 venv=$2 wheels=$3 +requirements="$(dirname "$0")/../../graalpython/com.oracle.graal.python.benchmarks/python/packages/requirements.txt" + +"$graalpy" -m venv --clear "$venv" +ls -l "$venv/bin" +# pip is run as a module, and installed when the environment came without it. +if ! "$venv/bin/python" -m pip --version; then + echo "the virtual environment has no pip, installing it with ensurepip" + "$venv/bin/python" -m ensurepip --default-pip +fi +"$venv/bin/python" -m pip install --no-cache-dir --no-index --find-links "$wheels" -r "$requirements" +"$venv/bin/python" -c 'import lxml.etree, lxml.html, numpy, orjson, pandas, pydantic' diff --git a/.github/workflows/elide-codspeed.yml b/.github/workflows/elide-codspeed.yml index 05889e47c7..bc330c613d 100644 --- a/.github/workflows/elide-codspeed.yml +++ b/.github/workflows/elide-codspeed.yml @@ -1,21 +1,45 @@ name: CodSpeed benchmarks -# Steady-state wall time of the C API micro benchmarks and the pure Python meso benchmarks on a -# native standalone, reported to CodSpeed (https://app.codspeed.io/elide-dev/graalpython). +# 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). # # Wall time needs a dedicated machine, so the measurement runs on the self-hosted benchmark runner # linux-amd64-bench. The repository variable # CODSPEED_WALLTIME_RUNNER selects another label; the standalone is built for linux-amd64, so it -# must be an x86_64 runner. The benchmark host is shared between repositories, so the standalone is -# built on the CI pool and the host is used only for the measurement. +# must be an x86_64 runner. The benchmark host is shared between repositories, so the standalone and +# the packages' wheels are built on the CI pool and the host is used only for the measurement. # # Pull requests are measured only when labelled "perf:bench", and never from a fork: both the build # and the measurement run on self-hosted runners. +# +# A manual run with "diagnose" set reports nothing to CodSpeed: instead of the walltime job, the job +# diagnose runs the selected benchmarks once per interpreter option set of +# .github/elide/codspeed-diagnose.txt and keeps every iteration's duration, the GC log and the peak +# RSS as an artifact, for example +# gh workflow run elide-codspeed.yml --ref -f diagnose=true -f variants=gc-log,default on: push: branches: [develop, 'elide-*.x'] pull_request: types: [opened, synchronize, reopened, labeled] workflow_dispatch: + inputs: + diagnose: + description: Run the diagnose job instead of the measurement; nothing is reported to CodSpeed + type: boolean + default: false + bench: + description: 'diagnose: regular expression matched against suite/name' + type: string + default: '^packages/(pydantic-json|orjson-roundtrip|pandas-csv|pandas-str|pandas-groupby-merge|lxml-xpath)$' + variants: + description: 'diagnose: comma-separated option sets of .github/elide/codspeed-diagnose.txt, or all' + type: string + default: all + iterations: + description: 'diagnose: iterations per benchmark and option set' + type: string + default: '30' permissions: contents: read @@ -75,13 +99,145 @@ jobs: retention-days: 1 if-no-files-found: error + # The packages of the suite "packages" (graalpython/com.oracle.graal.python.benchmarks/python/packages) have no wheels for this + # interpreter. Their compiled ones are built from source with the standalone just built, with + # GraalPy's patches, and every wheel is collected into one artifact that the benchmark host + # installs from without a network. Nothing is cached: the wheels depend on the interpreter build. + wheels: + name: build package wheels + needs: build + runs-on: ${{ vars.CODSPEED_BUILD_RUNNER || 'linux-amd64-cipool' }} + timeout-minutes: 90 + env: + REQUIREMENTS: graalpython/com.oracle.graal.python.benchmarks/python/packages/requirements.txt + # pydantic-core and orjson are written in Rust; orjson needs at least 1.95. + RUST_VERSION: 1.100.0 + steps: + - name: Clean workspace + run: find "${GITHUB_WORKSPACE:?}" -mindepth 1 -maxdepth 1 -exec rm -rf {} + + + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0 # v5.0.0 + with: + name: codspeed-graalpy-native-standalone + path: ${{ runner.temp }} + + # Everything the build installs or caches stays in the job's temporary directory. + - name: Install Rust + run: | + { + echo "CARGO_HOME=$RUNNER_TEMP/cargo" + echo "RUSTUP_HOME=$RUNNER_TEMP/rustup" + echo "XDG_CACHE_HOME=$RUNNER_TEMP/cache" + } >> "$GITHUB_ENV" + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | + CARGO_HOME="$RUNNER_TEMP/cargo" RUSTUP_HOME="$RUNNER_TEMP/rustup" \ + sh -s -- -y --no-modify-path --profile minimal --default-toolchain "$RUST_VERSION" + echo "$RUNNER_TEMP/cargo/bin" >> "$GITHUB_PATH" + + - name: Build the wheels + env: + # Only PyPI. GraalPy's pip also looks for prebuilt wheels in GraalPy's own index otherwise. + PIP_INDEX_URL: https://pypi.org/simple + run: | + set -o pipefail + rustc --version + tar -C "$RUNNER_TEMP" -xf "$RUNNER_TEMP/graalpy-native-standalone.tar" + "$RUNNER_TEMP/GRAALPY_NATIVE_STANDALONE/bin/graalpy" -m venv "$RUNNER_TEMP/build-venv" + WHEELS="$RUNNER_TEMP/wheelhouse" + pin() { grep -E "^$1==" "$REQUIREMENTS"; } + # Builds every package even when one fails, so that one run shows all failures. + failed="" + build() { + local name=$1 start=$SECONDS status=0 + shift + echo "::group::$name" + "$RUNNER_TEMP/build-venv/bin/pip" wheel --no-cache-dir --no-deps -w "$WHEELS" "$@" || status=$? + echo "::endgroup::" + echo "$name: exit status $status after $((SECONDS - start)) s" + if [ "$status" -ne 0 ]; then failed="$failed $name"; fi + } + # Without an external BLAS and LAPACK (numpy's own fallback routines), so that the benchmark + # host needs no libraries for it. + build numpy --no-binary numpy -Csetup-args=-Dblas=none -Csetup-args=-Dlapack=none "$(pin numpy)" + # Against that numpy, not one compiled again in pandas' build environment. + pin numpy > "$RUNNER_TEMP/numpy-constraint.txt" + build pandas --no-binary pandas --find-links "$WHEELS" \ + --build-constraint "$RUNNER_TEMP/numpy-constraint.txt" "$(pin pandas)" + # libxml2 and libxslt linked in statically, so that the benchmark host needs no libraries for + # lxml. The versions and flags are the ones of lxml's own Linux wheels (without -flto); the + # libraries go into a shared object, so they need -fPIC. zlib.net serves only its latest + # release, so zlib comes from its release page; lxml checks the archive's hash. + export STATIC_DEPS=true ZLIB_VERSION=1.3.2 LIBICONV_VERSION=1.18 LIBXML2_VERSION=2.14.6 LIBXSLT_VERSION=1.1.43 + export CFLAGS="-O3 -g1 -pipe -fPIC" LDFLAGS="-fPIC" + export DOWNLOAD_DIR="$RUNNER_TEMP/lxml-libs" + mkdir -p "$DOWNLOAD_DIR" + curl -sSfL -o "$DOWNLOAD_DIR/zlib-$ZLIB_VERSION.tar.gz" \ + "https://github.com/madler/zlib/releases/download/v$ZLIB_VERSION/zlib-$ZLIB_VERSION.tar.gz" + build lxml --no-binary lxml "$(pin lxml)" + unset STATIC_DEPS ZLIB_VERSION LIBICONV_VERSION LIBXML2_VERSION LIBXSLT_VERSION DOWNLOAD_DIR CFLAGS LDFLAGS + build pydantic-core --no-binary pydantic-core "$(pin pydantic-core)" + build orjson --no-binary orjson "$(pin orjson)" + if [ -n "$failed" ]; then + ls -l "$WHEELS" + echo "::error::failed to build:$failed" + exit 1 + fi + # The pure Python packages. Only these: PyPI also has prebuilt wheels of some of the compiled + # ones for GraalPy, which pip would prefer to the ones built here. + grep -v -E '^(numpy|pandas|lxml|pydantic-core|orjson)==' "$REQUIREMENTS" > "$RUNNER_TEMP/pure.txt" + "$RUNNER_TEMP/build-venv/bin/pip" wheel --no-cache-dir --no-deps --only-binary :all: -w "$WHEELS" \ + -r "$RUNNER_TEMP/pure.txt" + ls -l "$WHEELS" + # One wheel per pinned package, so that the installation has no choice. + expected=$(grep -c -E '^[A-Za-z0-9_.-]+==' "$REQUIREMENTS") + found=$(find "$WHEELS" -name '*.whl' | wc -l) + if [ "$found" -ne "$expected" ]; then + echo "::error::$found wheels for $expected pinned packages" + exit 1 + fi + + # The pool and the benchmark host run the same system, but the host has only its base libraries. + - name: Check the libraries the wheels need + run: | + python3 - "$RUNNER_TEMP/wheelhouse" <<'EOF' + import os, re, subprocess, sys, tempfile, zipfile + system = {"libc.so.6", "libm.so.6", "libpthread.so.0", "libdl.so.2", "librt.so.1", "libutil.so.1", + "ld-linux-x86-64.so.2", "libstdc++.so.6", "libgcc_s.so.1"} + problems = [] + for wheel in sorted(f for f in os.listdir(sys.argv[1]) if f.endswith(".whl")): + with zipfile.ZipFile(os.path.join(sys.argv[1], wheel)) as z, tempfile.TemporaryDirectory() as tmp: + libs = [n for n in z.namelist() if re.search(r"\.so(\.\d+)*$", n)] + shipped = {os.path.basename(n) for n in libs} + needed = set() + for name in libs: + out = subprocess.run(["readelf", "-d", z.extract(name, tmp)], capture_output=True, text=True, + check=True).stdout + for lib in re.findall(r"\(NEEDED\)\s+Shared library: \[([^\]]+)\]", out): + needed.add(lib) + if lib not in system and lib not in shipped: + problems.append("%s: %s needs %s" % (wheel, name, lib)) + print("%s: %d libraries, need %s" % (wheel, len(libs), ", ".join(sorted(needed)) or "nothing")) + if problems: + sys.exit("\n".join(problems)) + EOF + + - uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0 + with: + name: codspeed-package-wheels + path: ${{ runner.temp }}/wheelhouse/*.whl + retention-days: 1 + if-no-files-found: error + # The C API benchmarks compile an extension when they start. Check that the standalone runs and - # that this works before the benchmark host is occupied. No timing is taken from this job. + # that this works, and that the packages install and their benchmarks give the right results, before + # the benchmark host is occupied. No timing is taken from this job. check: name: check standalone - needs: build + needs: [build, wheels] runs-on: ${{ vars.CODSPEED_BUILD_RUNNER || 'linux-amd64-cipool' }} - timeout-minutes: 30 + timeout-minutes: 45 steps: - name: Clean workspace run: find "${GITHUB_WORKSPACE:?}" -mindepth 1 -maxdepth 1 -exec rm -rf {} + @@ -93,6 +249,11 @@ jobs: name: codspeed-graalpy-native-standalone path: ${{ runner.temp }} + - uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0 # v5.0.0 + with: + name: codspeed-package-wheels + path: ${{ runner.temp }}/wheelhouse + - name: Run three C API benchmarks run: | tar -C "$RUNNER_TEMP" -xf "$RUNNER_TEMP/graalpy-native-standalone.tar" @@ -102,11 +263,30 @@ 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: every iteration checks its result. + - name: Run the package benchmarks briefly + run: | + .github/elide/package-venv "$RUNNER_TEMP/GRAALPY_NATIVE_STANDALONE/bin/graalpy" "$RUNNER_TEMP/venv" \ + "$RUNNER_TEMP/wheelhouse" + python3 .github/elide/codspeed-bench --python "$RUNNER_TEMP/venv/bin/python" --suite packages \ + --max-iterations 4 + + # So that an option this build does not know fails here and not on the benchmark host. + - name: Start the interpreter with each diagnose option set + if: ${{ inputs.diagnose }} + env: + VARIANTS: ${{ inputs.variants }} + BENCH: ${{ inputs.bench }} + run: | + python3 .github/elide/codspeed-diagnose --preflight --python "$RUNNER_TEMP/venv/bin/python" \ + --variants "$VARIANTS" --bench "$BENCH" --output "$RUNNER_TEMP/diagnose" + walltime: name: walltime - needs: [build, check] + if: ${{ !inputs.diagnose }} + needs: [build, wheels, check] runs-on: ${{ vars.CODSPEED_WALLTIME_RUNNER || 'linux-amd64-bench' }} - timeout-minutes: 90 + timeout-minutes: 120 permissions: contents: read id-token: write # CodSpeed OIDC @@ -120,6 +300,11 @@ jobs: name: codspeed-graalpy-native-standalone path: ${{ runner.temp }} + - uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0 # v5.0.0 + with: + name: codspeed-package-wheels + path: ${{ runner.temp }}/wheelhouse + - name: Unpack the standalone run: | uname -a; cat /etc/os-release; nproc @@ -127,6 +312,12 @@ jobs: cc --version "$RUNNER_TEMP/GRAALPY_NATIVE_STANDALONE/bin/graalpy" -c 'import sys; print(sys.version)' + # From the wheels built on the pool only, without a network. + - name: Install the packages + run: | + .github/elide/package-venv "$RUNNER_TEMP/GRAALPY_NATIVE_STANDALONE/bin/graalpy" "$RUNNER_TEMP/venv" \ + "$RUNNER_TEMP/wheelhouse" + - name: Measure # Action and runner versions already in use on this host. uses: CodSpeedHQ/action@b1f28b5eccf7cb5bfe6a2a89cb3053eb67f1150c # v5.8.0 @@ -140,7 +331,8 @@ jobs: run: >- python3 .github/elide/codspeed-bench --python "${{ runner.temp }}/GRAALPY_NATIVE_STANDALONE/bin/graalpy" - --suite micro-native meso + --suite-python packages="${{ runner.temp }}/venv/bin/python" + --suite micro-native meso packages --output "${{ env.BENCH_OUTPUT }}" --defer-failures @@ -163,3 +355,56 @@ jobs: path: ${{ env.BENCH_OUTPUT }}/*.json retention-days: 14 if-no-files-found: warn + + # Manual runs with "diagnose" set, see the top of the file. Same host and packages as walltime, no + # CodSpeed action and no token for it. + diagnose: + name: diagnose + if: ${{ inputs.diagnose }} + needs: [build, wheels, check] + runs-on: ${{ vars.CODSPEED_WALLTIME_RUNNER || 'linux-amd64-bench' }} + timeout-minutes: 100 + env: + DIAGNOSE_OUTPUT: ${{ github.workspace }}/diagnose-results + steps: + - name: Clean workspace + run: find "${GITHUB_WORKSPACE:?}" -mindepth 1 -maxdepth 1 -exec rm -rf {} + + + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0 # v5.0.0 + with: + name: codspeed-graalpy-native-standalone + path: ${{ runner.temp }} + + - uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0 # v5.0.0 + with: + name: codspeed-package-wheels + path: ${{ runner.temp }}/wheelhouse + + - name: Install the packages + run: | + uname -a; nproc; free -m + tar -C "$RUNNER_TEMP" -xf "$RUNNER_TEMP/graalpy-native-standalone.tar" + .github/elide/package-venv "$RUNNER_TEMP/GRAALPY_NATIVE_STANDALONE/bin/graalpy" "$RUNNER_TEMP/venv" \ + "$RUNNER_TEMP/wheelhouse" + + - name: Run the option sets + timeout-minutes: 90 + env: + VARIANTS: ${{ inputs.variants }} + BENCH: ${{ inputs.bench }} + ITERATIONS: ${{ inputs.iterations }} + run: | + python3 .github/elide/codspeed-diagnose --python "$RUNNER_TEMP/venv/bin/python" \ + --variants "$VARIANTS" --bench "$BENCH" --iterations "$ITERATIONS" --output "$DIAGNOSE_OUTPUT" + + # Also after a timeout: the summary is written after every option set. + - name: Keep the results + if: ${{ !cancelled() }} + uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0 + with: + name: codspeed-diagnose-${{ github.run_attempt }} + path: ${{ env.DIAGNOSE_OUTPUT }} + retention-days: 14 + if-no-files-found: warn diff --git a/graalpython/com.oracle.graal.python.benchmarks/python/packages/benchmarks.txt b/graalpython/com.oracle.graal.python.benchmarks/python/packages/benchmarks.txt new file mode 100644 index 0000000000..d795106661 --- /dev/null +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/benchmarks.txt @@ -0,0 +1,19 @@ +# The benchmarks of the suite "packages" of .github/elide/codspeed-bench: one line per benchmark file +# in this folder, followed by its harness arguments in the form of upstream's +# mx.graalpython/mx_graalpython_bench_param.py (-i iterations, then the workload arguments). +# +# The workload argument is part of the benchmark's name on CodSpeed and selects the expected result +# in the benchmark file (EXPECTED); a change of it starts a new history there. The iteration count is +# not part of the name. The first half of the iterations is warm-up. +# +# name harness arguments +pydantic-json -i 40 8000 +pydantic-models -i 40 10000 +orjson-roundtrip -i 40 2500 +pandas-csv -i 40 50000 +pandas-str -i 40 20000 +pandas-groupby-merge -i 40 150000 +pandas-apply -i 40 20000 +numpy-small-ops -i 40 600 +numpy-vectorized -i 40 4000000 +lxml-xpath -i 40 2500 diff --git a/graalpython/com.oracle.graal.python.benchmarks/python/packages/lxml-xpath.py b/graalpython/com.oracle.graal.python.benchmarks/python/packages/lxml-xpath.py new file mode 100644 index 0000000000..829e19b09c --- /dev/null +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/lxml-xpath.py @@ -0,0 +1,89 @@ +# lxml: parse of a namespaced XML document, XPath queries (attributes, sums, predicates, a compiled +# XPath with variables), iterfind with edits, serialization and parse of the result, and lxml.html +# parsing, link extraction and serialization of an HTML table. +# +# Run with harness.py by .github/elide/codspeed-bench, see .github/elide/README.md. The argument is +# the number of items in the XML document. One iteration does the work ROUNDS times on data of that +# size, so that less data is alive at a time. +import math +import random + +from lxml import etree, html + +# number of items -> result of one round +EXPECTED = { + 2500: (264, 307224.9399999998, 766, 2500, 418417, 2500, 1250, 60754, 16278, 114026), +} +ROUNDS = 4 +REL_TOL = 1e-9 + +NS = "urn:example:inventory" +XML_DOC = b"" +HTML_DOC = "" +_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 XML_DOC, HTML_DOC + r = random.Random(61) + root = etree.Element("{%s}inventory" % NS, nsmap={"inv": NS}) + for i in range(size): + item = etree.SubElement(root, "{%s}item" % NS, sku="S%05d" % i, cat=r.choice(["a", "b", "c", "d"])) + etree.SubElement(item, "{%s}name" % NS).text = "Item %d <&>" % i + etree.SubElement(item, "{%s}qty" % NS).text = str(r.randint(0, 500)) + etree.SubElement(item, "{%s}price" % NS).text = "%.2f" % r.uniform(1, 999) + if r.random() < 0.3: + etree.SubElement(item, "{%s}note" % NS).text = "fragile" + XML_DOC = etree.tostring(root, xml_declaration=True, encoding="utf-8") + rows = "".join('Product %d%d' % (i, i, r.randint(1, 99)) + for i in range(size // 2)) + HTML_DOC = ("T
%s
" + "

Text bold
tail

" % rows) + + +def one_round(size): + ns = {"i": NS} + root = etree.fromstring(XML_DOC) + low = root.xpath("//i:item[number(i:qty) < 50]/@sku", namespaces=ns) + total = root.xpath("sum(//i:item[@cat='a']/i:price)", namespaces=ns) + fragile = len(root.xpath("//i:item[i:note='fragile']", namespaces=ns)) + names_of = etree.XPath("i:item[@cat=$c]/i:name/text()", namespaces=ns) + names = sum(len(names_of(root, c=c)) for c in "abcd") + for item in root.iterfind("i:item", ns): + qty = item.find("i:qty", ns) + qty.text = str(int(qty.text) + 1) + out = etree.tostring(root, pretty_print=True) + count = int(etree.fromstring(out).xpath("count(//i:item)", namespaces=ns)) + doc = html.fromstring(HTML_DOC) + links = [a.get("href") for a in doc.xpath("//a")] + prices = sum(int(td.text_content()) for td in doc.xpath("//td[@class='p']")) + doc.make_links_absolute("https://shop.example/") + text = doc.text_content() + serialized = html.tostring(doc) + result = (len(low), float(total), fragile, names, len(out), count, len(links), prices, len(text), len(serialized)) + _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/numpy-small-ops.py b/graalpython/com.oracle.graal.python.benchmarks/python/packages/numpy-small-ops.py new file mode 100644 index 0000000000..9803fc4e96 --- /dev/null +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/numpy-small-ops.py @@ -0,0 +1,77 @@ +# numpy on many small arrays from a Python loop: a particle simulation with one 3-element array per +# particle (arithmetic, indexing, linalg.norm, dot, stack, mean, clip). The time goes into calls +# from Python into numpy, not into numpy's loops. +# +# Run with harness.py by .github/elide/codspeed-bench, see .github/elide/README.md. The argument is +# the number of particles. +import math +import os + +for _var in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"): + os.environ.setdefault(_var, "1") + +import numpy as np + +STEPS = 50 + +# number of particles -> result of one iteration +EXPECTED = { + 600: (143392.7880996725, 804), +} +REL_TOL = 1e-9 + +POS = VEL = 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=600): + global POS, VEL + rs = np.random.RandomState(1) + POS = [rs.rand(3) for _ in range(size)] + VEL = [rs.rand(3) - 0.5 for _ in range(size)] + + +def measure(size): + pos = [p.copy() for p in POS] + vel = [v.copy() for v in VEL] + g = np.array([0.0, 0.0, -9.81]) + dt = np.float64(0.01) + energy = 0.0 + bounces = 0 + for step in range(STEPS): + for i in range(len(pos)): + v = vel[i] + g * dt + p = pos[i] + v * dt + if p[2] < 0.0: + p[2] = -p[2] + v[2] = -v[2] * 0.9 + bounces += 1 + n = np.linalg.norm(v) + if n > 5.0: + v = v / n * 5.0 + pos[i] = p + vel[i] = v + energy += float(0.5 * np.dot(v, v) + 9.81 * p[2]) + center = np.mean(np.stack(pos[:16]), axis=0) + energy += float(np.clip(center, 0, 1).sum()) + float(np.maximum(np.float64(step), 1.0)) + result = (energy, bounces) + _check(size, result) + return result + + +def __benchmark__(size=600): + return measure(size) diff --git a/graalpython/com.oracle.graal.python.benchmarks/python/packages/numpy-vectorized.py b/graalpython/com.oracle.graal.python.benchmarks/python/packages/numpy-vectorized.py new file mode 100644 index 0000000000..051f78d47e --- /dev/null +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/numpy-vectorized.py @@ -0,0 +1,80 @@ +# numpy on large arrays: element-wise ufuncs, reductions, percentile, cumsum, sort, where, an FFT +# and a small linear solve. Almost all the time is spent in numpy's compiled loops, so this row +# shows the cost of the C API boundary when the calls are few and large. numpy is built without an +# external BLAS (see .github/elide/README.md), so the linear algebra stays small. +# +# Run with harness.py by .github/elide/codspeed-bench, see .github/elide/README.md. The argument is +# the length of the arrays. +import math +import os + +for _var in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"): + os.environ.setdefault(_var, "1") + +import numpy as np + +# length of the arrays -> result of one iteration +EXPECTED = { + 4000000: ( + 2830945.870096583, + 0.8959134376782963, + 2830945.8700965187, + 0.7495966193253321, + 0.6603638159207382, + 3667766, + 1.731254587881972, + 27298.11534598013, + 0.06671724290320782, + ), +} +# Vectorized math functions and linear algebra round differently on different CPUs. +REL_TOL = 1e-7 + +X = S = B = 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=4000000): + global X, S, B + rs = np.random.RandomState(2) + X = rs.rand(size) + m = rs.rand(120, 120) + S = m @ m.T + 120 * np.eye(120) + B = rs.rand(120, 4) + + +def measure(size): + y = np.exp(-X) * np.sin(3 * X) + np.sqrt(X) * np.log1p(X) + total = float(y.sum()) + p90 = float(np.percentile(y, 90)) + running = float(np.cumsum(y)[-1]) + ordered = np.sort(y) + kth = float(ordered[size // 3]) + above = float(np.where(y > 0.5, y, 0).mean()) + count = int(np.count_nonzero(y > 0.25)) + z = (X - X.mean()) / X.std() + spread = float(np.abs(z).max()) + spectrum = np.fft.rfft(X[:1 << (size.bit_length() - 2)]) + low = float(np.abs(spectrum[1:100]).sum()) + solved = float(np.linalg.solve(S, B).sum()) + result = (total, p90, running, kth, above, count, spread, low, solved) + _check(size, result) + return result + + +def __benchmark__(size=4000000): + return measure(size) diff --git a/graalpython/com.oracle.graal.python.benchmarks/python/packages/orjson-roundtrip.py b/graalpython/com.oracle.graal.python.benchmarks/python/packages/orjson-roundtrip.py new file mode 100644 index 0000000000..f159eb9e9d --- /dev/null +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/orjson-roundtrip.py @@ -0,0 +1,97 @@ +# orjson: dumps and loads of a nested document tree (dicts, lists, strings with non-ASCII text, +# floats, None), 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 on data of that +# size, so that less data is alive at a time. +import dataclasses +import math +import random + +import orjson + +# number of users -> result of one round +EXPECTED = { + 2500: (4290716, 10000, 1962336, 316515, 6334, 11078071.56), +} +ROUNDS = 4 +REL_TOL = 1e-9 + + +@dataclasses.dataclass +class Event: + t: int + kind: str + value: int + + +DOC = None +EVENTS = None +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 make_doc(n, seed): + r = random.Random(seed) + words = ["alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta", "Příliš", "žluťoučký", "日本"] + users = [] + for i in range(n): + users.append({ + "id": i, "uuid": "%032x" % r.getrandbits(128), "name": "%s %s" % (r.choice(words), r.choice(words)), + "active": r.random() < 0.7, "balance": round(r.uniform(-1000, 10000), 2), "score": r.random(), + "tags": [r.choice(words) for _ in range(r.randint(0, 5))], + "address": {"street": "%d Main St" % r.randint(1, 999), "city": r.choice(words), + "geo": [r.uniform(-90, 90), r.uniform(-180, 180)]}, + "events": [{"t": 1700000000 + r.randint(0, 10**7), "kind": r.choice(["click", "view", "buy"]), + "value": r.randint(0, 100)} + for _ in range(r.randint(0, 6))], + "note": None if i % 3 else "x" * r.randint(10, 80), + }) + return {"version": 3, "generated": "2024-05-06T07:08:09Z", "users": users} + + +def __setup__(size=2500): + global DOC, EVENTS, BLOB + DOC = make_doc(size, 11) + EVENTS = [Event(e["t"], e["kind"], e["value"]) for u in DOC["users"] for e in u["events"]] + BLOB = orjson.dumps(DOC) + + +def one_round(size): + dumped = 0 + loaded = 0 + for _ in range(4): + dumped += len(orjson.dumps(DOC)) + loaded += len(orjson.loads(BLOB)["users"]) + pretty = len(orjson.dumps(DOC, option=orjson.OPT_INDENT_2 | orjson.OPT_SORT_KEYS)) + events = len(orjson.dumps(EVENTS)) + doc = orjson.loads(BLOB) + tags = sum(len(u["tags"]) for u in doc["users"]) + balance = sum(u["balance"] for u in doc["users"]) + result = (dumped, loaded, pretty, events, 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/packages/pandas-apply.py b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-apply.py new file mode 100644 index 0000000000..c4bff359e4 --- /dev/null +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-apply.py @@ -0,0 +1,73 @@ +# pandas with Python functions per row or element: DataFrame.apply(axis=1), Series.apply and +# Series.map with lambdas, iterrows and itertuples. +# +# Run with harness.py by .github/elide/codspeed-bench, see .github/elide/README.md. The argument is +# the number of rows. +import math +import os + +for _var in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"): + os.environ.setdefault(_var, "1") + +import numpy as np +import pandas as pd + +# number of rows -> result of one iteration +EXPECTED = { + 20000: (2823021.5738181015, 9988.025200000064, 354795085.89, 88890, 3493, 1905), +} +REL_TOL = 1e-9 + +DF = 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 classify(row): + if row["age"] < 25: + return "young" if row["income"] < 30000 else "young-rich" + if row["score"] > 0.8: + return "vip" + return "regular" + + +def __setup__(size=20000): + global DF + rs = np.random.RandomState(5) + DF = pd.DataFrame({"age": rs.randint(18, 80, size), "income": rs.randint(10000, 150000, size), + "score": rs.rand(size).round(4), "name": ["user_%d" % i for i in range(size)]}) + + +def measure(size): + df = DF.copy() + df["cls"] = df.apply(classify, axis=1) + df["tax"] = df["income"].apply(lambda x: x * 0.15 if x < 50000 else x * 0.23) + df["nlen"] = df["name"].map(lambda s: len(s.split("_")[1])) + per_age = 0.0 + for _, row in df.iloc[:size // 3].iterrows(): + per_age += row["tax"] / (row["age"] + 1) + score = 0.0 + for t in df.itertuples(): + score += t.score + counts = df["cls"].value_counts() + result = (per_age, score, float(df["tax"].sum()), int(df["nlen"].sum()), int(counts["vip"]), + int(counts["young-rich"])) + _check(size, result) + return result + + +def __benchmark__(size=20000): + return measure(size) diff --git a/graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-csv.py b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-csv.py new file mode 100644 index 0000000000..eb6b4c8d6e --- /dev/null +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-csv.py @@ -0,0 +1,75 @@ +# pandas: read_csv of an in-memory CSV (type inference, a date column, usecols with a categorical +# dtype), a filter, to_csv of the result and a groupby on the categorical column. +# +# Run with harness.py by .github/elide/codspeed-bench, see .github/elide/README.md. The argument is +# the number of rows. One iteration does the work ROUNDS times on data of that size, so that less +# data is alive at a time. +import io +import math +import os + +for _var in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"): + os.environ.setdefault(_var, "1") + +import numpy as np +import pandas as pd + +# number of rows -> result of one round +EXPECTED = { + 50000: (772606, 24984228, 50000, 325941, 5013, 24947990.612, 4967281.144), +} +ROUNDS = 4 +REL_TOL = 1e-9 + +CSV = "" +_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=50000): + global CSV + rs = np.random.RandomState(4) + df = pd.DataFrame({ + "id": np.arange(size), + "ts": pd.Timestamp("2023-01-01") + pd.to_timedelta(rs.randint(0, 86400 * 365, size), unit="s"), + "city": rs.choice(["Prague", "Brno", "Ostrava", "Plzen", "Liberec"], size), + "amount": (rs.rand(size) * 1000).round(3), + "count": rs.randint(0, 1000, size), + "flag": rs.rand(size) < 0.3, + "comment": np.where(rs.rand(size) < 0.1, "", "ok"), + }) + CSV = df.to_csv(index=False) + + +def one_round(size): + df = pd.read_csv(io.StringIO(CSV), parse_dates=["ts"]) + df2 = pd.read_csv(io.StringIO(CSV), usecols=["id", "city", "amount"], dtype={"city": "category"}) + out = df[df["flag"]].to_csv(index=False, float_format="%.2f") + by_city = df2.groupby("city", observed=True)["amount"].sum() + result = (len(out), int(df["count"].sum()), len(df2), int(df["ts"].dt.month.sum()), + int(df["comment"].isna().sum()), float(by_city.sum()), float(by_city["Brno"])) + _check(size, result) + return result + + +def measure(size): + for _ in range(ROUNDS): + result = one_round(size) + return result + + +def __benchmark__(size=50000): + return measure(size) diff --git a/graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-groupby-merge.py b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-groupby-merge.py new file mode 100644 index 0000000000..692f6a33f6 --- /dev/null +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-groupby-merge.py @@ -0,0 +1,90 @@ +# pandas: merges of a fact table with two dimension tables, groupby with named aggregations, +# nlargest, pivot_table and a grouped rank. +# +# Run with harness.py by .github/elide/codspeed-bench, see .github/elide/README.md. The argument is +# the number of rows of the fact table. One iteration does the work ROUNDS times on data of that +# size, so that less data is alive at a time. +import math +import os + +for _var in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"): + os.environ.setdefault(_var, "1") + +import numpy as np +import pandas as pd + +# number of rows -> result of one round +EXPECTED = { + 150000: ( + 131355, + 32, + 32762568.990000002, + 3013.5156341057127, + 131355, + 579432.23, + 12418730.170000002, + 33582, + 444748.38, + ), +} +ROUNDS = 4 +REL_TOL = 1e-9 + +SALES = CUSTOMERS = PRODUCTS = 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=150000): + global SALES, CUSTOMERS, PRODUCTS + rs = np.random.RandomState(3) + SALES = pd.DataFrame({ + "order_id": np.arange(size), + "cust_id": rs.randint(0, 5000, size), + "prod_id": rs.randint(0, 800, size), + "qty": rs.randint(1, 10, size), + "price": rs.randint(1, 10000, size) / 100, + "day": rs.randint(0, 365, size), + }) + CUSTOMERS = pd.DataFrame({"cust_id": np.arange(5000), "region": rs.choice(["EU", "US", "APAC", "LATAM"], 5000), + "segment": rs.choice(["retail", "smb", "ent"], 5000)}) + PRODUCTS = pd.DataFrame({"prod_id": np.arange(700), "category": rs.choice(list("ABCDEFGH"), 700), + "cost": rs.randint(1, 6000, 700) / 100}) + + +def one_round(size): + df = SALES.merge(CUSTOMERS, on="cust_id", how="left").merge(PRODUCTS, on="prod_id", how="inner") + df["revenue"] = df["qty"] * df["price"] + df["margin"] = df["revenue"] - df["qty"] * df["cost"] + g = df.groupby(["region", "category"]).agg(rev=("revenue", "sum"), m=("margin", "mean"), n=("order_id", "count")) + top = df.groupby("cust_id")["revenue"].sum().nlargest(50) + pivot = df.pivot_table(index="segment", columns="category", values="margin", aggfunc="sum") + rank = df.groupby("region")["revenue"].rank(method="first") + monthly = df.assign(month=df["day"] // 30).groupby("month")["revenue"].sum() + result = (len(df), len(g), float(g["rev"].sum()), float(g["m"].sum()), int(g["n"].sum()), float(top.sum()), + float(pivot.values.sum()), int(rank.max()), float(monthly.iloc[-1])) + _check(size, result) + return result + + +def measure(size): + for _ in range(ROUNDS): + result = one_round(size) + return result + + +def __benchmark__(size=150000): + return measure(size) diff --git a/graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-str.py b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-str.py new file mode 100644 index 0000000000..82c9b29324 --- /dev/null +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-str.py @@ -0,0 +1,78 @@ +# pandas: text cleaning with the Series.str methods (strip, lower, contains, extract, split, +# replace, title, len, slice) and parsing of date strings with to_datetime. +# +# Run with harness.py by .github/elide/codspeed-bench, see .github/elide/README.md. The argument is +# the number of rows. One iteration does the work ROUNDS times on data of that size, so that less +# data is alive at a time. +import math +import os + +for _var in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"): + os.environ.setdefault(_var, "1") + +import numpy as np +import pandas as pd + +# number of rows -> result of one round +EXPECTED = { + 20000: (6620, 182185, 959289, 666674, 3262, 60018, 864, 24, 312836), +} +ROUNDS = 3 +REL_TOL = 1e-9 + +TEXT = None +DATES = 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=20000): + global TEXT, DATES + rs = np.random.RandomState(6) + first = rs.choice([" John", "jane ", "ALICE", "Bob", "Éva", "Zoë "], size) + domain = rs.choice(["example.com", "mail.cz", "corp.org"], size) + TEXT = pd.Series(["%s Doe <%s.%d@%s> #%d" % (f, f.strip().lower(), i, d, i % 97) + for i, (f, d) in enumerate(zip(first, domain))]) + base = pd.Timestamp("2022-01-01") + seconds = rs.randint(0, 86400 * 700, size) + DATES = pd.Series([(base + pd.Timedelta(seconds=int(s))).strftime("%Y-%m-%d %H:%M:%S") for s in seconds]) + + +def one_round(size): + s = TEXT.str.strip().str.lower() + corp = s.str.contains("corp.org", regex=False) + emails = s.str.extract(r"<([^>]+)>", expand=False) + user = emails.str.split("@").str[0] + tag = s.str.extract(r"#(\d+)$", expand=False).astype(int) + cleaned = s.str.replace(r"\s+", " ", regex=True).str.title() + d = pd.to_datetime(DATES, format="%Y-%m-%d %H:%M:%S") + by_month = d.dt.to_period("M").value_counts().sort_index() + days = pd.to_datetime(DATES.str.slice(0, 10)).dt.day + result = (int(corp.sum()), int(user.str.len().sum()), int(tag.sum()), int(cleaned.str.len().sum()), + int(cleaned.str.startswith("Éva").sum()), int(d.dt.dayofweek.sum()), int(by_month.iloc[0]), + len(by_month), int(days.sum())) + _check(size, result) + return result + + +def measure(size): + for _ in range(ROUNDS): + result = one_round(size) + return result + + +def __benchmark__(size=20000): + return measure(size) diff --git a/graalpython/com.oracle.graal.python.benchmarks/python/packages/pydantic-json.py b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pydantic-json.py new file mode 100644 index 0000000000..f1f1a96721 --- /dev/null +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pydantic-json.py @@ -0,0 +1,118 @@ +# pydantic: a JSON array of invoices (nested models, a discriminated union, constrained fields) is +# validated into models with validate_json and serialized back with dump_json, and part of it goes +# through model_dump_json and model_validate_json one model at a time. +# +# Run with harness.py by .github/elide/codspeed-bench, see .github/elide/README.md. The argument is +# the number of invoices. +import math +import random +from datetime import date +from typing import Annotated, Literal, Union + +from pydantic import BaseModel, Field, TypeAdapter + +# number of invoices -> result of one iteration +EXPECTED = { + 8000: (3626504, 35782, 2633, 1832408), +} +REL_TOL = 1e-9 + + +class Card(BaseModel): + kind: Literal["card"] + last4: str = Field(pattern=r"^\d{4}$") + brand: str + + +class Bank(BaseModel): + kind: Literal["bank"] + iban: str + bic: str + + +class Wallet(BaseModel): + kind: Literal["wallet"] + provider: str + token: str + + +Payment = Annotated[Union[Card, Bank, Wallet], Field(discriminator="kind")] + + +class Item(BaseModel): + sku: str + qty: int = Field(ge=1) + unit_price: float + tags: list[str] = [] + + +class Invoice(BaseModel): + id: int + customer: str + issued: date + paid: bool + payment: Payment + items: list[Item] + meta: dict[str, str] = {} + + +ADAPTER = TypeAdapter(list[Invoice]) +PAYLOAD = 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=8000): + global PAYLOAD + r = random.Random(7) + raw = [] + for i in range(size): + kind = r.choice(["card", "bank", "wallet"]) + if kind == "card": + payment = {"kind": "card", "last4": "%04d" % r.randint(0, 9999), "brand": r.choice(["visa", "mc"])} + elif kind == "bank": + payment = {"kind": "bank", "iban": "CZ%d" % r.randint(10**9, 10**10), "bic": "GIBACZPX"} + else: + payment = {"kind": "wallet", "provider": "pp", "token": "tok%d" % i} + raw.append({ + "id": i, "customer": "cust-%d" % r.randint(0, 99), + "issued": "2024-%02d-%02d" % (r.randint(1, 12), r.randint(1, 28)), + "paid": r.random() < 0.5, "payment": payment, + "items": [{"sku": "SKU%d" % r.randint(0, 999), "qty": r.randint(1, 5), + "unit_price": round(r.random() * 100, 2), + "tags": ["t%d" % r.randint(0, 9) for _ in range(2)]} + for _ in range(r.randint(1, 8))], + "meta": {"src": "web", "region": r.choice(["eu", "us"])}, + }) + PAYLOAD = ADAPTER.dump_json(ADAPTER.validate_python(raw)) + + +def measure(size): + invoices = ADAPTER.validate_json(PAYLOAD) + out = ADAPTER.dump_json(invoices) + items = sum(len(inv.items) for inv in invoices) + cards = sum(1 for inv in invoices if inv.payment.kind == "card") + single = 0 + for inv in invoices[:size // 2]: + text = inv.model_dump_json() + single += len(text) + len(Invoice.model_validate_json(text).items) + result = (len(out), items, cards, single) + _check(size, result) + return result + + +def __benchmark__(size=8000): + return measure(size) diff --git a/graalpython/com.oracle.graal.python.benchmarks/python/packages/pydantic-models.py b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pydantic-models.py new file mode 100644 index 0000000000..3fbbb9f42a --- /dev/null +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pydantic-models.py @@ -0,0 +1,103 @@ +# pydantic: users with nested models, a field validator and constrained fields are validated from +# Python dicts with model_validate and dumped with model_dump, and validated from JSON text with +# model_validate_json and dumped with model_dump_json. +# +# Run with harness.py by .github/elide/codspeed-bench, see .github/elide/README.md. The argument is +# the number of users. +import math +import random +from datetime import datetime +from typing import Optional + +from pydantic import BaseModel, Field, field_validator + +# number of users -> result of one iteration +EXPECTED = { + 10000: (64704, 574470.0, 2938636, 8571), +} +REL_TOL = 1e-9 + + +class Address(BaseModel): + street: str + city: str + zip: str = Field(pattern=r"^\d{5}$") + + +class OrderLine(BaseModel): + sku: str + qty: int = Field(gt=0) + price: float + + +class User(BaseModel): + id: int + name: str + email: str + created: datetime + tags: list[str] = [] + address: Optional[Address] = None + orders: list[OrderLine] = [] + + @field_validator("name") + @classmethod + def strip(cls, v): + return v.strip() + + +DICTS = [] +TEXTS = [] +_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=10000): + r = random.Random(3) + for i in range(size): + d = { + "id": i, "name": " user%d " % i, "email": "u%d@example.com" % i, + "created": "2024-%02d-%02dT03:04:05" % (r.randint(1, 12), r.randint(1, 28)), + "tags": ["t%d" % r.randint(0, 9) for _ in range(3)], + "address": {"street": "%d Main" % i, "city": r.choice(["Prague", "Brno"]), "zip": "%05d" % (10000 + i)}, + "orders": [{"sku": "S%d" % j, "qty": j + 1, "price": j * 2.5} for j in range(r.randint(1, 6))], + } + if i % 7 == 0: + del d["address"] + DICTS.append(d) + TEXTS.append(User.model_validate(d).model_dump_json()) + + +def measure(size): + orders = 0 + total = 0.0 + for d in DICTS: + u = User.model_validate(d) + dumped = u.model_dump() + orders += len(u.orders) + len(dumped["tags"]) + total += sum(o["qty"] * o["price"] for o in dumped["orders"]) + text_len = 0 + named = 0 + for text in TEXTS: + u = User.model_validate_json(text) + text_len += len(u.model_dump_json()) + named += u.name.startswith("user") and u.address is not None + result = (orders, total, text_len, named) + _check(size, result) + return result + + +def __benchmark__(size=10000): + return measure(size) diff --git a/graalpython/com.oracle.graal.python.benchmarks/python/packages/requirements.txt b/graalpython/com.oracle.graal.python.benchmarks/python/packages/requirements.txt new file mode 100644 index 0000000000..8bc1ec8091 --- /dev/null +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/requirements.txt @@ -0,0 +1,15 @@ +# Packages of the suite "packages" with all their dependencies, pinned. The workflow +# elide-codspeed.yml builds numpy, pandas, lxml, pydantic-core and orjson from source with the +# standalone it measures (GraalPy's pip applies its patches from +# graalpython/lib-graalpython/patches); the others are pure Python wheels from PyPI. +numpy==2.5.4 +pandas==3.1.1 +python-dateutil==4.0.0 +tzdata==2026.6 +pydantic==2.14.3 +pydantic-core==2.50.4 +annotated-types==0.8.0 +typing-extensions==4.16.0 +typing-inspection==0.4.5 +orjson==3.13.0 +lxml==6.1.3