From 645af6c0fab261d66dba478dc5122e7c3e1b8cf2 Mon Sep 17 00:00:00 2001 From: Ivo Horak Date: Fri, 27 Nov 2026 11:49:40 +0100 Subject: [PATCH 1/8] CodSpeed: benchmark real packages A new suite "packages" of codspeed-bench measures pydantic, orjson, pandas, numpy and lxml: ten benchmarks in the format of upstream's harness under .github/elide/benchmarks/packages, with their table and pinned requirements. Each iteration checks its result. The wheels are compiled on the pool with the standalone of the run (new job "wheels"): numpy without an external BLAS, pandas against it, lxml with libxml2 and libxslt linked in statically, pydantic-core and orjson with a Rust toolchain in the job's temporary directory. A check fails the job when a wheel needs a library the benchmark host may not have. "check" installs the wheels offline and runs every package benchmark briefly; "walltime" installs them into a virtual environment and runs the suite with it (--suite-python), in the same CodSpeed upload. --- .github/elide/README.md | 68 +++++++- .../elide/benchmarks/packages/benchmarks.txt | 19 +++ .github/elide/benchmarks/packages/lxml-xpath | 77 +++++++++ .../elide/benchmarks/packages/numpy-small-ops | 73 ++++++++ .../benchmarks/packages/numpy-vectorized | 76 +++++++++ .../benchmarks/packages/orjson-roundtrip | 85 ++++++++++ .../elide/benchmarks/packages/pandas-apply | 69 ++++++++ .github/elide/benchmarks/packages/pandas-csv | 63 +++++++ .../benchmarks/packages/pandas-groupby-merge | 78 +++++++++ .github/elide/benchmarks/packages/pandas-str | 66 ++++++++ .../elide/benchmarks/packages/pydantic-json | 114 +++++++++++++ .../elide/benchmarks/packages/pydantic-models | 99 +++++++++++ .../benchmarks/packages/requirements.txt | 15 ++ .github/elide/codspeed-bench | 69 ++++++-- .github/workflows/elide-codspeed.yml | 158 ++++++++++++++++-- 15 files changed, 1101 insertions(+), 28 deletions(-) create mode 100644 .github/elide/benchmarks/packages/benchmarks.txt create mode 100644 .github/elide/benchmarks/packages/lxml-xpath create mode 100644 .github/elide/benchmarks/packages/numpy-small-ops create mode 100644 .github/elide/benchmarks/packages/numpy-vectorized create mode 100644 .github/elide/benchmarks/packages/orjson-roundtrip create mode 100644 .github/elide/benchmarks/packages/pandas-apply create mode 100644 .github/elide/benchmarks/packages/pandas-csv create mode 100644 .github/elide/benchmarks/packages/pandas-groupby-merge create mode 100644 .github/elide/benchmarks/packages/pandas-str create mode 100644 .github/elide/benchmarks/packages/pydantic-json create mode 100644 .github/elide/benchmarks/packages/pydantic-models create mode 100644 .github/elide/benchmarks/packages/requirements.txt diff --git a/.github/elide/README.md b/.github/elide/README.md index 1675e8d873..40b2702570 100644 --- a/.github/elide/README.md +++ b/.github/elide/README.md @@ -42,14 +42,72 @@ 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 in `benchmarks/packages`, not in upstream's benchmark folders: + +| 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`: `__setup__(size)` builds the input from a +fixed seed and is not measured, `__benchmark__(size)` is one measured iteration. Every iteration +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. `benchmarks.txt` lists the benchmarks with their harness arguments (iterations and size). +The size is part of the name on CodSpeed. The files are Python without the `.py` extension, like the +scripts in this folder (see below); the harness loads a benchmark by its path. + +To add a benchmark: + +1. Write the file in `benchmarks/packages` and add a line to `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 (30 for the current ones). +2. Run it with CPython, for example + `python3 graalpython/com.oracle.graal.python.benchmarks/python/harness.py .github/elide/benchmarks/packages/ -i 4 ` + in a virtual environment with `benchmarks/packages/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 `benchmarks/packages/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 `benchmarks/packages/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 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`). ## Runners @@ -70,7 +128,7 @@ forks. Such a pull request gets no tests until its branch is pushed to this repo Upstream's style job, which this CI does not run but upstream does, requires an Oracle copyright header in every `.py`, `.sh`, `.java`, `.c` and `.h` file of the repository. The exceptions are listed in an upstream file, which the fork does not edit. The scripts in this folder are therefore Python files without the `.py` extension; run them -with `python3 `. +with `python3 `. The same holds for the benchmark files in `benchmarks`. ## Upstream workflows that are switched off diff --git a/.github/elide/benchmarks/packages/benchmarks.txt b/.github/elide/benchmarks/packages/benchmarks.txt new file mode 100644 index 0000000000..4dd3982fe5 --- /dev/null +++ b/.github/elide/benchmarks/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 30 8000 +pydantic-models -i 30 10000 +orjson-roundtrip -i 30 10000 +pandas-csv -i 30 200000 +pandas-str -i 30 60000 +pandas-groupby-merge -i 30 600000 +pandas-apply -i 30 20000 +numpy-small-ops -i 30 600 +numpy-vectorized -i 30 4000000 +lxml-xpath -i 30 10000 diff --git a/.github/elide/benchmarks/packages/lxml-xpath b/.github/elide/benchmarks/packages/lxml-xpath new file mode 100644 index 0000000000..902d753b22 --- /dev/null +++ b/.github/elide/benchmarks/packages/lxml-xpath @@ -0,0 +1,77 @@ +# 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. +# +# Loaded by upstream's harness.py (see .github/elide/README.md). The argument is the number of +# items in the XML document. +import math +import random + +from lxml import etree, html + +# number of items -> result of one iteration +EXPECTED = { + 10000: (1013, 1263194.7300000004, 3109, 10000, 1678301, 10000, 5000, 249656, 68457, 462455), +} +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): + 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 __benchmark__(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 diff --git a/.github/elide/benchmarks/packages/numpy-small-ops b/.github/elide/benchmarks/packages/numpy-small-ops new file mode 100644 index 0000000000..a151c52a02 --- /dev/null +++ b/.github/elide/benchmarks/packages/numpy-small-ops @@ -0,0 +1,73 @@ +# 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. +# +# Loaded by upstream's harness.py (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): + 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 __benchmark__(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 diff --git a/.github/elide/benchmarks/packages/numpy-vectorized b/.github/elide/benchmarks/packages/numpy-vectorized new file mode 100644 index 0000000000..b612a249e5 --- /dev/null +++ b/.github/elide/benchmarks/packages/numpy-vectorized @@ -0,0 +1,76 @@ +# 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. +# +# Loaded by upstream's harness.py (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): + 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 __benchmark__(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 diff --git a/.github/elide/benchmarks/packages/orjson-roundtrip b/.github/elide/benchmarks/packages/orjson-roundtrip new file mode 100644 index 0000000000..607229fc73 --- /dev/null +++ b/.github/elide/benchmarks/packages/orjson-roundtrip @@ -0,0 +1,85 @@ +# 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. +# +# Loaded by upstream's harness.py (see .github/elide/README.md). The argument is the number of +# users in the document. +import dataclasses +import math +import random + +import orjson + +# number of users -> result of one iteration +EXPECTED = { + 10000: (17173340, 40000, 7853271, 1268050, 25294, 44980320.98), +} +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): + 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 __benchmark__(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 diff --git a/.github/elide/benchmarks/packages/pandas-apply b/.github/elide/benchmarks/packages/pandas-apply new file mode 100644 index 0000000000..c9def93dad --- /dev/null +++ b/.github/elide/benchmarks/packages/pandas-apply @@ -0,0 +1,69 @@ +# pandas with Python functions per row or element: DataFrame.apply(axis=1), Series.apply and +# Series.map with lambdas, iterrows and itertuples. +# +# Loaded by upstream's harness.py (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): + 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 __benchmark__(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 diff --git a/.github/elide/benchmarks/packages/pandas-csv b/.github/elide/benchmarks/packages/pandas-csv new file mode 100644 index 0000000000..a6cc520b75 --- /dev/null +++ b/.github/elide/benchmarks/packages/pandas-csv @@ -0,0 +1,63 @@ +# 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. +# +# Loaded by upstream's harness.py (see .github/elide/README.md). The argument is the number of +# rows. +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 iteration +EXPECTED = { + 200000: (3120180, 99878260, 200000, 1305855, 20054, 100052818.382, 20024794.616), +} +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): + 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 __benchmark__(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 diff --git a/.github/elide/benchmarks/packages/pandas-groupby-merge b/.github/elide/benchmarks/packages/pandas-groupby-merge new file mode 100644 index 0000000000..0091432f45 --- /dev/null +++ b/.github/elide/benchmarks/packages/pandas-groupby-merge @@ -0,0 +1,78 @@ +# pandas: merges of a fact table with two dimension tables, groupby with named aggregations, +# nlargest, pivot_table and a grouped rank. +# +# Loaded by upstream's harness.py (see .github/elide/README.md). The argument is the number of +# rows of the fact table. +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 = { + 600000: ( + 524828, + 32, + 130964960.46000001, + 3217.1785678239376, + 524828, + 1750154.6600000001, + 52768190.0, + 136105, + 1762282.68, + ), +} +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): + 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 __benchmark__(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 diff --git a/.github/elide/benchmarks/packages/pandas-str b/.github/elide/benchmarks/packages/pandas-str new file mode 100644 index 0000000000..a886e1f975 --- /dev/null +++ b/.github/elide/benchmarks/packages/pandas-str @@ -0,0 +1,66 @@ +# 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. +# +# Loaded by upstream's harness.py (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 = { + 60000: (20146, 569021, 2878839, 2022984, 9922, 180777, 2620, 24, 938675), +} +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): + 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 __benchmark__(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 diff --git a/.github/elide/benchmarks/packages/pydantic-json b/.github/elide/benchmarks/packages/pydantic-json new file mode 100644 index 0000000000..e13d45d77b --- /dev/null +++ b/.github/elide/benchmarks/packages/pydantic-json @@ -0,0 +1,114 @@ +# 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. +# +# Loaded by upstream's harness.py (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): + 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 __benchmark__(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 diff --git a/.github/elide/benchmarks/packages/pydantic-models b/.github/elide/benchmarks/packages/pydantic-models new file mode 100644 index 0000000000..202b6812b8 --- /dev/null +++ b/.github/elide/benchmarks/packages/pydantic-models @@ -0,0 +1,99 @@ +# 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. +# +# Loaded by upstream's harness.py (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): + 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 __benchmark__(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 diff --git a/.github/elide/benchmarks/packages/requirements.txt b/.github/elide/benchmarks/packages/requirements.txt new file mode 100644 index 0000000000..8bc1ec8091 --- /dev/null +++ b/.github/elide/benchmarks/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 diff --git a/.github/elide/codspeed-bench b/.github/elide/codspeed-bench index 4128568034..4a59075a56 100755 --- a/.github/elide/codspeed-bench +++ b/.github/elide/codspeed-bench @@ -1,6 +1,7 @@ #!/usr/bin/env python3 -# Runs benchmarks from graalpython/com.oracle.graal.python.benchmarks with the upstream harness and -# reports steady-state wall time to CodSpeed. Used by .github/workflows/elide-codspeed.yml; runs on CPython. +# Runs benchmarks from graalpython/com.oracle.graal.python.benchmarks, and the fork's own benchmarks +# from .github/elide/benchmarks, with the upstream harness and reports steady-state wall time to +# CodSpeed. Used by .github/workflows/elide-codspeed.yml; runs on CPython. # # Every benchmark runs in its own process of the interpreter under test. The harness prints one # duration per iteration; the first half of the iterations is warm-up and the second half are the @@ -26,12 +27,21 @@ BENCH_REL = "graalpython/com.oracle.graal.python.benchmarks/python" HARNESS = os.path.join(REPO, BENCH_REL, "harness.py") PARAMS = os.path.join(REPO, "mx.graalpython", "mx_graalpython_bench_param.py") +OWN_BENCH_REL = ".github/elide/benchmarks" + # suite name -> (table in mx_graalpython_bench_param.py, directory under BENCH_REL) SUITES = { "micro-native": ("MICRO_NATIVE_BENCHMARKS", "micro"), "meso": ("MESO_BENCHMARKS", "meso"), "micro": ("MICRO_BENCHMARKS", "micro"), } +# The fork's suites: suite name -> directory under OWN_BENCH_REL. It holds the benchmark files (Python +# without the .py extension; the harness loads them by path) and their 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 +74,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, OWN_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,18 +108,23 @@ 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 = "%s/%s" % (OWN_BENCH_REL, OWN_SUITES[suite]) + table, extension = load_own_table(OWN_SUITES[suite]), "" + else: + directory = "%s/%s" % (BENCH_REL, SUITES[suite][1]) + table, extension = load_table(SUITES[suite][0]), ".py" + for name, harness_args in table.items(): 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" % (directory, name, extension) # 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,9 +152,11 @@ def walltime_stats(durations_s): } -def run_one(python, bench, min_iterations, timeout): +def run_one(python, bench, min_iterations, max_iterations, timeout): """-> (status, durations in seconds, pid, output tail)""" iterations = max(bench["iterations"], min_iterations) + if max_iterations: + iterations = min(iterations, max_iterations) cmd = [python, 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"} @@ -174,9 +202,14 @@ 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("--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 +221,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") @@ -210,7 +252,8 @@ 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) + status, durations, pid, tail = run_one(pythons.get(bench["suite"], args.python), bench, args.min_iterations, + args.max_iterations, args.timeout) if status != "ok": failed.append(bench["id"]) print("%-48s %10s %10s %7s FAILED: %s" % (bench["id"], "-", "-", "-", status), flush=True) diff --git a/.github/workflows/elide-codspeed.yml b/.github/workflows/elide-codspeed.yml index 05889e47c7..baca9fdf9e 100644 --- a/.github/workflows/elide-codspeed.yml +++ b/.github/workflows/elide-codspeed.yml @@ -1,12 +1,13 @@ 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. @@ -75,13 +76,122 @@ jobs: retention-days: 1 if-no-files-found: error + # The packages of the suite "packages" (.github/elide/benchmarks/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: .github/elide/benchmarks/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"; } + build() { + local name=$1 start=$SECONDS + shift + echo "::group::$name" + "$RUNNER_TEMP/build-venv/bin/pip" wheel --no-cache-dir --no-deps -w "$WHEELS" "$@" + echo "::endgroup::" + echo "$name built in $((SECONDS - start)) s" + } + # 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 are the ones of lxml's own Linux wheels. + ( + export STATIC_DEPS=true ZLIB_VERSION=1.3.2 LIBICONV_VERSION=1.18 LIBXML2_VERSION=2.14.6 LIBXSLT_VERSION=1.1.43 + build lxml --no-binary lxml "$(pin lxml)" + ) + build pydantic-core --no-binary pydantic-core "$(pin pydantic-core)" + build orjson --no-binary orjson "$(pin orjson)" + # The pure Python packages. The compiled ones are taken from the wheelhouse. + "$RUNNER_TEMP/build-venv/bin/pip" wheel --no-cache-dir --only-binary :all: -w "$WHEELS" \ + --find-links "$WHEELS" -r "$REQUIREMENTS" + ls -l "$WHEELS" + + # 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 +203,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 +217,21 @@ 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: | + "$RUNNER_TEMP/GRAALPY_NATIVE_STANDALONE/bin/graalpy" -m venv "$RUNNER_TEMP/venv" + "$RUNNER_TEMP/venv/bin/pip" install --no-cache-dir --no-index --find-links "$RUNNER_TEMP/wheelhouse" \ + -r .github/elide/benchmarks/packages/requirements.txt + "$RUNNER_TEMP/venv/bin/python" -c 'import lxml.etree, lxml.html, numpy, orjson, pandas, pydantic' + python3 .github/elide/codspeed-bench --python "$RUNNER_TEMP/venv/bin/python" --suite packages \ + --max-iterations 4 + walltime: name: walltime - needs: [build, check] + 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 +245,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 +257,13 @@ 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: | + "$RUNNER_TEMP/GRAALPY_NATIVE_STANDALONE/bin/graalpy" -m venv "$RUNNER_TEMP/venv" + "$RUNNER_TEMP/venv/bin/pip" install --no-cache-dir --no-index --find-links "$RUNNER_TEMP/wheelhouse" \ + -r .github/elide/benchmarks/packages/requirements.txt + - name: Measure # Action and runner versions already in use on this host. uses: CodSpeedHQ/action@b1f28b5eccf7cb5bfe6a2a89cb3053eb67f1150c # v5.8.0 @@ -140,7 +277,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 From 486dfb834e594e26d61a4e74a6023f1459669116 Mon Sep 17 00:00:00 2001 From: Ivo Horak Date: Fri, 27 Nov 2026 12:07:29 +0100 Subject: [PATCH 2/8] CodSpeed packages: download zlib for lxml from its release page zlib.net serves only its latest release, so lxml's static build could not download zlib 1.3.2. Build every package even when one fails, so that one run shows all failures. --- .github/workflows/elide-codspeed.yml | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/.github/workflows/elide-codspeed.yml b/.github/workflows/elide-codspeed.yml index baca9fdf9e..159322c0fa 100644 --- a/.github/workflows/elide-codspeed.yml +++ b/.github/workflows/elide-codspeed.yml @@ -124,13 +124,16 @@ jobs: "$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 + 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" "$@" + "$RUNNER_TEMP/build-venv/bin/pip" wheel --no-cache-dir --no-deps -w "$WHEELS" "$@" || status=$? echo "::endgroup::" - echo "$name built in $((SECONDS - start)) s" + 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. @@ -140,13 +143,22 @@ jobs: 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 are the ones of lxml's own Linux wheels. - ( - export STATIC_DEPS=true ZLIB_VERSION=1.3.2 LIBICONV_VERSION=1.18 LIBXML2_VERSION=2.14.6 LIBXSLT_VERSION=1.1.43 - build lxml --no-binary lxml "$(pin lxml)" - ) + # lxml. The versions are the ones of lxml's own Linux wheels. 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 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 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. The compiled ones are taken from the wheelhouse. "$RUNNER_TEMP/build-venv/bin/pip" wheel --no-cache-dir --only-binary :all: -w "$WHEELS" \ --find-links "$WHEELS" -r "$REQUIREMENTS" From 136504f40494c785b56e4a90d26e7c8dfff81042 Mon Sep 17 00:00:00 2001 From: Ivo Horak Date: Fri, 27 Nov 2026 12:20:21 +0100 Subject: [PATCH 3/8] CodSpeed packages: move the benchmarks next to GraalPy's others The package benchmarks are now .py files in the new folder graalpython/com.oracle.graal.python.benchmarks/python/packages, in the form of the neighbouring meso and micro benchmarks (measure, defaults on __setup__ and __benchmark__), with their table and requirements. Upstream has no such folder, so merges cannot conflict with it, and no upstream file is edited. The CodSpeed names change accordingly. --- .github/elide/README.md | 41 ++++++++++++------- .github/elide/codspeed-bench | 21 ++++------ .github/workflows/elide-codspeed.yml | 8 ++-- .../python}/packages/benchmarks.txt | 0 .../python/packages/lxml-xpath.py | 12 ++++-- .../python/packages/numpy-small-ops.py | 12 ++++-- .../python/packages/numpy-vectorized.py | 12 ++++-- .../python/packages/orjson-roundtrip.py | 12 ++++-- .../python/packages/pandas-apply.py | 12 ++++-- .../python/packages/pandas-csv.py | 12 ++++-- .../python/packages/pandas-groupby-merge.py | 12 ++++-- .../python/packages/pandas-str.py | 12 ++++-- .../python/packages/pydantic-json.py | 12 ++++-- .../python/packages/pydantic-models.py | 12 ++++-- .../python}/packages/requirements.txt | 0 15 files changed, 118 insertions(+), 72 deletions(-) rename {.github/elide/benchmarks => graalpython/com.oracle.graal.python.benchmarks/python}/packages/benchmarks.txt (100%) rename .github/elide/benchmarks/packages/lxml-xpath => graalpython/com.oracle.graal.python.benchmarks/python/packages/lxml-xpath.py (93%) rename .github/elide/benchmarks/packages/numpy-small-ops => graalpython/com.oracle.graal.python.benchmarks/python/packages/numpy-small-ops.py (90%) rename .github/elide/benchmarks/packages/numpy-vectorized => graalpython/com.oracle.graal.python.benchmarks/python/packages/numpy-vectorized.py (91%) rename .github/elide/benchmarks/packages/orjson-roundtrip => graalpython/com.oracle.graal.python.benchmarks/python/packages/orjson-roundtrip.py (92%) rename .github/elide/benchmarks/packages/pandas-apply => graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-apply.py (90%) rename .github/elide/benchmarks/packages/pandas-csv => graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-csv.py (90%) rename .github/elide/benchmarks/packages/pandas-groupby-merge => graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-groupby-merge.py (92%) rename .github/elide/benchmarks/packages/pandas-str => graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-str.py (91%) rename .github/elide/benchmarks/packages/pydantic-json => graalpython/com.oracle.graal.python.benchmarks/python/packages/pydantic-json.py (93%) rename .github/elide/benchmarks/packages/pydantic-models => graalpython/com.oracle.graal.python.benchmarks/python/packages/pydantic-models.py (92%) rename {.github/elide/benchmarks => graalpython/com.oracle.graal.python.benchmarks/python}/packages/requirements.txt (100%) diff --git a/.github/elide/README.md b/.github/elide/README.md index 40b2702570..6efde0a205 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. @@ -55,7 +56,9 @@ the measurement runs there. ### Package benchmarks The suite `packages` of `codspeed-bench` measures pydantic, orjson, pandas, numpy and lxml. Its -files are in `benchmarks/packages`, not in upstream's benchmark folders: +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 | |---|---| @@ -70,30 +73,38 @@ files are in `benchmarks/packages`, not in upstream's benchmark folders: | `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`: `__setup__(size)` builds the input from a -fixed seed and is not measured, `__benchmark__(size)` is one measured iteration. Every iteration -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. `benchmarks.txt` lists the benchmarks with their harness arguments (iterations and size). -The size is part of the name on CodSpeed. The files are Python without the `.py` extension, like the -scripts in this folder (see below); the harness loads a benchmark by its path. +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)`. Every iteration 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, because the benchmark host has no network access to PyPI. + +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 the file in `benchmarks/packages` and add a line to `benchmarks.txt`. Size it so that an +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 (30 for the current ones). 2. Run it with CPython, for example - `python3 graalpython/com.oracle.graal.python.benchmarks/python/harness.py .github/elide/benchmarks/packages/ -i 4 ` - in a virtual environment with `benchmarks/packages/requirements.txt` installed. For a size + `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 `benchmarks/packages/requirements.txt` with all its dependencies pinned. +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 `benchmarks/packages/requirements.txt`. The compiled packages are built +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. @@ -128,7 +139,7 @@ forks. Such a pull request gets no tests until its branch is pushed to this repo Upstream's style job, which this CI does not run but upstream does, requires an Oracle copyright header in every `.py`, `.sh`, `.java`, `.c` and `.h` file of the repository. The exceptions are listed in an upstream file, which the fork does not edit. The scripts in this folder are therefore Python files without the `.py` extension; run them -with `python3 `. The same holds for the benchmark files in `benchmarks`. +with `python3 `. ## Upstream workflows that are switched off diff --git a/.github/elide/codspeed-bench b/.github/elide/codspeed-bench index 4a59075a56..d09ec5b83b 100755 --- a/.github/elide/codspeed-bench +++ b/.github/elide/codspeed-bench @@ -1,7 +1,6 @@ #!/usr/bin/env python3 -# Runs benchmarks from graalpython/com.oracle.graal.python.benchmarks, and the fork's own benchmarks -# from .github/elide/benchmarks, with the upstream harness and reports steady-state wall time to -# CodSpeed. Used by .github/workflows/elide-codspeed.yml; runs on CPython. +# Runs benchmarks from graalpython/com.oracle.graal.python.benchmarks with the upstream harness and +# reports steady-state wall time to CodSpeed. Used by .github/workflows/elide-codspeed.yml; runs on CPython. # # Every benchmark runs in its own process of the interpreter under test. The harness prints one # duration per iteration; the first half of the iterations is warm-up and the second half are the @@ -27,16 +26,14 @@ BENCH_REL = "graalpython/com.oracle.graal.python.benchmarks/python" HARNESS = os.path.join(REPO, BENCH_REL, "harness.py") PARAMS = os.path.join(REPO, "mx.graalpython", "mx_graalpython_bench_param.py") -OWN_BENCH_REL = ".github/elide/benchmarks" - # suite name -> (table in mx_graalpython_bench_param.py, directory under BENCH_REL) SUITES = { "micro-native": ("MICRO_NATIVE_BENCHMARKS", "micro"), "meso": ("MESO_BENCHMARKS", "meso"), "micro": ("MICRO_BENCHMARKS", "micro"), } -# The fork's suites: suite name -> directory under OWN_BENCH_REL. It holds the benchmark files (Python -# without the .py extension; the harness loads them by path) and their table, benchmarks.txt. +# 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. @@ -77,7 +74,7 @@ def load_table(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, OWN_BENCH_REL, directory, "benchmarks.txt")) as f: + 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: @@ -109,17 +106,15 @@ def split_args(harness_args): def benchmarks(suites, pattern): for suite in suites: if suite in OWN_SUITES: - directory = "%s/%s" % (OWN_BENCH_REL, OWN_SUITES[suite]) - table, extension = load_own_table(OWN_SUITES[suite]), "" + directory, table = OWN_SUITES[suite], load_own_table(OWN_SUITES[suite]) else: - directory = "%s/%s" % (BENCH_REL, SUITES[suite][1]) - table, extension = load_table(SUITES[suite][0]), ".py" + 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 iterations, options, workload = split_args(list(harness_args)) - rel = "%s/%s%s" % (directory, name, extension) + rel = "%s/%s/%s.py" % (BENCH_REL, 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 "") diff --git a/.github/workflows/elide-codspeed.yml b/.github/workflows/elide-codspeed.yml index 159322c0fa..9d0805fae1 100644 --- a/.github/workflows/elide-codspeed.yml +++ b/.github/workflows/elide-codspeed.yml @@ -76,7 +76,7 @@ jobs: retention-days: 1 if-no-files-found: error - # The packages of the suite "packages" (.github/elide/benchmarks/packages) have no wheels for this + # 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. @@ -86,7 +86,7 @@ jobs: runs-on: ${{ vars.CODSPEED_BUILD_RUNNER || 'linux-amd64-cipool' }} timeout-minutes: 90 env: - REQUIREMENTS: .github/elide/benchmarks/packages/requirements.txt + 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: @@ -234,7 +234,7 @@ jobs: run: | "$RUNNER_TEMP/GRAALPY_NATIVE_STANDALONE/bin/graalpy" -m venv "$RUNNER_TEMP/venv" "$RUNNER_TEMP/venv/bin/pip" install --no-cache-dir --no-index --find-links "$RUNNER_TEMP/wheelhouse" \ - -r .github/elide/benchmarks/packages/requirements.txt + -r graalpython/com.oracle.graal.python.benchmarks/python/packages/requirements.txt "$RUNNER_TEMP/venv/bin/python" -c 'import lxml.etree, lxml.html, numpy, orjson, pandas, pydantic' python3 .github/elide/codspeed-bench --python "$RUNNER_TEMP/venv/bin/python" --suite packages \ --max-iterations 4 @@ -274,7 +274,7 @@ jobs: run: | "$RUNNER_TEMP/GRAALPY_NATIVE_STANDALONE/bin/graalpy" -m venv "$RUNNER_TEMP/venv" "$RUNNER_TEMP/venv/bin/pip" install --no-cache-dir --no-index --find-links "$RUNNER_TEMP/wheelhouse" \ - -r .github/elide/benchmarks/packages/requirements.txt + -r graalpython/com.oracle.graal.python.benchmarks/python/packages/requirements.txt - name: Measure # Action and runner versions already in use on this host. diff --git a/.github/elide/benchmarks/packages/benchmarks.txt b/graalpython/com.oracle.graal.python.benchmarks/python/packages/benchmarks.txt similarity index 100% rename from .github/elide/benchmarks/packages/benchmarks.txt rename to graalpython/com.oracle.graal.python.benchmarks/python/packages/benchmarks.txt diff --git a/.github/elide/benchmarks/packages/lxml-xpath b/graalpython/com.oracle.graal.python.benchmarks/python/packages/lxml-xpath.py similarity index 93% rename from .github/elide/benchmarks/packages/lxml-xpath rename to graalpython/com.oracle.graal.python.benchmarks/python/packages/lxml-xpath.py index 902d753b22..3fb52950ce 100644 --- a/.github/elide/benchmarks/packages/lxml-xpath +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/lxml-xpath.py @@ -2,8 +2,8 @@ # XPath with variables), iterfind with edits, serialization and parse of the result, and lxml.html # parsing, link extraction and serialization of an HTML table. # -# Loaded by upstream's harness.py (see .github/elide/README.md). The argument is the number of -# items in the XML document. +# 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. import math import random @@ -35,7 +35,7 @@ def _check(size, result): raise AssertionError("wrong result for size %d: %r, expected %r" % (size, result, expected)) -def __setup__(size): +def __setup__(size=10000): global XML_DOC, HTML_DOC r = random.Random(61) root = etree.Element("{%s}inventory" % NS, nsmap={"inv": NS}) @@ -53,7 +53,7 @@ def __setup__(size): "

