diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 0ebb99a..1a65d3b 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -45,8 +45,12 @@ jobs: timeout-minutes: 20 strategy: fail-fast: false + # `requires`: what the example needs beyond benchx and pyperf, for `uv pip install`. matrix: - example: [pyperf-suite] + include: + - example: pyperf-suite + - example: matmul-params + requires: numpy torch --index-url https://download.pytorch.org/whl/cpu env: EXAMPLE: ${{ matrix.example }} steps: @@ -69,6 +73,12 @@ jobs: uv sync --extra parquet --extra test --python 3.13 echo "$PWD/.venv/bin" >> "$GITHUB_PATH" + - name: Install what the example needs + if: matrix.requires + env: + REQUIRES: ${{ matrix.requires }} + run: uv pip install $REQUIRES + - name: Show what is under test run: | echo "python: $(python --version) ($(command -v python))" diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 0779820..54c4be8 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -1,6 +1,6 @@ name: e2e examples -# Runs examples from benchx-dev/benchx_examples and prints their output. Five jobs: +# Runs examples from benchx-dev/benchx_examples and prints their output. Three jobs: # # numpy-spin builds NumPy with spin and benchmarks it: # track.sh several revisions, each built and benchmarked @@ -8,9 +8,6 @@ name: e2e examples # arrow builds a small Google Benchmark suite with CMake and compares the builds: # examples/arrow/demo/run.sh # examples/arrow/archery-local/run.sh -# matmul-params runs one parametrized benchmark, numpy and torch at three sizes, with -# `bx bench`; the quick version from the example's README: -# examples/matmul-params # numpy-venvs measures the same benchmarks under two numpy versions, each in its own venv, # with a `bx bench` call per side and round, and compares them: # examples/numpy-venvs/run.sh @@ -239,73 +236,6 @@ jobs: if-no-files-found: warn retention-days: 14 - matmul-params: - name: matmul-params (quick version) - runs-on: ubuntu-latest - timeout-minutes: 20 - env: - # Keep the result store with the output, as the README does, not in the home directory. - BENCHX_HOME: ${{ github.workspace }}/benchx_examples/examples/matmul-params/out/home - steps: - - name: Check out benchx - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - with: - path: benchx - - - name: Clone benchx_examples - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - with: - repository: benchx-dev/benchx_examples - ref: ${{ inputs.examples_ref || 'main' }} - path: benchx_examples - - - uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5.4.2 - with: - enable-cache: true - cache-dependency-glob: benchx/uv.lock - - # The workers need pyperf, which benchx brings. benchx is installed in editable - # mode, which is where it reads its schemas from. - - name: Install benchx - working-directory: benchx - run: | - uv python install 3.13 - uv sync --extra parquet --python 3.13 - echo "$PWD/.venv/bin" >> "$GITHUB_PATH" - - # The README's install lines. torch comes from PyTorch's CPU index: the default - # build is several GB of CUDA libraries that the runner has no use for. - - name: Install NumPy and PyTorch - run: | - uv pip install --python benchx/.venv/bin/python numpy - uv pip install --python benchx/.venv/bin/python torch --index-url https://download.pytorch.org/whl/cpu - - - name: Show what is under test - run: | - echo "python: $(python --version) ($(command -v python))" - echo "bx: $(command -v bx)" - echo "pyperf: $(python -c 'import pyperf; print(pyperf.__version__)')" - echo "numpy: $(python -c 'import numpy; print(numpy.__version__)')" - echo "torch: $(python -c 'import torch; print(torch.__version__)')" - echo "benchx: $(git -C benchx rev-parse --short HEAD)" - echo "benchx_examples: $(git -C benchx_examples rev-parse --short HEAD)" - - # The quick version of the README: 2 processes x 2 values per case, 0.01 s of - # calibration. With pyperf's defaults it takes several minutes, mostly importing torch - # in every worker. `bx bench` prints one row per case. - - name: Run the quick version - working-directory: benchx_examples/examples/matmul-params - run: bx bench bench_matmul.py --processes 2 --values 2 --min-time 0.01 --out out - - - name: Upload the output - if: always() - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: matmul-params-output - path: benchx_examples/examples/matmul-params/out - if-no-files-found: warn - retention-days: 14 - numpy-venvs: name: numpy-venvs (run.sh) runs-on: ubuntu-latest diff --git a/docs/benchx.md b/docs/benchx.md index d7b0bae..cffaad2 100644 --- a/docs/benchx.md +++ b/docs/benchx.md @@ -70,6 +70,10 @@ bx compare BASELINE CONTENDER --profile revisions|environments bx compare TARGET --profile variants --adapter pyperf|asv --suite NAME [--rounds 6] [--vary NAME] [--baseline VALUE] [--filter REGEX] [...] # the options above, except --label +# the shorthand of bx bench MODULE.py, in measure mode: Python files, no --suite, pyperf +bx compare BASE/MODULE.py HEAD/MODULE.py --profile revisions|environments --rounds R [...] +bx compare MODULE.py --profile variants --rounds R [--vary NAME] [...] + # read mode: compare results already measured bx compare --run KEY --profile revisions|environments|variants --baseline VALUE [--label NAME] [--vary NAME] [--results DIR] [--k 3] [--json | --tables [--all]] @@ -134,7 +138,7 @@ it measures and where it sits (`measuring np_mean.py on @numpy (round 1/5, slot with one naming the order; `-q` keeps it, `-qq` does not. What `bx bench` and `bx run` report on stdout when they finish, the table of results, the cases that were not measured and the result line, is in the log as well, a line a record, and `-q` and `-qq` hide it by tiers: `-q` leaves -the not-measured section and the result line (`N result(s) -> DIR`), `-qq` only the +the not-measured section and the result line (`N result(s) -> DIR`, then `run-key: KEY`), `-qq` only the not-measured section (a failed case does not change the exit status, so it must not vanish; a case that failed without a message is counted on a line that both keep, and a case the harness skipped is expected, so what it said goes with the table). A @@ -198,7 +202,9 @@ function without readable source has no version. `bx bench MODULE.py [FUNCTION …]` is the shorthand for the quickest case, timing a few functions: the module's git checkout is the target, its path the suite, and the -functions are exact case names. `bx run` is the layer underneath: it executes a finished +functions are exact case names. `bx compare` takes the same shorthand for each target when +there is no `--suite`: every target is then a Python file, and the files have the same path +in their checkouts, since the suite is one name for all the sides. `bx run` is the layer underneath: it executes a finished order, so `bx run results/KEY/orders/order.json` replays any bench run. [`examples/pyperf-suite`](examples/pyperf-suite.md) is a runnable walk-through. diff --git a/docs/design/prototype-design.md b/docs/design/prototype-design.md index 7033420..2cf3870 100644 --- a/docs/design/prototype-design.md +++ b/docs/design/prototype-design.md @@ -25,7 +25,7 @@ bx compare --run KEY --profile revisions|environments|variants --baseline VALUE # read mode: compare results already measured bx target describe|prepare TARGET # a target's description (a provider's answer, or a build directory's sidecar) bx compare BASELINE CONTENDER --profile revisions|environments - [--adapter pyperf|google-benchmark] # default: adapter.name + [--adapter pyperf|google-benchmark] # default: adapter.name, else pyperf --suite NAME [--filter REGEX] [--quantity NAMES] # default: adapter.suite, adapter.quantities --rounds R [-e NAME=VALUE ...] [--repetitions N] # google-benchmark diff --git a/docs/examples.md b/docs/examples.md index 09e4640..d24cfc6 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -37,6 +37,8 @@ in this repository. - [`pyperf-suite`](examples/pyperf-suite.md) -- timing a suite of Python functions with `bx bench`, the local store, and `bx series` / `bx history`. +- [`matmul-params`](examples/matmul-params.md) — one benchmark function with several parameter + combinations (sizes, numpy and torch), and a numpy-vs-torch comparison with `bx compare`. ## Additional, cookbook-style examples diff --git a/examples/README.md b/examples/README.md index 66048f4..6ee4376 100644 --- a/examples/README.md +++ b/examples/README.md @@ -32,8 +32,8 @@ Each directory here is an example: a `README.md` and the files it uses. CI execu an unexpected failure does, so the page cannot go on showing an error the code no longer gives. Its output goes into the page as for any block, and the run goes on. The fence is one script run with `-e`, so the status is that of the first command that fails, and the commands after it - do not run: put the failing command last. The page has the fence without `exit=1` (the site's - fence parser does not take a `key=value` there). Python blocks have no such marker. + do not run: put the failing command last. Python blocks have no such marker. + The page has a fence without its `exit=1` or `noexec` (the site's fence parser takes neither). - On the page, ANSI escape sequences are removed from the output, and so is the path of the repository checkout (`/home/runner/work/benchx/benchx/examples/x` shows as `examples/x`). - Do not link to other files of the example from the README: the page is built into the site on its @@ -49,7 +49,8 @@ Each directory here is an example: a `README.md` and the files it uses. CI execu `tools/gen_docs.py --executed` stops, since the site would show the example unexecuted. 3. Add a line for it under "Worked examples of local benchmarking" in `docs/examples.md`. -An example that needs more than `benchx` and `pyperf` (a compiler, another package) gets its own job in +An example that needs other Python packages than `benchx` and `pyperf` lists them as `requires` in its +matrix entry (`matmul-params` does, for numpy and torch). One that needs more (a compiler) gets its own job in `docs.yml` instead of a matrix leg. The contract is the artifact: the job uploads `docs-` containing `.md`. diff --git a/examples/matmul-params/.gitignore b/examples/matmul-params/.gitignore new file mode 100644 index 0000000..ea93687 --- /dev/null +++ b/examples/matmul-params/.gitignore @@ -0,0 +1,2 @@ +out/ +__pycache__/ diff --git a/examples/matmul-params/README.md b/examples/matmul-params/README.md new file mode 100644 index 0000000..4445cfa --- /dev/null +++ b/examples/matmul-params/README.md @@ -0,0 +1,319 @@ +# Example: one benchmark, several parameter combinations; comparisons across parameters + +In this demo, we show + +- how to run a parametrized benchmark: time a matrix multiply, `a @ b`, +for square arrays of several sizes, represented as numpy arrays and torch tensors. + +- how to arrive at a *comparison verdict* across "variants": is matrix multiply in + NumPy faster or slower than PyTorch's? + +The first part follows the +[UC-01](https://github.com/benchx-dev/benchx/blob/main/docs/use-cases/UC-01-short-slug.md) shape, +and second part is a +[UC-02](https://github.com/benchx-dev/benchx/blob/main/docs/use-cases/UC-02-variants.md) +benchmark: the same function, run once with each library, with the rounds interleaved. + + +## Install the required dependencies + + +```sh noexec +python -m venv .venv && . .venv/bin/activate +pip install benchx[parquet] +pip install numpy +pip install torch --index-url https://download.pytorch.org/whl/cpu # the CPU build +``` + + +## Run a quick version + +By default, `benchx` uses `pyperf`'s defauls: 20 worker processes x 3 values each, and 0.1s calibration. +In this demo, we use a quick-and-dirty version, so that the run time is smaller but the results are noisy + +```sh +$ export QUICK="--processes 2 --values 2 --min-time 0.01" +$ bx bench bench_matmul.py $QUICK +``` + +```text +measuring bench_matmul.py on /home/br/temp/bex +precision: 2 processes x 2 values (config: /home/br/temp/bex/benchx.conf.json) +caveats: dirty-benchmark-tree, dirty-subject-tree +case median mean ± sd min .. max n status +-------------------------------- -------- ------------------- -------------------- - ------- +bench_matmul [n=10, xp='numpy'] 2.612 us 2.647 us ± 99.43 ns 2.572 us .. 2.793 us 4 success +bench_matmul [n=10, xp='torch'] 2.784 us 2.772 us ± 103.2 ns 2.65 us .. 2.871 us 4 success +bench_matmul [n=50, xp='numpy'] 15.37 us 15.42 us ± 240.6 ns 15.22 us .. 15.71 us 4 success +bench_matmul [n=50, xp='torch'] 6.533 us 6.502 us ± 86.06 ns 6.376 us .. 6.567 us 4 success +bench_matmul [n=100, xp='numpy'] 42.39 us 42.4 us ± 214.4 ns 42.21 us .. 42.61 us 4 success +bench_matmul [n=100, xp='torch'] 15.84 us 15.89 us ± 178.2 ns 15.75 us .. 16.13 us 4 success +bench_matmul [n=200, xp='numpy'] 131.7 us 143.1 us ± 25.6 us 127.8 us .. 181.2 us 4 success +bench_matmul [n=200, xp='torch'] 95.36 us 95.49 us ± 2.644 us 93.15 us .. 98.09 us 4 success + +16 result(s) -> /home/br/temp/bex/out/bench-20261130T094305Z (order sha256:b414dd788b58) +run-key: bench-20261130T094305Z +/home/br/temp/bex/out/home/store.parquet: ingested 16, duplicate 0 +``` + +The output shows a row per combination, named by the function and its arguments. It also shows paths to the +*benchx configuration file*, and the *local store*, a parquet file which contains detailed data +from the benchmarking run. + +As usual (see the [basic tutorial](https://benchx.dev/examples/pyperf-suite/)), +bare result files are in `out/`, and `out/home/store.parquet` is the store. +Note that `bx` reports twice as many results as rows: each case also records `load-average`--- +roughly, the *load average* is how many processes were running or waiting for a CPU over at the start of the benchmark +run. A value well above the CPU core count means the machine was busy, so the timings may be noisy. + + +### Choosing cases + +We can select specific cases by either giving exact parameter values or a regex. Note that since we are parametrizing +the benchmark with string arguments, we have to use the quoted strings in CLI. + +``` +$ bx bench bench_matmul.py bench_matmul # a function's name: all eight +$ bx bench bench_matmul.py "bench_matmul(100, 'torch')" # one combination +$ bx bench bench_matmul.py --filter "'torch'" # a regex: the four torch cases +``` + +A regex is searched in `bench_matmul(10, 'torch')`, the function's name and the argument +values (not their names). `--filter 'bench_matmul$'` is therefore refused, since `$` leaves +no room for the arguments; the refusal says so. + + +## Comparing numpy and torch + +Suppose now we ask: is PyTorch matmul faster than NumPy matmul for the same matrix size? +We can of course, visually inspect the output above, and try to guesstimate the spread of the results +(shown in the `min..max` column). + +`benchx` however provides a better way to perform a comparison and run a statistical analysis to come up with +a _comparison verdict_ (faster, slower or indeterminate). The relevant CLI command is `bx compare`. + +### A first attempt (that fails) + +We have already run benchmarks for both numpy and torch, can we use them to run the comparison via `bx compare`? +First, we need to find out the *run key*. We did not specify it explicitly, thus it has been automatically +generated by `bx bench`, from the name of the benchmark and the timestamp: + +```bash +$ bx head +``` + +```text +/home/br/temp/bex/out/home/store.parquet: 16 result(s); latest 10, newest first + row started run-key workload quantity status median revision project + 15 2026-11-30 10:09:35 bench-20261130T100917Z bench_matmul load-average success 0.7 directory- local/gonzales + 14 2026-11-30 10:09:35 bench-20261130T100917Z bench_matmul wall-time success [dirty-subject-tree, dirty-benchmark-tree] 9.68303e-05 s directory- local/gonzales + 13 2026-11-30 10:09:34 bench-20261130T100917Z bench_matmul load-average success 0.7 directory- local/gonzales + 12 2026-11-30 10:09:34 bench-20261130T100917Z bench_matmul wall-time success [dirty-subject-tree, dirty-benchmark-tree] 0.000140487 s directory- local/gonzales + 11 2026-11-30 10:09:29 bench-20261130T100917Z bench_matmul load-average success 0.68 directory- local/gonzales + 10 2026-11-30 10:09:29 bench-20261130T100917Z bench_matmul wall-time success [dirty-subject-tree, dirty-benchmark-tree] 1.57617e-05 s directory- local/gonzales + 9 2026-11-30 10:09:28 bench-20261130T100917Z bench_matmul load-average success 0.68 directory- local/gonzales + 8 2026-11-30 10:09:28 bench-20261130T100917Z bench_matmul wall-time success [dirty-subject-tree, dirty-benchmark-tree] 4.2506e-05 s directory- local/gonzales + 7 2026-11-30 10:09:23 bench-20261130T100917Z bench_matmul load-average success 0.65 directory- local/gonzales + 6 2026-11-30 10:09:23 bench-20261130T100917Z bench_matmul wall-time success [dirty-subject-tree, dirty-benchmark-tree] 6.44393e-06 s directory- local/gonzales +``` + +The *run key* is listed in the fourth column of the output. + +Next, we supply the following parameters to `bx compare`: + +- we compare across *variants*: same function, varying values of its parameter: `--profile variants`; +- we vary the `xp` parameter and compare for each value of the other parameter `n`: `--vary xp`; +- we ask whether the *contender* PyTorch is measurably faster than the *baseline* NumPy: `--baseline "'numpy'"`; Note that + the double quotes here are not a typo: in Python, we parametrize the benchmark function with strings, thus we need to + keep the quotes in the CLI invocation. + +Taking it all together, we run + +```bash +$ RUN=$(bx head -n 1 | awk 'NR==3 {print $4}') +$ bx compare --profile variants --run $RUN --vary xp --baseline "'numpy'" +``` + +```text +run bench-20261126T180958Z profile variants baseline 'numpy' contender 'torch' + +failed invariants (1) + alternating-slots: a result has no slot: give every bx bench call --slot; make one bx bench call per value, each with --run-key, --round and --slot, or run bx compare TARGET --profile variants +``` + +which fails with a mysterious error message. What is going on here? + + +### A proper comparison requires an alternating run + +Here we are facing a design constraint of `benchx`: to produce a comparison verdict, it needs to +run the comparison sides multiple times, and interleave the runs. This way, it can estimate the noise +and control for possible drift in the benchmarking environment. + +To run the comparison, we need to explicitly to provide the `--rounds R` argument, where each +side of the comparison will be run `R` times. In fact, to compare the *sides* `A` and `B`, it +runs a sequence `ABABABAB` or `ABBAABBA`, of `2R` runs in total, where it places +the individuals runs for the sides into alternating *slots*. +From the run-to-run variations, it estimates the noise. To arrive to a +*comparison verdict* (regressed, improved, indeterminate), it compares the measured +difference between `A` and `B` to the noise estimate. + +The minimal number of rounds is four, since otherwise the noise estimate is too unreliable. +Setting a smaller number of rounds will result in `INDETERMINATE (insufficient-rounds)` +as a comparison verdict. +Increasing the number of rounds improves the quality of the statistical estimates, at +the expense of longer run times. + +Taking this all together: + +```bash +$ export QUICK="--processes 2 --values 2 --min-time 0.01" +bx compare bench_matmul.py --profile variants --vary xp --rounds 5 $QUICK +``` + +```text +/home/br/temp/bex/out/home/store.parquet +tree /home/br/temp/bex is dirty: the comparison will be local-only +round 1/5 xp='numpy': 8 result(s) +round 1/5 xp='torch': 8 result(s) +round 2/5 xp='torch': 8 result(s) +round 2/5 xp='numpy': 8 result(s) +round 3/5 xp='numpy': 8 result(s) +round 3/5 xp='torch': 8 result(s) +round 4/5 xp='torch': 8 result(s) +round 4/5 xp='numpy': 8 result(s) +round 5/5 xp='numpy': 8 result(s) +round 5/5 xp='torch': 8 result(s) +run-key compare-20261130T095855Z profile variants baseline 'numpy' contender 'torch' [local-only] + caveats: baseline: dirty-benchmark-tree, dirty-subject-tree + contender: dirty-benchmark-tree, dirty-subject-tree + +IMPROVED (3) + bench_matmul [n=50] wall-time effect -62.84% noise 1.15% rounds=5 + bench_matmul [n=100] wall-time effect -62.84% noise 4.98% rounds=5 + bench_matmul [n=200] wall-time effect -38.61% noise 3.37% rounds=5 + +NO CHANGE DETECTED (1) + bench_matmul [n=10] wall-time effect -1.37% noise 4.04% rounds=5 +``` + +The result is one unit per size, with numpy as the *baseline* and torch as the *contender*: the effect is +torch's median time relative to numpy's, so `REGRESSED` means torch took longer, and the noise is taken +across the five rounds. The units are grouped by verdict. + +On one specific laptop, the report was that `torch` is on par with `numpy` at N=10 and is faster for larger N. +In general, for our quick-and-dirty setting, `$QUICK`, results are expected to show fairly wild variations or even be borderline +noise. A real comparison will need to use at least the default settings or actually larger number of rounds and values. + + +#### Show all comparison results, as a table + +The output above only shows "effects" and does not show actual timings. To show both, we could have +added `--tables --all` to the `bx compare` call. Given that we did not add it, we can rerun the +comparison (but not the benchmarks themselves!) in the so-called *read mode*, where it pulls the +data to compare from the store. + +First, instead of the benchmark suite, it needs the run key for the precomputed data. +Then, we give it the same `--profile variants --vary xp` arguments to specify what to +compare, and also we tell it which side is the baseline, `--baseline "'numpy'"` +Taking it all together, + +```bash +$ RUN=$(bx head -n 1 | awk 'NR==3 {print $4}') +$ bx compare --run $RUN --profile variants --vary xp --baseline "'numpy'" --tables --all +``` + +```text +bx compare --run $RUN --profile variants --vary xp --baseline "'numpy'" --tables --all +run-key compare-20261130T095855Z profile variants baseline 'numpy' contender 'torch' [local-only] + caveats: baseline: dirty-benchmark-tree, dirty-subject-tree + contender: dirty-benchmark-tree, dirty-subject-tree + +IMPROVED (3) + bench_matmul [n=50] wall-time effect -62.84% noise 1.15% rounds=5 + bench_matmul [n=100] wall-time effect -62.84% noise 4.98% rounds=5 + bench_matmul [n=200] wall-time effect -38.61% noise 3.37% rounds=5 + +NO CHANGE DETECTED (1) + bench_matmul [n=10] wall-time effect -1.37% noise 4.04% rounds=5 + +For local/gonzales xp='numpy' [dirty tree] (5 rounds): +bench_matmul ok + ===== ============ + n + ----- ------------ + 10 2.95±0.2μs + 50 17.1±2μs + 100 48.9±5μs + 200 157±20μs + ===== ============ + +For local/gonzales xp='torch' [dirty tree] (5 rounds): +bench_matmul ok + ===== ============ + n + ----- ------------ + 10 2.84±0.1μs + 50 6.53±0.2μs + 100 16.3±4μs + 200 96.0±2μs + ===== ============ + +| Change | Before ['numpy'] | After ['torch'] | Ratio | Noise | Verdict | Benchmark (Parameter) | +|----------|--------------------|-------------------|---------|---------|--------------------|-------------------------| +| | 2.95±0.2μs | 2.84±0.1μs | 0.96 | 4.04% | no change detected | bench_matmul(10) | +| - | 17.1±2μs | 6.53±0.2μs | 0.38 | 1.15% | improved | bench_matmul(50) | +| - | 48.9±5μs | 16.3±4μs | 0.33 | 4.98% | improved | bench_matmul(100) | +| - | 157±20μs | 96.0±2μs | 0.61 | 3.37% | improved | bench_matmul(200) | +``` + +which first repeats the same information it gave without `--tables`, and then emits +the summary tables. + + +### A manual loop + "read mode" comparisons. + +Above we used `bx compare` in the so-called *measure mode*, where it ran the benchmarks under the comparison schedule. An alternative, more +manual, way is to run a loop over `bx bench` calls and then invoke `bx compare` in the *read mode*, as before. + +For the first step, we need to handle alternating the sides manually: Each call runs one library, +with `--filter`, as one side of the session; we also need to specify the same run key for all calls, +via the `--run-key` argument. + +The previous `bx compare` call sequence used the `--rounds` argument to arrange the individual calls into +the comparison sequence. Here we manually assemble the comparison sequence `ABABABAB` using the +`--slots` argument (note how `numpy` runs are assigned even slots and `torch` runs are assigned the +odd slots) + +Taking this all together, we call + +``` +for r in 0 1 2 4; do + bx bench bench_matmul.py --filter "'numpy'" --run-key mm --round $r --slot $((2*r)) $QUICK + bx bench bench_matmul.py --filter "'torch'" --run-key mm --round $r --slot $((2*r+1)) $QUICK +done +``` + +The output (not shown) will be somewhat noisy because every `bx bench` call prints out its measurements. +Once the data is computed, we run the comparison in the run mode by specifying the `--run RUN_KEY` + +``` +$ bx compare --run mm --profile variants --vary xp --baseline "'numpy'" +``` + +The resulting output will be the same as the measure mode comparison (since we used quick-and-dirty settings, +results are not reliable and may thus differ though). + + +## Final remarks + +In the second part of this example, we demonstrated two ways of running a comparison: the *measurement* mode, +where `bx compare` runs benchmarks itself, and the *read* mode, where we run benchmarks in a manual loop. +Why would one use the second variant over the measurement mode, as it looks to be more work for no gain? + +For the *variants* comparison it is indeed unnecessary. However, `benchx` supports several other *comparison profiles*: +`revisions` (where you run comparisons across the history of a project) and `environments` (where you hand +`bx compare` two prepared virtual environments). These kinds of tasks involve building the project or activating +environments---and `benchx` does not do either. This is where the run mode comparisons come in handy. See the +[`pandas-asv` worked example](https://github.com/benchx-dev/benchx_examples/tree/main/examples/pandas-asv) for an +end-to-end demo. diff --git a/examples/matmul-params/bench_matmul.py b/examples/matmul-params/bench_matmul.py new file mode 100644 index 0000000..7b37e42 --- /dev/null +++ b/examples/matmul-params/bench_matmul.py @@ -0,0 +1,29 @@ +"""Example: one benchmark function, eight cases (4 sizes x 2 array libraries). + + bx bench bench_matmul.py # every combination + bx bench bench_matmul.py bench_matmul # the same, by name + bx bench bench_matmul.py "bench_matmul(100, 'torch')" # one combination + +`params` holds one list of values per argument of the function and `param_names` names +them; each combination is its own case. Values are recorded as their repr, so the +library is given by name and imported when first used. Both libraries use float64 +(torch would default to float32). +""" + +import functools +import importlib + + +@functools.cache +def operands(n, xp): + lib = importlib.import_module(xp) + return lib.ones((n, n), dtype=lib.float64), lib.ones((n, n), dtype=lib.float64) + + +def bench_matmul(n, xp): + a, b = operands(n, xp) + a @ b + + +bench_matmul.params = [[10, 50, 100, 200], ["numpy", "torch"]] +bench_matmul.param_names = ["n", "xp"] diff --git a/examples/matmul-params/benchx.conf.json b/examples/matmul-params/benchx.conf.json new file mode 100644 index 0000000..cfea181 --- /dev/null +++ b/examples/matmul-params/benchx.conf.json @@ -0,0 +1,4 @@ +{ + "schema_version": "benchx/config/0.1.0", + "paths": { "store": "out/home/store.parquet", "results": "out" } +} diff --git a/src/benchx/bench.py b/src/benchx/bench.py index 0d55084..60869a2 100644 --- a/src/benchx/bench.py +++ b/src/benchx/bench.py @@ -132,6 +132,13 @@ def render(rows, leading=()) -> str: return "\n".join([lines[0], " ".join("-" * w for w in widths), *lines[1:]]) +def split_caveats(rows) -> tuple[list[str], list[dict]]: + """The warnings every row carries (sorted, as `bx compare` lists them) and the rows without them, so that + `bx bench` says them once, above the table. A warning only some rows carry stays on those rows.""" + common = set.intersection(*(set(r["warnings"]) for r in rows)) if rows else set() + return sorted(common), [{**r, "warnings": [w for w in r["warnings"] if w not in common]} for r in rows] + + def failures(rows, names=3) -> str: """The section under the table for the cases that were not measured: what each said, `case: message`, cases with the same message as one line, `message (K cases: a, b, c, …)`. Empty when none has a message diff --git a/src/benchx/cli.py b/src/benchx/cli.py index 13660ba..a4d9e22 100644 --- a/src/benchx/cli.py +++ b/src/benchx/cli.py @@ -433,6 +433,36 @@ def _bench_target(args) -> tuple[str, str | None, str | None]: return target, suite, "pyperf" +def _compare_targets(args) -> tuple[list[str], str | None, str | None]: + """The targets, the suite they force (or None: --suite, then the file's), and the adapter + they force: the shorthand of `bx bench MODULE.py`, for each target. Without `--suite`, a + target that is a Python file is a module: its checkout is the target, its path in it the + suite, and the harness pyperf. The suite is one name for every side, so all the targets must + be Python files then, with the same path in their checkouts (or the same file, for variants).""" + modules = [t for t in args.targets if t.endswith(".py")] + if args.suite or not modules: + logger.debug("plain targets: %s, with the suite from --suite or the file's adapter.suite", args.targets) + return args.targets, None, None + if len(modules) != len(args.targets): + raise UsageError( + "a Python file is a target of the shorthand, so every target must be one; to compare trees, give --suite" + ) + if args.adapter not in (None, "pyperf"): + raise UsageError(f"a Python file is benchmarked with pyperf, not {args.adapter}") + logger.debug("the Python-module shorthand: %s are benchmarked with pyperf", modules) + try: + resolved = [bench_mod.module_target(module) for module in modules] + except session.SessionError as e: # `bx bench` reports it as an error in the arguments too + raise UsageError(str(e)) from None + suites = sorted({suite for _, suite in resolved}) + if len(suites) != 1: + raise UsageError( + f"the Python files have different paths in their checkouts ({', '.join(suites)}), " + "and the suite is one name for every side: give the trees as targets with --suite" + ) + return [target for target, _ in resolved], suites[0], "pyperf" + + def _common(cfg, args, *, forced_adapter=None, forced_suite=None) -> dict: """The settings `bx bench` and `bx compare` share, each from the command line, else the file, else its default (config.Config.pick); ConfigError when a @@ -460,7 +490,9 @@ def _common(cfg, args, *, forced_adapter=None, forced_suite=None) -> dict: if args.project and args.no_project: raise UsageError("give --project or --no-project, not both") timeouts = cfg.section("timeouts") - adapter, adapter_source = cfg.pick_with_source(given, block.get("name"), flag="--adapter", key="adapter.name") + adapter, adapter_source = cfg.pick_with_source( + given, block.get("name"), "pyperf", flag="--adapter", key="adapter.name" + ) named = block.get("name") if given and named and given != named: # the file's block serves another adapter of its family adapter_source += f"; the file says {named}, same family" @@ -615,9 +647,13 @@ def cmd_bench(args): return _refused(e) # What the run reports goes through the marker: stdout, by the tiers `-q` and `-qq` leave, and the log. rows = bench_mod.summarize(summary["files"]) - say.out(bench_mod.render(rows), log.TABLE) + caveats, shown = bench_mod.split_caveats(rows) + say.out((f"caveats: {', '.join(caveats)}\n" if caveats else "") + bench_mod.render(shown), log.TABLE) _report_unmeasured(rows) - say.out(f"\n{summary['results']} result(s) -> {summary['out']} (order {summary['order'][:19]})", log.SUMMARY) + say.out( + f"\n{summary['results']} result(s) -> {summary['out']} (order {summary['order'][:19]})\nrun-key: {run_key}", + log.SUMMARY, + ) if store is None: logger.info("ingest skipped (--no-ingest): the results are files only") return EXIT_OK @@ -751,9 +787,8 @@ def cmd_series(args): logger.info("no series%s", " matches the filter" if args.workload or args.quantity else " in the store") for s in listed: estimator = json.loads(s["estimator"])["method_version"] - print( - f"{s['fingerprint'][:12]} {s['project']} {s['workload']} {s['quantity']} [{s['unit']}] est={estimator}" - ) + unit = "" if s["unit"] == "1" else f" [{s['unit']}]" # a dimensionless quantity has no unit to write + print(f"{s['fingerprint'][:12]} {s['project']} {s['workload']} {s['quantity']}{unit} est={estimator}") return EXIT_OK @@ -820,7 +855,8 @@ def cmd_head(args): return EXIT_OK cells = [] for r in rows: - median = f"{r['median']:.6g} {r['unit']}" if r["median"] is not None else "-" + unit = "" if r["unit"] == "1" else f" {r['unit']}" # a dimensionless quantity has no unit to write + median = f"{r['median']:.6g}{unit}" if r["median"] is not None else "-" started = r["started_at"].strftime("%Y-%m-%d %H:%M:%S") labels = f" {r['labels']}" if r["labels"] else "" codes = warning_codes(json.loads(r["document"])) # such as dirty-subject-tree, as `--table` shows them @@ -838,6 +874,9 @@ def cmd_head(args): f"{r['project']}{labels}", ) ) + if cells: # the names of the columns above them, `row` right-aligned as its numbers are + names = ("started", "run-key", "workload", "quantity", "status", "median", "revision", "project") + cells.insert(0, (f"{'row':>5}", *names)) widths = [max([len(cell[i]) for cell in cells], default=0) for i in range(len(cells[0]))] if cells else [] for cell in cells: print(" ".join(text.ljust(width) for text, width in zip(cell, widths)).rstrip()) @@ -1000,11 +1039,12 @@ def _read(cfg, args, policy, sources): def _measure(cfg, args, policy, sources): """The workbench's session loop: run both sides, deliver, compare.""" try: # the check phase: nothing has run, and no folder exists yet - settings = _common(cfg, args) + targets, forced_suite, forced_adapter = _compare_targets(args) + settings = _common(cfg, args, forced_adapter=forced_adapter, forced_suite=forced_suite) session.check_harness( settings["adapter"], settings["flags"], settings["file_precision"], settings["quantities"] ) - _needs_provider(cfg, *args.targets) + _needs_provider(cfg, *targets) rounds, rounds_source = cfg.pick_with_source( args.rounds, cfg.section("compare").get("rounds"), session.ROUNDS, flag="--rounds", key="compare.rounds" ) @@ -1038,7 +1078,7 @@ def _measure(cfg, args, policy, sources): try: if policy["profile"] == "variants": doc = session.compare_variants( - *args.targets, + *targets, rounds=rounds, store=store, parameter=args.vary, @@ -1050,7 +1090,7 @@ def _measure(cfg, args, policy, sources): ) else: doc = session.compare_targets( - *args.targets, rounds=rounds, store=store, label=label, progress=say.info, **policy, **settings + *targets, rounds=rounds, store=store, label=label, progress=say.info, **policy, **settings ) except runner.Refused as e: return _refused(e) @@ -1238,7 +1278,7 @@ def _add_target_options(parser, command): """The options `bx bench` and `bx compare` (measure mode) share: the harness, its suite and cases, its precision flags, and where the results go.""" parser.add_argument( - "--adapter", choices=sorted(harnesses.HARNESSES), help="the harness (default: adapter.name; required)" + "--adapter", choices=sorted(harnesses.HARNESSES), help="the harness (default: adapter.name, else pyperf)" ) parser.add_argument( "--suite", @@ -1508,7 +1548,13 @@ def main(argv=None): "benchmark parameter (--vary), as in TARGET --profile variants --suite NAME " "--rounds R.", ) - p.add_argument("targets", nargs="*", metavar="TARGET", help="measure mode: BASELINE CONTENDER (variants: TARGET)") + p.add_argument( + "targets", + nargs="*", + metavar="TARGET", + help="measure mode: BASELINE CONTENDER (variants: TARGET); with no --suite, Python files " + "(as in bx bench MODULE.py): each one's checkout is the target, its path the suite", + ) p.add_argument("--profile", choices=list(compare_mod.PROFILES), help="default: compare.profile") p.add_argument( "--vary", diff --git a/src/benchx/compare.py b/src/benchx/compare.py index 0240349..fc671f3 100644 --- a/src/benchx/compare.py +++ b/src/benchx/compare.py @@ -396,7 +396,7 @@ def render(doc: dict) -> str: params, sides = doc["selector"]["params"], doc.get("sides", {}) if sides and "run_key" in params and "profile" in params: header = ( - f"run {params['run_key']} profile {params['profile']} " + f"run-key {params['run_key']} profile {params['profile']} " f"baseline {str(sides['baseline'])[:12]} contender {str(sides.get('contender'))[:12]}" ) else: # another selector, such as one with sides of its own (reference and target) @@ -420,8 +420,13 @@ def render(doc: dict) -> str: shown = ", ".join(dotted(p) for p in differs[:6]) lines.append(f" differs: {shown}" + (f" (+{len(differs) - 6} more)" if len(differs) > 6 else "")) caveats = sorted({c for u in doc["units"] for c in u.get("caveats", [])}) - if caveats: - lines.append(f" caveats: {', '.join(caveats)}") + if caveats: # one line a side (`baseline: a, b`), the labels in one column; a caveat of no side comes after + by_side = {} + for caveat in caveats: + side, colon, what = caveat.partition(": ") + by_side.setdefault(side if colon else "", []).append(what if colon else caveat) + rows = [f"{side}: {', '.join(what)}" if side else ", ".join(what) for side, what in by_side.items()] + lines += [(" caveats: " if i == 0 else " " * 11) + row for i, row in enumerate(rows)] for section in ( "regressed", "improved", diff --git a/src/benchx/tables.py b/src/benchx/tables.py index d227957..68bac28 100644 --- a/src/benchx/tables.py +++ b/src/benchx/tables.py @@ -75,8 +75,9 @@ def human(value, spread, unit) -> str: spread to 1. Any other unit is written after the number.""" if value is None or value != value: return "n/a" - if unit != "s": - return _float(value, 3) + (f"±{_float(spread, 1, 2)}" if spread is not None else "") + f" {unit}" + if unit != "s": # a dimensionless quantity (unit `1`) has no unit to write + shown = _float(value, 3) + (f"±{_float(spread, 1, 2)}" if spread is not None else "") + return shown if unit == "1" else f"{shown} {unit}" scale = spread if value == 0 and spread is not None else value units = TIME_UNITS if scale != 0 else (("s", 1), ("m", 60)) for (name, size), (_, bigger) in zip(units, units[1:]): diff --git a/tests/test_bench.py b/tests/test_bench.py index 65e491e..1085598 100644 --- a/tests/test_bench.py +++ b/tests/test_bench.py @@ -9,6 +9,7 @@ pytest.importorskip("pyperf") +from benchx import bench as bench_mod from benchx import cli, config, core, harnesses, session from benchx.errors import SessionError from benchx.store import Store @@ -92,6 +93,24 @@ def test_bench_command_runs_and_ingests(tree, capsys): assert levels(order["precision"]) == {"process": 2, "value": 2} +def test_the_warnings_every_case_carries_are_said_once_above_the_table(tree, capsys): + assert cli.main(["bench", "mod.py", "bench_a", "bench_b", "--run-key", "cav", *FAST]) == cli.EXIT_OK + lines = capsys.readouterr().out.splitlines() + assert lines[0] == "caveats: dirty-benchmark-tree, dirty-subject-tree" # the fixture's tree is dirty + assert lines[1].startswith("case ") and "[" not in "\n".join(lines[1:5]) # not in the status column + + +def test_a_warning_only_some_cases_carry_stays_on_their_rows(): + rows = [ + {"case": "a", "warnings": ["dirty-subject-tree", "dirty-benchmark-tree"]}, + {"case": "b", "warnings": ["dirty-subject-tree", "dirty-benchmark-tree", "setup-per-call-unbatched"]}, + ] + caveats, shown = bench_mod.split_caveats(rows) + assert caveats == ["dirty-benchmark-tree", "dirty-subject-tree"] + assert [r["warnings"] for r in shown] == [[], ["setup-per-call-unbatched"]] + assert bench_mod.split_caveats([]) == ([], []) + + def test_a_function_with_params_is_named_by_itself_or_by_one_combination(tree, capsys): (tree / "mod.py").write_text( textwrap.dedent(""" diff --git a/tests/test_bench_harnesses.py b/tests/test_bench_harnesses.py index f037a71..bf6ddd7 100644 --- a/tests/test_bench_harnesses.py +++ b/tests/test_bench_harnesses.py @@ -185,7 +185,7 @@ def test_precision_and_quantity_are_the_harnesss(build, tmp): (["BUILD", *GBENCH, "--processes", "2"], "google-benchmark takes no --processes"), (["BUILD", *GBENCH, "--loops", "5"], "google-benchmark takes no --loops"), (["BUILD", "--suite", "mod.py", "--adapter", "pyperf", "--repetitions", "3"], "pyperf takes no --repetitions"), - (["BUILD", "--suite", "mod.py"], "--adapter is required"), + (["BUILD", "--suite", "mod.py", "--repetitions", "3"], "pyperf takes no --repetitions"), # no --adapter: pyperf (["BUILD", *GBENCH, "--filter", "Quiet", QUIET], "case names or --filter"), (["BUILD", *GBENCH, "--tree", "t"], "--tree belongs to"), (["BUILD", "--adapter", "google-benchmark"], "--suite is required"), diff --git a/tests/test_comparator.py b/tests/test_comparator.py index 7b7f0df..5c33861 100644 --- a/tests/test_comparator.py +++ b/tests/test_comparator.py @@ -288,6 +288,13 @@ def test_both_sides_dirty_are_each_named(): doc = evaluate(dirty(dirty(run(), HEAD), BASE, "benchmark_dirty")) assert invariants(doc) == [] and doc["local_only"] is True assert doc["units"][0]["caveats"] == ["baseline: dirty-benchmark-tree", "contender: dirty-subject-tree"] + lines = compare.render(doc).splitlines() + assert lines[0].startswith("run-key ") + first = next(i for i, line in enumerate(lines) if "caveats:" in line) + assert lines[first : first + 2] == [ + " caveats: baseline: dirty-benchmark-tree", + " contender: dirty-subject-tree", # a line a side, the labels in one column + ] def test_clean_sides_are_not_local_only(): diff --git a/tests/test_compare_harnesses.py b/tests/test_compare_harnesses.py index f3d9efc..2a15cc3 100644 --- a/tests/test_compare_harnesses.py +++ b/tests/test_compare_harnesses.py @@ -26,9 +26,18 @@ (MEASURE + ["--adapter", "google-benchmark", "--processes", "2"], "google-benchmark takes no --processes"), (MEASURE + ["--adapter", "pyperf", "--repetitions", "3"], "pyperf takes no --repetitions"), (MEASURE + ["--repetitions", "3"], "pyperf takes no --repetitions"), - (["A", "B", "--profile", "revisions", "--suite", "s", "--rounds", "1"], "--adapter is required"), + ( + ["A", "B", "--profile", "revisions", "--suite", "s", "--rounds", "1", "--repetitions", "3"], + "pyperf takes no --repetitions", + ), # no --adapter: the default is pyperf (["A", "B", "--profile", "revisions", "--rounds", "1", "--adapter", "pyperf"], "--suite is required"), (["A", "B", "--suite", "s", "--rounds", "1", "--adapter", "pyperf"], "--profile is required"), + # the shorthand of `bx bench MODULE.py`: Python files with no --suite + ( + ["m.py", "--profile", "variants", "--rounds", "1", "--adapter", "google-benchmark"], + "benchmarked with pyperf", + ), + (["m.py", "B", "--profile", "revisions", "--rounds", "1"], "every target must be one"), (MEASURE + ["--project", "p", "--no-project"], "--project or --no-project"), (MEASURE + ["--quantity", "wall-time,wall-time"], "twice"), (MEASURE + ["-e", "NOEQUALS"], "-e wants NAME=VALUE"), @@ -278,6 +287,181 @@ def test_pyperf_bare_paths_are_working_trees(tmp, worktrees): assert order["target"]["path"] == str(worktrees["head"].resolve()) +# --- Python files as targets: the shorthand of `bx bench MODULE.py` ---------------------------- + +SHORTHAND_FAST = [ + "--rounds", + "2", + "--min-rounds", + "2", + "--processes", + "2", + "--values", + "2", + "--loops", + "20", + "--warmups", + "0", + "--no-ingest", +] + + +def orders_of(out): + """The orders of a run, without what is the run's own (its key and the order's id).""" + orders = [json.loads(path.read_text()) for path in sorted((out / "orders").glob("order-*.json"))] + for order in orders: + order.pop("work_order_id"), order.pop("run_key") + return orders + + +def test_python_files_as_targets_are_the_long_form_spelled_shorter(tmp, worktrees, monkeypatch): + """As for `bx bench`: the shorthand and the long form write the same orders. Two sides, two files.""" + pytest.importorskip("pyperf") + monkeypatch.chdir(tmp) + base, head = worktrees["base"], worktrees["head"] + case = ["--filter", harnesses.exact_filter(["f"])] # the default case set is bench_*/benchmark_* functions + assert ( + cli.main( + [ + "compare", + str(base), + str(head), + "--profile", + "revisions", + "--adapter", + "pyperf", + "--suite", + "mod.py", + *case, + *SHORTHAND_FAST, + "--run-key", + "l", + "--out", + str(tmp / "l"), + ] + ) + == cli.EXIT_OK + ) + assert ( + cli.main( + [ + "compare", + str(base / "mod.py"), + str(head / "mod.py"), + "--profile", + "revisions", + *case, + *SHORTHAND_FAST, + "--run-key", + "s", + "--out", + str(tmp / "s"), + ] + ) + == cli.EXIT_OK + ) + short, long = orders_of(tmp / "s"), orders_of(tmp / "l") + assert len(short) == 4 and short == long + assert short[0]["target"]["kind"] == "working_tree" and short[0]["suites"][0]["adapter"] == "pyperf" + + +def test_one_python_file_as_the_target_of_variants_is_the_long_form_spelled_shorter(tmp, monkeypatch): + pytest.importorskip("pyperf") + monkeypatch.chdir(tmp) + tree = variants_tree(tmp, VARIANTS) + variants = ["--profile", "variants", "--vary", "role", *SHORTHAND_FAST] + assert ( + cli.main( + [ + "compare", + str(tree), + *variants, + "--adapter", + "pyperf", + "--suite", + "mod.py", + "--run-key", + "l", + "--out", + str(tmp / "l"), + ] + ) + == cli.EXIT_OK + ) + assert ( + cli.main(["compare", str(tree / "mod.py"), *variants, "--run-key", "s", "--out", str(tmp / "s")]) == cli.EXIT_OK + ) + assert orders_of(tmp / "s") == orders_of(tmp / "l") and len(orders_of(tmp / "s")) == 4 + + +def test_with_no_adapter_given_a_tree_and_a_suite_are_benchmarked_with_pyperf(tmp, monkeypatch): + """`bx compare TREE --suite NAME` with no --adapter and no adapter.name in a config: pyperf, as `bx bench`.""" + pytest.importorskip("pyperf") + monkeypatch.chdir(tmp) + tree = variants_tree(tmp, VARIANTS) + assert ( + cli.main( + [ + "compare", + str(tree), + "--profile", + "variants", + "--vary", + "role", + "--suite", + "mod.py", + *SHORTHAND_FAST, + "--run-key", + "d", + "--out", + str(tmp / "d"), + ] + ) + == cli.EXIT_OK + ) + assert {o["suites"][0]["adapter"] for o in orders_of(tmp / "d")} == {"pyperf"} + + +def test_python_files_with_different_paths_in_their_checkouts_are_refused_before_anything_runs(tmp, worktrees, capsys): + base, head = worktrees["base"], worktrees["head"] + (head / "other.py").write_text("def f():\n pass\n") + assert ( + cli.main( + [ + "compare", + str(base / "mod.py"), + str(head / "other.py"), + "--profile", + "revisions", + "--rounds", + "1", + "--out", + str(tmp / "out"), + ] + ) + == cli.EXIT_REFUSED + ) + assert "different paths in their checkouts (mod.py, other.py)" in capsys.readouterr().err + assert not (tmp / "out").exists() + + +def test_a_missing_python_file_is_refused_as_it_is_for_bench(tmp, monkeypatch, capsys): + monkeypatch.chdir(tmp) + assert cli.main(["compare", "nosuch.py", "--profile", "variants", "--rounds", "1"]) == cli.EXIT_REFUSED + assert "bx compare: error: no such module" in capsys.readouterr().err # bench: "bx bench: error: no such module" + + +def test_the_files_adapter_is_the_only_one_the_shorthand_fits(tmp, monkeypatch, capsys): + """The same refusal as `bx bench mod.py` gives, from the same check.""" + monkeypatch.chdir(tmp) + (tmp / "benchx.conf.json").write_text( + json.dumps({"schema_version": "benchx/config/0.1.0", "adapter": {"name": "google-benchmark", "suite": "demo"}}) + ) + (tmp / "mod.py").write_text("def bench_a():\n pass\n") + assert cli.main(["compare", "mod.py", "--profile", "variants", "--rounds", "1"]) == cli.EXIT_REFUSED + assert "adapter.name to 'google-benchmark'" in capsys.readouterr().err + + # --- variants: one target, the two values of one parameter (UC-02) ------------------------------ VARIANTS = textwrap.dedent(""" diff --git a/tests/test_execute_markdown.py b/tests/test_execute_markdown.py index 6cbf9f8..ab75811 100644 --- a/tests/test_execute_markdown.py +++ b/tests/test_execute_markdown.py @@ -92,7 +92,8 @@ def test_a_json_fence_after_a_heading_or_of_another_language_is_not_a_snapshot(r def test_noexec_unlabelled_and_other_fences_are_kept_and_not_run(repo): text = "```sh noexec\nexit 1\n```\n\n```\n$ pip install x\n```\n\n```json\n{}\n```\n" - assert page_of(repo, text) == text # `exit 1` would have failed the run + # `exit 1` would have failed the run; the page has no `noexec` (the site's fence parser takes none) + assert page_of(repo, text) == text.replace("sh noexec", "sh") def test_a_readme_with_no_executable_block_is_copied(repo, capsys): @@ -161,7 +162,7 @@ def test_a_block_marked_exit_is_expected_to_fail_and_the_run_goes_on(repo): def test_the_marker_is_left_out_of_every_fence_of_the_page_and_the_fence_is_kept_as_it_was(repo): page = page_of(repo, "~~~sh exit=2\nexit 2\n~~~\n\n```sh noexec exit=1\nexit 1\n```\n") - assert page == "~~~sh\nexit 2\n~~~\n\n```sh noexec\nexit 1\n```\n" # a noexec block is not run, so not checked + assert page == "~~~sh\nexit 2\n~~~\n\n```sh\nexit 1\n```\n" # a noexec block is not run, so not checked @pytest.mark.parametrize( diff --git a/tests/test_logging.py b/tests/test_logging.py index 9f7cdf8..25b54d1 100644 --- a/tests/test_logging.py +++ b/tests/test_logging.py @@ -436,7 +436,8 @@ def test_stop_hands_the_logger_back_to_the_root_not_to_a_fixed_level(): def test_a_refused_comparison_does_not_print_the_store_path(tmp, capsys): assert ( - cli.main(["compare", "A", "B", "--profile", "revisions", "--suite", "s", "--rounds", "3"]) == cli.EXIT_REFUSED - ) # no adapter + cli.main(["compare", "A", "B", "--profile", "revisions", "--suite", "s", "--rounds", "3", "--repetitions", "3"]) + == cli.EXIT_REFUSED + ) # pyperf, the default adapter, takes no --repetitions err = capsys.readouterr().err - assert "--adapter is required" in err and "store.parquet" not in err and "store.jsonl" not in err + assert "pyperf takes no --repetitions" in err and "store.parquet" not in err and "store.jsonl" not in err diff --git a/tests/test_logging_quiet.py b/tests/test_logging_quiet.py index 9ba210a..c805679 100644 --- a/tests/test_logging_quiet.py +++ b/tests/test_logging_quiet.py @@ -61,7 +61,8 @@ def test_q_leaves_the_failures_and_the_result_line_and_no_table(build, capsys): assert HEADER not in out and "" not in lines # no table, and no spacing between what is left assert lines[0] == "not measured (2)" and lines[1].startswith(" BM_Broken: ") assert lines[2].startswith(" BM_Skipped: ") - assert re.fullmatch(r"\d+ result\(s\) -> \S+ \(order sha256:\w+\)", lines[3]) and len(lines) == 4 + assert re.fullmatch(r"\d+ result\(s\) -> \S+ \(order sha256:\w+\)", lines[3]) and lines[4] == "run-key: r1" + assert len(lines) == 5 assert re.fullmatch(START + "\n", err) # on stderr, the start line: not the progress line or the ingest line @@ -80,8 +81,8 @@ def test_qq_on_a_run_that_succeeded_is_silent(clean, capsys): def test_q_on_a_run_that_succeeded_is_a_start_line_and_a_result_line(clean, capsys): code, out, err = bench(clean, capsys, "-q", *POSITION) lines = out.splitlines() - assert code == cli.EXIT_OK and re.fullmatch(START + "\n", err) and len(lines) == 1 - assert "result(s) ->" in lines[0] + assert code == cli.EXIT_OK and re.fullmatch(START + "\n", err) and len(lines) == 2 + assert "result(s) ->" in lines[0] and lines[1] == "run-key: r1" def test_the_start_line_says_where_a_call_sits_and_what_it_measures(clean, capsys): diff --git a/tests/test_prototype.py b/tests/test_prototype.py index 38940f7..454a06d 100644 --- a/tests/test_prototype.py +++ b/tests/test_prototype.py @@ -253,7 +253,7 @@ def test_revisions_labels_a_dirty_side_local_only(repo, tmp): assert {"contender: dirty-subject-tree", "contender: dirty-benchmark-tree"} <= caveats assert not any(c.startswith("baseline:") for c in caveats) # the clean side is not named shown = compare.render(doc) - assert "[local-only]" in shown and "contender: dirty-subject-tree" in shown + assert "[local-only]" in shown and "contender: dirty-benchmark-tree, dirty-subject-tree" in shown @requires_pyarrow @@ -336,8 +336,12 @@ def test_head_and_history_show_the_dirty_warnings(repo, tmp, capsys): assert cli.main(["head", "--table"]) == cli.EXIT_OK assert marker in capsys.readouterr().out assert cli.main(["head", "-n", "50"]) == cli.EXIT_OK - rows = capsys.readouterr().out.splitlines()[1:] + header, *rows = capsys.readouterr().out.splitlines()[1:] assert any(marker in row for row in rows) and any(marker not in row for row in rows) + names = ["row", "started", "run-key", "workload", "quantity", "status", "median", "revision", "project"] + assert header.split() == names and header.index("run-key") == rows[0].index("listed") # over its column + loads = [row.split() for row in rows if "load-average" in row] # dimensionless: the median has no unit + assert loads and all(cells[-4] == "success" for cells in loads) series = [ x for x in store.series(workload=QUIET, quantity="wall-time") if json.loads(x["estimator"]) == identity.MEDIAN ] diff --git a/tests/test_tables.py b/tests/test_tables.py index 8bb00a4..b2a0d4f 100644 --- a/tests/test_tables.py +++ b/tests/test_tables.py @@ -50,6 +50,8 @@ def evaluate(docs): (90.0, 3.0, "s", "1.50±0.05m"), (0.0, None, "s", "0s"), (1500.0, 20.0, "B", "1500±20 B"), + (2.5, None, "1", "2.5"), # a dimensionless quantity has no unit to write + (2.5, 0.1, "1", "2.5±0.1"), (None, None, "s", "n/a"), ], ) diff --git a/tests/test_uc04.py b/tests/test_uc04.py index 874694e..9e3d385 100644 --- a/tests/test_uc04.py +++ b/tests/test_uc04.py @@ -139,7 +139,9 @@ def test_a_failed_check_is_shown_in_the_comparison_and_changes_nothing_else(tree capsys.readouterr() code, out = compare(capsys) assert code == cli.EXIT_OK - caveats = next(line for line in out.splitlines() if line.strip().startswith("caveats:")) + lines = out.splitlines() + first = next(i for i, line in enumerate(lines) if line.strip().startswith("caveats:")) + caveats = "\n".join(lines[first : first + 2]) # a line a side assert "contender: collector-mismatch" in caveats # beside any dirty-tree caveats the fixture tree earns assert "baseline: collector-mismatch" not in out assert "failed invariants" not in out and "bench_a" in out diff --git a/tools/execute_markdown.py b/tools/execute_markdown.py index 5c98c76..9d3ae7f 100644 --- a/tools/execute_markdown.py +++ b/tools/execute_markdown.py @@ -13,11 +13,11 @@ page keeps it, as a prompt). - python fences: executed in one namespace shared by the whole file. - A language followed by `noexec` (```sh noexec) is not executed. +- The page has a fence without its `noexec` and `exit=1`: the site's fence parser takes neither. - A sh/bash fence that is meant to fail says so: ```sh exit=1. The block must end with exactly that status (a 0 fails the run as well as any other status), its output goes into the page as for any block, and the run goes on. The fence is one script run with -e, so the status is that - of the first command that fails and the commands after it do not run: put it last. The page - has the fence without its `exit=1`: the site's fence parser does not take a key=value there. + of the first command that fails and the commands after it do not run: put it last. Python fences have no such marker: one that raises fails the run. - A sh/bash fence that ends with status 0 must also leave no failed result in the example's store: `bx bench` exits 0 when a case fails, but it stores the result with its status. The @@ -118,14 +118,15 @@ def expected_status(attributes: list[str], language: str) -> int: def page_fence(fence_lines: list[str], token) -> list[str]: - """The lines of a fence as they go into the page: without its `exit=N`. + """The lines of a fence as they go into the page: without its `exit=N` and its `noexec`. - The site's fence parser (pymdownx.superfences) does not accept an unquoted key=value after the - language: it shows the fence as text, with the markup that follows it. The README keeps - `exit=N`, since that is what the runner reads; the page has no use for it. + The site's fence parser (pymdownx.superfences) does not accept a bare word or an unquoted key=value + after the language: it shows the fence as text, and pairs the closing fence with the next opening one, + so the markup that follows goes with it. The README keeps them, since that is what the runner reads; + the page has no use for them. """ parts = token.info.strip().split() - kept = [part for part in parts if not part.startswith("exit=")] + kept = [part for part in parts if not part.startswith("exit=") and part != "noexec"] if len(kept) == len(parts): return fence_lines