Text bold
tail" % rows) -def __benchmark__(size): +def measure(size): ns = {"i": NS} root = etree.fromstring(XML_DOC) low = root.xpath("//i:item[number(i:qty) < 50]/@sku", namespaces=ns) @@ -75,3 +75,7 @@ def __benchmark__(size): result = (len(low), float(total), fragile, names, len(out), count, len(links), prices, len(text), len(serialized)) _check(size, result) return result + + +def __benchmark__(size=10000): + return measure(size) diff --git a/.github/elide/benchmarks/packages/numpy-small-ops b/graalpython/com.oracle.graal.python.benchmarks/python/packages/numpy-small-ops.py similarity index 90% rename from .github/elide/benchmarks/packages/numpy-small-ops rename to graalpython/com.oracle.graal.python.benchmarks/python/packages/numpy-small-ops.py index a151c52a02..9803fc4e96 100644 --- a/.github/elide/benchmarks/packages/numpy-small-ops +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/numpy-small-ops.py @@ -2,8 +2,8 @@ # particle (arithmetic, indexing, linalg.norm, dot, stack, mean, clip). The time goes into calls # from Python into numpy, not into numpy's loops. # -# Loaded by upstream's harness.py (see .github/elide/README.md). The argument is the number of -# particles. +# 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 @@ -38,14 +38,14 @@ def _check(size, result): raise AssertionError("wrong result for size %d: %r, expected %r" % (size, result, expected)) -def __setup__(size): +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 __benchmark__(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]) @@ -71,3 +71,7 @@ def __benchmark__(size): result = (energy, bounces) _check(size, result) return result + + +def __benchmark__(size=600): + return measure(size) diff --git a/.github/elide/benchmarks/packages/numpy-vectorized b/graalpython/com.oracle.graal.python.benchmarks/python/packages/numpy-vectorized.py similarity index 91% rename from .github/elide/benchmarks/packages/numpy-vectorized rename to graalpython/com.oracle.graal.python.benchmarks/python/packages/numpy-vectorized.py index b612a249e5..051f78d47e 100644 --- a/.github/elide/benchmarks/packages/numpy-vectorized +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/numpy-vectorized.py @@ -3,8 +3,8 @@ # 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. # -# Loaded by upstream's harness.py (see .github/elide/README.md). The argument is the length of the -# arrays. +# 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 @@ -48,7 +48,7 @@ def _check(size, result): raise AssertionError("wrong result for size %d: %r, expected %r" % (size, result, expected)) -def __setup__(size): +def __setup__(size=4000000): global X, S, B rs = np.random.RandomState(2) X = rs.rand(size) @@ -57,7 +57,7 @@ def __setup__(size): B = rs.rand(120, 4) -def __benchmark__(size): +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)) @@ -74,3 +74,7 @@ def __benchmark__(size): 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/.github/elide/benchmarks/packages/orjson-roundtrip b/graalpython/com.oracle.graal.python.benchmarks/python/packages/orjson-roundtrip.py similarity index 92% rename from .github/elide/benchmarks/packages/orjson-roundtrip rename to graalpython/com.oracle.graal.python.benchmarks/python/packages/orjson-roundtrip.py index 607229fc73..be399af27b 100644 --- a/.github/elide/benchmarks/packages/orjson-roundtrip +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/orjson-roundtrip.py @@ -1,8 +1,8 @@ # 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. # -# Loaded by upstream's harness.py (see .github/elide/README.md). The argument is the number of -# users in the document. +# Run with harness.py by .github/elide/codspeed-bench, see .github/elide/README.md. The argument is +# the number of users in the document. import dataclasses import math import random @@ -62,14 +62,14 @@ def make_doc(n, seed): return {"version": 3, "generated": "2024-05-06T07:08:09Z", "users": users} -def __setup__(size): +def __setup__(size=10000): 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 __benchmark__(size): +def measure(size): dumped = 0 loaded = 0 for _ in range(4): @@ -83,3 +83,7 @@ def __benchmark__(size): result = (dumped, loaded, pretty, events, tags, balance) _check(size, result) return result + + +def __benchmark__(size=10000): + return measure(size) diff --git a/.github/elide/benchmarks/packages/pandas-apply b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-apply.py similarity index 90% rename from .github/elide/benchmarks/packages/pandas-apply rename to graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-apply.py index c9def93dad..c4bff359e4 100644 --- a/.github/elide/benchmarks/packages/pandas-apply +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-apply.py @@ -1,8 +1,8 @@ # pandas with Python functions per row or element: DataFrame.apply(axis=1), Series.apply and # Series.map with lambdas, iterrows and itertuples. # -# Loaded by upstream's harness.py (see .github/elide/README.md). The argument is the number of -# rows. +# 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 @@ -44,14 +44,14 @@ def classify(row): return "regular" -def __setup__(size): +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 __benchmark__(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) @@ -67,3 +67,7 @@ def __benchmark__(size): int(counts["young-rich"])) _check(size, result) return result + + +def __benchmark__(size=20000): + return measure(size) diff --git a/.github/elide/benchmarks/packages/pandas-csv b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-csv.py similarity index 90% rename from .github/elide/benchmarks/packages/pandas-csv rename to graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-csv.py index a6cc520b75..883cf21b41 100644 --- a/.github/elide/benchmarks/packages/pandas-csv +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-csv.py @@ -1,8 +1,8 @@ # 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. # -# Loaded by upstream's harness.py (see .github/elide/README.md). The argument is the number of -# rows. +# Run with harness.py by .github/elide/codspeed-bench, see .github/elide/README.md. The argument is +# the number of rows. import io import math import os @@ -37,7 +37,7 @@ def _check(size, result): raise AssertionError("wrong result for size %d: %r, expected %r" % (size, result, expected)) -def __setup__(size): +def __setup__(size=200000): global CSV rs = np.random.RandomState(4) df = pd.DataFrame({ @@ -52,7 +52,7 @@ def __setup__(size): CSV = df.to_csv(index=False) -def __benchmark__(size): +def measure(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") @@ -61,3 +61,7 @@ def __benchmark__(size): int(df["comment"].isna().sum()), float(by_city.sum()), float(by_city["Brno"])) _check(size, result) return result + + +def __benchmark__(size=200000): + return measure(size) diff --git a/.github/elide/benchmarks/packages/pandas-groupby-merge b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-groupby-merge.py similarity index 92% rename from .github/elide/benchmarks/packages/pandas-groupby-merge rename to graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-groupby-merge.py index 0091432f45..61bdbaeec2 100644 --- a/.github/elide/benchmarks/packages/pandas-groupby-merge +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-groupby-merge.py @@ -1,8 +1,8 @@ # pandas: merges of a fact table with two dimension tables, groupby with named aggregations, # nlargest, pivot_table and a grouped rank. # -# Loaded by upstream's harness.py (see .github/elide/README.md). The argument is the number of -# rows of the fact table. +# 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. import math import os @@ -46,7 +46,7 @@ def _check(size, result): raise AssertionError("wrong result for size %d: %r, expected %r" % (size, result, expected)) -def __setup__(size): +def __setup__(size=600000): global SALES, CUSTOMERS, PRODUCTS rs = np.random.RandomState(3) SALES = pd.DataFrame({ @@ -63,7 +63,7 @@ def __setup__(size): "cost": rs.randint(1, 6000, 700) / 100}) -def __benchmark__(size): +def measure(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"] @@ -76,3 +76,7 @@ def __benchmark__(size): float(pivot.values.sum()), int(rank.max()), float(monthly.iloc[-1])) _check(size, result) return result + + +def __benchmark__(size=600000): + return measure(size) diff --git a/.github/elide/benchmarks/packages/pandas-str b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-str.py similarity index 91% rename from .github/elide/benchmarks/packages/pandas-str rename to graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-str.py index a886e1f975..c8b20bea3c 100644 --- a/.github/elide/benchmarks/packages/pandas-str +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-str.py @@ -1,8 +1,8 @@ # 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. # -# Loaded by upstream's harness.py (see .github/elide/README.md). The argument is the number of -# rows. +# 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 @@ -37,7 +37,7 @@ def _check(size, result): raise AssertionError("wrong result for size %d: %r, expected %r" % (size, result, expected)) -def __setup__(size): +def __setup__(size=60000): global TEXT, DATES rs = np.random.RandomState(6) first = rs.choice([" John", "jane ", "ALICE", "Bob", "Éva", "Zoë "], size) @@ -49,7 +49,7 @@ def __setup__(size): DATES = pd.Series([(base + pd.Timedelta(seconds=int(s))).strftime("%Y-%m-%d %H:%M:%S") for s in seconds]) -def __benchmark__(size): +def measure(size): s = TEXT.str.strip().str.lower() corp = s.str.contains("corp.org", regex=False) emails = s.str.extract(r"<([^>]+)>", expand=False) @@ -64,3 +64,7 @@ def __benchmark__(size): len(by_month), int(days.sum())) _check(size, result) return result + + +def __benchmark__(size=60000): + return measure(size) diff --git a/.github/elide/benchmarks/packages/pydantic-json b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pydantic-json.py similarity index 93% rename from .github/elide/benchmarks/packages/pydantic-json rename to graalpython/com.oracle.graal.python.benchmarks/python/packages/pydantic-json.py index e13d45d77b..f1f1a96721 100644 --- a/.github/elide/benchmarks/packages/pydantic-json +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pydantic-json.py @@ -2,8 +2,8 @@ # 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. # -# Loaded by upstream's harness.py (see .github/elide/README.md). The argument is the number of -# invoices. +# 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 @@ -75,7 +75,7 @@ def _check(size, result): raise AssertionError("wrong result for size %d: %r, expected %r" % (size, result, expected)) -def __setup__(size): +def __setup__(size=8000): global PAYLOAD r = random.Random(7) raw = [] @@ -100,7 +100,7 @@ def __setup__(size): PAYLOAD = ADAPTER.dump_json(ADAPTER.validate_python(raw)) -def __benchmark__(size): +def measure(size): invoices = ADAPTER.validate_json(PAYLOAD) out = ADAPTER.dump_json(invoices) items = sum(len(inv.items) for inv in invoices) @@ -112,3 +112,7 @@ def __benchmark__(size): result = (len(out), items, cards, single) _check(size, result) return result + + +def __benchmark__(size=8000): + return measure(size) diff --git a/.github/elide/benchmarks/packages/pydantic-models b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pydantic-models.py similarity index 92% rename from .github/elide/benchmarks/packages/pydantic-models rename to graalpython/com.oracle.graal.python.benchmarks/python/packages/pydantic-models.py index 202b6812b8..3fbbb9f42a 100644 --- a/.github/elide/benchmarks/packages/pydantic-models +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pydantic-models.py @@ -2,8 +2,8 @@ # 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. # -# Loaded by upstream's harness.py (see .github/elide/README.md). The argument is the number of -# users. +# 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 @@ -64,7 +64,7 @@ def _check(size, result): raise AssertionError("wrong result for size %d: %r, expected %r" % (size, result, expected)) -def __setup__(size): +def __setup__(size=10000): r = random.Random(3) for i in range(size): d = { @@ -80,7 +80,7 @@ def __setup__(size): TEXTS.append(User.model_validate(d).model_dump_json()) -def __benchmark__(size): +def measure(size): orders = 0 total = 0.0 for d in DICTS: @@ -97,3 +97,7 @@ def __benchmark__(size): result = (orders, total, text_len, named) _check(size, result) return result + + +def __benchmark__(size=10000): + return measure(size) diff --git a/.github/elide/benchmarks/packages/requirements.txt b/graalpython/com.oracle.graal.python.benchmarks/python/packages/requirements.txt similarity index 100% rename from .github/elide/benchmarks/packages/requirements.txt rename to graalpython/com.oracle.graal.python.benchmarks/python/packages/requirements.txt From a1cd0f51fec8e8436eda9389902bb11596cd14f5 Mon Sep 17 00:00:00 2001 From: Ivo Horak Date: Fri, 27 Nov 2026 12:24:34 +0100 Subject: [PATCH 4/8] CodSpeed packages: compile lxml's static libraries with -fPIC lxml's static build links libxml2 and libxslt into the extension, which fails without position-independent code. Use the flags of lxml's own Linux wheels. --- .github/workflows/elide-codspeed.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/elide-codspeed.yml b/.github/workflows/elide-codspeed.yml index 9d0805fae1..6664d15872 100644 --- a/.github/workflows/elide-codspeed.yml +++ b/.github/workflows/elide-codspeed.yml @@ -143,15 +143,17 @@ jobs: 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 are the ones of lxml's own Linux wheels. zlib.net serves only its latest + # 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 + 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 From 9c5f666ad59b49ba713d34aa1b7d0875d25083bf Mon Sep 17 00:00:00 2001 From: Ivo Horak Date: Fri, 27 Nov 2026 13:27:44 +0100 Subject: [PATCH 5/8] CodSpeed packages: use the wheels built here, steadier rows PyPI has prebuilt GraalPy wheels of pydantic-core, and the step that collects the pure Python packages fetched one, which the installation then preferred to the wheel built with the run's standalone. That step now fetches only the pure packages, and the job checks that there is one wheel per pinned package. The iterations of orjson-roundtrip, pandas-csv, pandas-groupby-merge and lxml-xpath varied by up to a factor of ten on GraalPy. These rows, and pandas-str, now repeat their work for a few rounds on smaller data. Every row runs 40 iterations. walltime-summary.json keeps the duration of every iteration. --- .github/elide/README.md | 10 +++--- .github/elide/codspeed-bench | 3 +- .github/workflows/elide-codspeed.yml | 15 ++++++-- .../python/packages/benchmarks.txt | 20 +++++------ .../python/packages/lxml-xpath.py | 20 +++++++---- .../python/packages/orjson-roundtrip.py | 20 +++++++---- .../python/packages/pandas-csv.py | 20 +++++++---- .../python/packages/pandas-groupby-merge.py | 36 +++++++++++-------- .../python/packages/pandas-str.py | 20 +++++++---- 9 files changed, 108 insertions(+), 56 deletions(-) diff --git a/.github/elide/README.md b/.github/elide/README.md index 6efde0a205..71ab49f2b3 100644 --- a/.github/elide/README.md +++ b/.github/elide/README.md @@ -75,11 +75,13 @@ merges from upstream cannot conflict with it: 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)`. Every iteration compares its result with -`EXPECTED[size]` in the file and fails the benchmark when it differs; floats are compared with a +one measured iteration and calls `measure(size)`. Benchmarks whose data are large repeat the work +`ROUNDS` times per iteration on smaller data instead: on GraalPy, iterations over data with +millions of objects varied by a factor of up to ten. 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, because the benchmark host has no network access to PyPI. +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 @@ -93,7 +95,7 @@ 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 (30 for the current ones). + 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 diff --git a/.github/elide/codspeed-bench b/.github/elide/codspeed-bench index d09ec5b83b..1f564954f6 100755 --- a/.github/elide/codspeed-bench +++ b/.github/elide/codspeed-bench @@ -257,7 +257,8 @@ 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) 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) diff --git a/.github/workflows/elide-codspeed.yml b/.github/workflows/elide-codspeed.yml index 6664d15872..255d45712e 100644 --- a/.github/workflows/elide-codspeed.yml +++ b/.github/workflows/elide-codspeed.yml @@ -161,10 +161,19 @@ jobs: echo "::error::failed to build:$failed" exit 1 fi - # The pure Python packages. The compiled ones are taken from the wheelhouse. - "$RUNNER_TEMP/build-venv/bin/pip" wheel --no-cache-dir --only-binary :all: -w "$WHEELS" \ - --find-links "$WHEELS" -r "$REQUIREMENTS" + # 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 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 4dd3982fe5..d795106661 100644 --- a/graalpython/com.oracle.graal.python.benchmarks/python/packages/benchmarks.txt +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/benchmarks.txt @@ -7,13 +7,13 @@ # not part of the name. The first half of the iterations is warm-up. # # name harness arguments -pydantic-json -i 30 8000 -pydantic-models -i 30 10000 -orjson-roundtrip -i 30 10000 -pandas-csv -i 30 200000 -pandas-str -i 30 60000 -pandas-groupby-merge -i 30 600000 -pandas-apply -i 30 20000 -numpy-small-ops -i 30 600 -numpy-vectorized -i 30 4000000 -lxml-xpath -i 30 10000 +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 index 3fb52950ce..829e19b09c 100644 --- a/graalpython/com.oracle.graal.python.benchmarks/python/packages/lxml-xpath.py +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/lxml-xpath.py @@ -3,16 +3,18 @@ # 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. +# 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 iteration +# number of items -> result of one round EXPECTED = { - 10000: (1013, 1263194.7300000004, 3109, 10000, 1678301, 10000, 5000, 249656, 68457, 462455), + 2500: (264, 307224.9399999998, 766, 2500, 418417, 2500, 1250, 60754, 16278, 114026), } +ROUNDS = 4 REL_TOL = 1e-9 NS = "urn:example:inventory" @@ -35,7 +37,7 @@ def _check(size, result): raise AssertionError("wrong result for size %d: %r, expected %r" % (size, result, expected)) -def __setup__(size=10000): +def __setup__(size=2500): global XML_DOC, HTML_DOC r = random.Random(61) root = etree.Element("{%s}inventory" % NS, nsmap={"inv": NS}) @@ -53,7 +55,7 @@ def __setup__(size=10000): "

Text bold
tail" % rows) -def measure(size): +def one_round(size): ns = {"i": NS} root = etree.fromstring(XML_DOC) low = root.xpath("//i:item[number(i:qty) < 50]/@sku", namespaces=ns) @@ -77,5 +79,11 @@ def measure(size): return result -def __benchmark__(size=10000): +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-roundtrip.py b/graalpython/com.oracle.graal.python.benchmarks/python/packages/orjson-roundtrip.py index be399af27b..f159eb9e9d 100644 --- a/graalpython/com.oracle.graal.python.benchmarks/python/packages/orjson-roundtrip.py +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/orjson-roundtrip.py @@ -2,17 +2,19 @@ # 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. +# 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 iteration +# number of users -> result of one round EXPECTED = { - 10000: (17173340, 40000, 7853271, 1268050, 25294, 44980320.98), + 2500: (4290716, 10000, 1962336, 316515, 6334, 11078071.56), } +ROUNDS = 4 REL_TOL = 1e-9 @@ -62,14 +64,14 @@ def make_doc(n, seed): return {"version": 3, "generated": "2024-05-06T07:08:09Z", "users": users} -def __setup__(size=10000): +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 measure(size): +def one_round(size): dumped = 0 loaded = 0 for _ in range(4): @@ -85,5 +87,11 @@ def measure(size): return result -def __benchmark__(size=10000): +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-csv.py b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-csv.py index 883cf21b41..eb6b4c8d6e 100644 --- a/graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-csv.py +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-csv.py @@ -2,7 +2,8 @@ # 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. +# 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 @@ -13,10 +14,11 @@ import numpy as np import pandas as pd -# number of rows -> result of one iteration +# number of rows -> result of one round EXPECTED = { - 200000: (3120180, 99878260, 200000, 1305855, 20054, 100052818.382, 20024794.616), + 50000: (772606, 24984228, 50000, 325941, 5013, 24947990.612, 4967281.144), } +ROUNDS = 4 REL_TOL = 1e-9 CSV = "" @@ -37,7 +39,7 @@ def _check(size, result): raise AssertionError("wrong result for size %d: %r, expected %r" % (size, result, expected)) -def __setup__(size=200000): +def __setup__(size=50000): global CSV rs = np.random.RandomState(4) df = pd.DataFrame({ @@ -52,7 +54,7 @@ def __setup__(size=200000): CSV = df.to_csv(index=False) -def measure(size): +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") @@ -63,5 +65,11 @@ def measure(size): return result -def __benchmark__(size=200000): +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 index 61bdbaeec2..692f6a33f6 100644 --- 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 @@ -2,7 +2,8 @@ # 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. +# 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 @@ -12,20 +13,21 @@ import numpy as np import pandas as pd -# number of rows -> result of one iteration +# number of rows -> result of one round EXPECTED = { - 600000: ( - 524828, + 150000: ( + 131355, 32, - 130964960.46000001, - 3217.1785678239376, - 524828, - 1750154.6600000001, - 52768190.0, - 136105, - 1762282.68, + 32762568.990000002, + 3013.5156341057127, + 131355, + 579432.23, + 12418730.170000002, + 33582, + 444748.38, ), } +ROUNDS = 4 REL_TOL = 1e-9 SALES = CUSTOMERS = PRODUCTS = None @@ -46,7 +48,7 @@ def _check(size, result): raise AssertionError("wrong result for size %d: %r, expected %r" % (size, result, expected)) -def __setup__(size=600000): +def __setup__(size=150000): global SALES, CUSTOMERS, PRODUCTS rs = np.random.RandomState(3) SALES = pd.DataFrame({ @@ -63,7 +65,7 @@ def __setup__(size=600000): "cost": rs.randint(1, 6000, 700) / 100}) -def measure(size): +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"] @@ -78,5 +80,11 @@ def measure(size): return result -def __benchmark__(size=600000): +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 index c8b20bea3c..82c9b29324 100644 --- a/graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-str.py +++ b/graalpython/com.oracle.graal.python.benchmarks/python/packages/pandas-str.py @@ -2,7 +2,8 @@ # 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. +# 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 @@ -12,10 +13,11 @@ import numpy as np import pandas as pd -# number of rows -> result of one iteration +# number of rows -> result of one round EXPECTED = { - 60000: (20146, 569021, 2878839, 2022984, 9922, 180777, 2620, 24, 938675), + 20000: (6620, 182185, 959289, 666674, 3262, 60018, 864, 24, 312836), } +ROUNDS = 3 REL_TOL = 1e-9 TEXT = None @@ -37,7 +39,7 @@ def _check(size, result): raise AssertionError("wrong result for size %d: %r, expected %r" % (size, result, expected)) -def __setup__(size=60000): +def __setup__(size=20000): global TEXT, DATES rs = np.random.RandomState(6) first = rs.choice([" John", "jane ", "ALICE", "Bob", "Éva", "Zoë "], size) @@ -49,7 +51,7 @@ def __setup__(size=60000): DATES = pd.Series([(base + pd.Timedelta(seconds=int(s))).strftime("%Y-%m-%d %H:%M:%S") for s in seconds]) -def measure(size): +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) @@ -66,5 +68,11 @@ def measure(size): return result -def __benchmark__(size=60000): +def measure(size): + for _ in range(ROUNDS): + result = one_round(size) + return result + + +def __benchmark__(size=20000): return measure(size) From 51dfaec533a89ee48e6b5cdde1911fcda348b56a Mon Sep 17 00:00:00 2001 From: Ivo Horak Date: Fri, 27 Nov 2026 13:49:33 +0100 Subject: [PATCH 6/8] CodSpeed packages: create the package environment with a script In one run the virtual environment on the benchmark host came without pip, although the same commands worked on the pool and in the run before. package-venv, used by check and walltime, starts from an empty environment, lists it, runs pip as a module and installs pip with ensurepip when it is missing. --- .github/elide/README.md | 2 +- .github/elide/package-venv | 20 ++++++++++++++++++++ .github/workflows/elide-codspeed.yml | 11 ++++------- 3 files changed, 25 insertions(+), 8 deletions(-) create mode 100755 .github/elide/package-venv diff --git a/.github/elide/README.md b/.github/elide/README.md index 71ab49f2b3..10386eace4 100644 --- a/.github/elide/README.md +++ b/.github/elide/README.md @@ -118,7 +118,7 @@ libxslt linked in statically, pydantic-core and orjson with a Rust toolchain ins 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 and runs every package benchmark for four iterations; `walltime` installs them into a +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`). 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 255d45712e..287a55b78c 100644 --- a/.github/workflows/elide-codspeed.yml +++ b/.github/workflows/elide-codspeed.yml @@ -243,10 +243,8 @@ jobs: # Four iterations each: every iteration checks its result. - name: Run the package benchmarks briefly run: | - "$RUNNER_TEMP/GRAALPY_NATIVE_STANDALONE/bin/graalpy" -m venv "$RUNNER_TEMP/venv" - "$RUNNER_TEMP/venv/bin/pip" install --no-cache-dir --no-index --find-links "$RUNNER_TEMP/wheelhouse" \ - -r graalpython/com.oracle.graal.python.benchmarks/python/packages/requirements.txt - "$RUNNER_TEMP/venv/bin/python" -c 'import lxml.etree, lxml.html, numpy, orjson, pandas, pydantic' + .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 @@ -283,9 +281,8 @@ jobs: # From the wheels built on the pool only, without a network. - name: Install the packages run: | - "$RUNNER_TEMP/GRAALPY_NATIVE_STANDALONE/bin/graalpy" -m venv "$RUNNER_TEMP/venv" - "$RUNNER_TEMP/venv/bin/pip" install --no-cache-dir --no-index --find-links "$RUNNER_TEMP/wheelhouse" \ - -r graalpython/com.oracle.graal.python.benchmarks/python/packages/requirements.txt + .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. From 903a8e52f9adedb01d6161487321f667c69e872b Mon Sep 17 00:00:00 2001 From: Ivo Horak Date: Fri, 27 Nov 2026 15:02:25 +0100 Subject: [PATCH 7/8] CodSpeed packages: manual diagnose runs, correct the ROUNDS rationale A manual run of elide-codspeed.yml with the input "diagnose" runs the selected benchmarks on the benchmark host once per interpreter option set of codspeed-diagnose.txt instead of the walltime job, and reports nothing to CodSpeed. It keeps every iteration's duration, the GC log, the collections per iteration and the peak RSS of each benchmark process as an artifact. The option sets compare GraalPy's forced full collections (background GC task, native memory limit, System.gc) and the young generation size on the rows that vary most. codspeed-bench takes interpreter options (--python-arg, refused when reporting to CodSpeed), a label and a directory for each process's output, and records each benchmark process's peak RSS. The README said that repeating the work in ROUNDS makes the rows steadier; the last run showed it does not. The title of the commit that introduced ROUNDS ("steadier rows") is inaccurate for the same reason. --- .github/elide/README.md | 27 ++- .github/elide/codspeed-bench | 76 ++++++-- .github/elide/codspeed-diagnose | 279 +++++++++++++++++++++++++++ .github/elide/codspeed-diagnose.txt | 20 ++ .github/workflows/elide-codspeed.yml | 87 +++++++++ 5 files changed, 470 insertions(+), 19 deletions(-) create mode 100755 .github/elide/codspeed-diagnose create mode 100644 .github/elide/codspeed-diagnose.txt diff --git a/.github/elide/README.md b/.github/elide/README.md index 10386eace4..bf92450b46 100644 --- a/.github/elide/README.md +++ b/.github/elide/README.md @@ -75,9 +75,10 @@ merges from upstream cannot conflict with it: 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)`. Benchmarks whose data are large repeat the work -`ROUNDS` times per iteration on smaller data instead: on GraalPy, iterations over data with -millions of objects varied by a factor of up to ten. Every iteration (or round) compares its result +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 (see "Diagnosing noisy rows"). 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 @@ -122,6 +123,26 @@ 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`). +### 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 All jobs run on Elide's runners, the pool with the label `linux-amd64-cipool`. Set the repository diff --git a/.github/elide/codspeed-bench b/.github/elide/codspeed-bench index 1f564954f6..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 @@ -147,12 +152,13 @@ def walltime_stats(durations_s): } -def run_one(python, bench, min_iterations, max_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) if max_iterations: iterations = min(iterations, max_iterations) - cmd = [python, HARNESS, bench["file"], "-i", str(iterations)] + bench["options"] + bench["workload"] + 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 @@ -160,22 +166,43 @@ def run_one(python, bench, min_iterations, max_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): @@ -202,6 +229,11 @@ def main(): "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") @@ -238,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, {} @@ -247,8 +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(pythons.get(bench["suite"], args.python), bench, args.min_iterations, - args.max_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) @@ -258,14 +299,17 @@ def main(): 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) + 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/workflows/elide-codspeed.yml b/.github/workflows/elide-codspeed.yml index 287a55b78c..bc330c613d 100644 --- a/.github/workflows/elide-codspeed.yml +++ b/.github/workflows/elide-codspeed.yml @@ -11,12 +11,35 @@ name: CodSpeed benchmarks # # 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 @@ -248,8 +271,19 @@ jobs: 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 + if: ${{ !inputs.diagnose }} needs: [build, wheels, check] runs-on: ${{ vars.CODSPEED_WALLTIME_RUNNER || 'linux-amd64-bench' }} timeout-minutes: 120 @@ -321,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 From 1df9f224a36dc39d11d9dfed4354dace38e24926 Mon Sep 17 00:00:00 2001 From: Ivo Horak Date: Fri, 27 Nov 2026 16:19:06 +0100 Subject: [PATCH 8/8] CodSpeed packages: describe what makes five rows vary The first diagnose run (46012333870) showed that the variation of orjson-roundtrip, pandas-csv, pandas-str, pandas-groupby-merge and lxml-xpath is garbage collection time: a heap that grows with every iteration on four of them, and collections forced by the native memory limit on pandas-groupby-merge. --- .github/elide/README.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/.github/elide/README.md b/.github/elide/README.md index bf92450b46..c7f77a185b 100644 --- a/.github/elide/README.md +++ b/.github/elide/README.md @@ -78,7 +78,22 @@ Each file is in the format of upstream's `harness.py`, like the files in `meso` 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 (see "Diagnosing noisy rows"). Every iteration (or round) compares its result +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