pytest-jax-bench 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jens Stücker
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,257 @@
1
+ Metadata-Version: 2.4
2
+ Name: pytest-jax-bench
3
+ Version: 0.5.0
4
+ Summary: Pytest plugin to profile jitted JAX functions (compile time, runtime, memory).
5
+ Author-email: Jens Stücker <jens.stuecker@univie.ac.at>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/jstuecker/pytest-jax-bench
8
+ Project-URL: Issues, https://github.com/jstuecker/pytest-jax-bench/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: pytest>=7
15
+ Requires-Dist: jax>=0.4.26
16
+ Requires-Dist: numpy>=1.24
17
+ Requires-Dist: nvtx
18
+ Provides-Extra: plot
19
+ Requires-Dist: matplotlib>=3.6; extra == "plot"
20
+ Requires-Dist: graphviz>=0.20; extra == "plot"
21
+ Dynamic: license-file
22
+
23
+ # pytest-jax-bench
24
+ A pytest plugin to benchmark memory usage, compilation time and run time of jitted JAX functions. This code is inspired by [pytest-benchmark](https://pytest-benchmark.readthedocs.io/en/latest/). It has only been tested on GPU with jax=0.7.2 and CUDA13 so far.
25
+
26
+ ## Installation
27
+ First install [jax](https://docs.jax.dev/en/latest/installation.html) with GPU support and then...
28
+
29
+ ```bash
30
+ pip install -e .[plot] # With optional plotting support (requires matplotlib)
31
+ pip install -e . # In general
32
+ ```
33
+ If you don't want to edit the project, you can skip the "-e"
34
+
35
+ ## Usage
36
+
37
+ Define a [pytest](https://docs.pytest.org/en/stable/index.html) unit test, e.g. in a file "tests/test_benchmark.py":
38
+ ```python
39
+ import jax
40
+ import jax.numpy as jnp
41
+
42
+ def fft(x): # An example function we want to profile
43
+ return jnp.fft.ifftn(jnp.fft.fftn(x))
44
+
45
+ def test_fft(jax_bench): # jax_bench is a fixture that creates a JaxBench object.
46
+ x = jnp.ones((256, 256, 256), dtype=jnp.float32)
47
+
48
+ jb = jax_bench(jit_rounds=20, jit_loops=1, jit_warmup=1, eager_rounds=10, eager_warmup=1)
49
+ jb.measure(fn=fft, fn_jit=jax.jit(fft), x=x)
50
+ ```
51
+ Then simply run your tests as usual with [pytest](https://docs.pytest.org/en/stable/getting-started.html). E.g.
52
+ ```
53
+ pytest -v
54
+ ```
55
+ The benchmark results will only be displayed if you use the "-v" (verbose) option. However, they will always be saved to a ".csv" file in a simple to read table -- by default in the `.benchmarks` directory.
56
+
57
+ The `jb.measure` call in the example above will take the following steps:
58
+
59
+ * An eager execution warmup run using `fn`
60
+ * Save the measured peak memory usage. (This measurement has additional requirements as discussed below.)
61
+ * Average the run-time of eager execution over 10 runs using `fn`.
62
+ * Compile the jitted function using `fn_jit`
63
+ * Save the predicted memory usage of the jitted function (including peak memory, temporary memory and memory used by folded constants)
64
+ * Average the run-time of the jitted function over 20 runs, using `fn_jit`
65
+
66
+ Different stages can be skipped by setting the measurement parameters to 0 or by not passing `fn` or `fn_jit`.
67
+
68
+ ## jit_loops
69
+ The `jit_loops` parameter can be used to improve profiling -- especially of functions that have a large launch or synchronization overhead. When it is > 1, we will run a compiled for loop with `jit_loops` iterations `jit_rounds`+ `jit_warmup` times. The profiling will still calculate the average run time per call, but each individual measurement will already be averaged of the inner loop iterations so that this gives more accurate results per sample.
70
+
71
+ ### Eager exeuction memory
72
+
73
+ So far I didn't find a reliable way to measure the eager execution peak-memory usage that does not require restarting the measuring process. Therefore, this part of the measurement will be invalid unless you execute with the `--forked` flag provided by `pytest-forked`
74
+ ```bash
75
+ #pip install pytest-forked # If you didn't install it already
76
+ pytest --forked
77
+ ```
78
+ However, this may significantly slow down execution and create a bunch of other problems. So I don't recommend using this, unless you really need an eager-memory report.
79
+
80
+ ### Optional parameters
81
+ All the optional parameters are listed in ```pytest --help```. Since the help file can be a bit overwhelming, you can specifically find all the options defined by pytest-jax-bench (ptjb) as follows:
82
+ ```bash
83
+ pytest --help | grep ptjb -A 2
84
+ ```
85
+
86
+ ### Alternative usage:
87
+ Fixtures in pytest don't go too well with syntax highlighting. If you want proper code completion, you can also create the `JaxBench` object explicitly in your unit test, leading to the exact same result.
88
+ ```python
89
+ from pytest_jax_bench import JaxBench
90
+
91
+ def test_fft_alt(request):
92
+ x = jnp.ones((256, 256, 256), dtype=jnp.float32)
93
+
94
+ jb = JaxBench(request, jit_rounds=20, jit_warmup=1, eager_rounds=10, eager_warmup=1)
95
+ jb.measure(fn_jit=jax.jit(fft), x=x)
96
+ ```
97
+ > Note: We still need to pass the `request` fixture to the JaxBench object.
98
+
99
+ ### Tags
100
+ It is possible to do several measurements inside of the same test if you provide a tag to each run:
101
+ ```python
102
+ def rfft(x):
103
+ return jnp.fft.irfftn(jnp.fft.rfftn(x*2.))
104
+
105
+ def fft(x):
106
+ return jnp.fft.ifftn(jnp.fft.fftn(x*2.))
107
+
108
+ def test_tags(request):
109
+ x = jnp.ones((256, 256, 256), dtype=jnp.float32)
110
+
111
+ jb = JaxBench(request, jit_rounds=10, jit_warmup=1, eager_rounds=5, eager_warmup=1)
112
+
113
+ jb.measure(fn=fft, fn_jit=jax.jit(fft), x=x, tag="fft")
114
+ jb.measure(fn=rfft, fn_jit=jax.jit(rfft), x=x, tag="rfft")
115
+ ```
116
+ So far, this doesn't support eager memory at all (even when using `--forked`)
117
+
118
+ In this case tests with several tags will be saved to the same file and they will be plotted together by default. Note that the plots skip some less relevant aspects in this case to keep it simple.
119
+
120
+ ### Usage outside of pytest
121
+ You can also use the benchmark class independently of pytest:
122
+ ```python
123
+ from pytest_jax_bench import JaxBench
124
+
125
+ jb = JaxBench(jit_rounds=10, jit_warmup=2, eager_rounds=5, eager_warmup=1)
126
+ res, out = jb.measure(fn=rfft, fn_jit=jax.jit(rfft), x=x, write=False)
127
+ print(res)
128
+ ```
129
+
130
+ ### Examples:
131
+ For more examples check the [examples](tests/test_examples.py).
132
+
133
+ ## Outputs
134
+
135
+ Outputs of tests come in three different varieties. (1) Files (.csv) that log the results of the benchmarks (one per test). (2) The terminal output displayed if using "-v" (3) Overview plots that can be created optionally.
136
+
137
+ ### The .csv files
138
+
139
+ Each test creates a csv file in `--ptjb-output-dir` (defaults to `.benchmarks`) named after the nodeid of the test. For example this is the file ".benchmarks/tests:test_interface::test_full.csv" that was creates by running the unit tests in this directory several times:
140
+ ```
141
+ # pytest-jax-bench
142
+ # created: 2025-10-16T19:58:11Z
143
+ # test_nodeid: tests/test_interface.py::test_full
144
+ # backend: gpu
145
+ # device: NVIDIA GeForce RTX 4070 Laptop GPU
146
+ # First commit: 6bc9501
147
+ # (1) run_id
148
+ # (2) commit
149
+ # (3) commit_run
150
+ # (4) tag
151
+ # (5) compile_ms
152
+ # (6) jit_mean_ms
153
+ # (7) jit_std_ms
154
+ # (8) eager_mean_ms
155
+ # (9) eager_std_ms
156
+ # (10) jit_peak_bytes
157
+ # (11) jit_constants_bytes
158
+ # (12) jit_temporary_bytes
159
+ # (13) eager_peak_bytes
160
+ # (14) jit_rounds
161
+ # (15) jit_warmup
162
+ # (16) eager_rounds
163
+ # (17) eager_warmup
164
+ # (1) (2) (3) (4) (5) (6) (7) (8) (9) (10) (11) (12) (13) (14) (15) (16) (17)
165
+ 0 6bc9501 0 base 40.65 1.11 0.46 0.78 0.51 25296896 4 8519680 33816576 10 2 5 1
166
+ 1 6bc9501+ 1 base 46.39 0.99 0.49 1.01 0.52 25296896 4 8519680 33816576 10 2 5 1
167
+ 2 76640ba 0 base 43.14 1.14 0.41 0.85 0.57 25296896 4 8519680 33816576 10 2 5 1
168
+ 3 76640ba 1 base 43.19 0.91 0.49 0.54 0.02 25296896 4 8519680 33816576 10 2 5 1
169
+ [...]
170
+ ```
171
+ Each run creates a line in this table. The active git-commit is logged (a "+" indicates a "dirty" commit with some uncommited changes in the directory.) anda per-commit run-id is tracked additionally for convenience. If you want to work with the raw data of these ".csv" files you can use
172
+ ```python
173
+ from pytest_jax_bench import load_bench_data
174
+ data = load_bench_data(".benchmarks/tests:test_interface::test_full.csv")
175
+ ```
176
+ This reads the data into a [numpy structured array](https://numpy.org/doc/stable/user/basics.rec.html) that you can easily index with strings, e.g.
177
+ ```python
178
+ print(data[-2:]["commit"], data[-2:]["jit_mean_ms"], "+-", data[-2:]["jit_std_ms"])
179
+ ```
180
+ to print the last two runs' commit, average runtime and measurement uncertainty. Measurements may be set to "np.nan" for invalid timings or "-1" for invalid memory values.
181
+
182
+ ### The terminal output
183
+ If you run pytest with "-v" option you will get a terminal output similar to this:
184
+
185
+ ![pytest-jax-bench terminal example](assets/terminal_example.png)
186
+ <!-- ```
187
+ ===================================================== Pytest Jax Benchmark (PTJB) results ======================================================
188
+ Test C.Run Tag Compile(ms) Jit-Run(ms) Eager-Run(ms) Jit-Peak(MB) Eager-Peak(MB)
189
+ tests/test_interface.py::test_full 0->4 base 45.0->54.0 1.1->0.9+-0.7 0.7->0.8+-0.7 24.1->24.1 32.2->32.2
190
+ tests/test_interface.py::test_fixture 0->4 base 40.6->44.7 1.1->1.2+-0.6 1.2->1.0+-0.8 24.1->24.1 32.2->32.2
191
+ tests/test_interface.py::test_only_jit 0->4 base 46.1->48.5 0.7->1.2+-0.6 24.1->24.1
192
+ tests/test_interface.py::test_only_eager 0->4 base 0.8->0.8+-0.7 32.2->32.2
193
+ tests/test_interface.py::test_no_warmup 0->4 base 40.9->42.7 1.0->1.0+-0.7 1.0->0.8+-0.7 24.1->24.1 32.2->32.2
194
+ tests/test_interface.py::test_no_rounds 0->4 base 43.7->45.2 24.1->24.1 32.2->32.2
195
+ tests/test_interface.py::test_nothing 0->4 base 42.2->40.3 24.1->24.1
196
+ tests/test_interface.py::test_parameters[128] 0->4 base 40.9->38.5 1.0->1.1+-0.6 1.0->0.8+-0.7 24.1->24.1 32.2->32.2
197
+ tests/test_interface.py::test_parameters[256] 0->4 base 39.8->40.8 7.1->7.0+-0.1 6.4->6.5+-0.1 192->192 257->257
198
+ tests/test_tags.py::test_tags 0->4 fft 43.0->43.7 11.3->11.5+-0.4 11.9->11.9+-0.1 320->320 384->384
199
+ tests/test_tags.py::test_tags 0->4 rfft 40.5->39.8 5.9->6.0+-0.1 6.4->6.3+-0.2 192->192
200
+ ============================================================== 10 passed in 8.34s ==============================================================
201
+ ``` -->
202
+ (Irrelevant output columns may be ommitted.) Each result is compared to a previous run. For now, the comparison run is always the first run that was run within the same active commmit. The intended workflow is to run the benchmark on your clean commit once before you make any changes. Then afterwards you can repeat it frequently while you experiment with the code.
203
+
204
+ Results that may be particularly relevant are marked in green (improvement) or red (worsened). Benchmarks can fluctuate randomly so don't panic immediately if something flashes up red -- it just means that it *might* be worth your attention. Also be aware that functions with runtime <~ 1ms are not really well profiled (as you can see in the example above), due to the synchronization overhead -- so prefer to profile runs that take >~ 5 ms.
205
+
206
+ In the example at hand, you can see that I had improved the function that is called bin `test_tags` with a very significant reduction in run time and memory usage -- leading to a lot of green marks. However, you can also see that the compile time fluctuated sufficiently for two other tests and the run time for a third one to flash up in color.
207
+
208
+ ### Plotting results
209
+ You can create plots in two different ways:
210
+
211
+ * By directly passing `--ptjb-plot` to the `pytest` command
212
+ * By using the `ptjb-plot` command line tool (supporting the same + some additional options -- see `ptjb-plot --help`)
213
+
214
+ Depending on the chosen options, this will either create one big summary plot or an individual plot for each test. For example, this is how one of my individual plots looked, after I had "accidentally" increased the size of my FFT, then panicked and made it too small and finally reverted it to the correct state:
215
+ ![pytest-jax-bench plot example](assets/plot_example.png)
216
+
217
+ ### Custom plotting functions
218
+ You can define custom plotting functions as follows:
219
+ ```python
220
+ def custom_plot(data):
221
+ fig = plt.figure()
222
+ plt.xlabel("run_id")
223
+ plt.plot(data["run_id"], data["compile_ms"])
224
+ plt.ylabel("compile_ms")
225
+ return fig
226
+
227
+ @pytest.mark.ptjb(plot=custom_plot)
228
+ def test_with_custom_plot(jax_bench):
229
+ x = jnp.ones((128, 128, 128), dtype=jnp.float32)
230
+
231
+ jb = jax_bench(jit_rounds=10, jit_warmup=1)
232
+ jb.measure(fn_jit=jax.jit(rfft), x=x)
233
+ ```
234
+ The plot will be saved automatically in a reasonable path if a figure is returned, but of course you also have the option to save the figure yourself and not return anything.
235
+
236
+ For parameterized tests it is additionally possible to define a summary plot via `plot_summary`. In this case the data will contain the merged information of the tests with different parameters (`plot` would create one plot per parameter instead). For convenience it is also possible to set the `only_last` flag that will pre-filter the data, so that it only contains the result of the most recent run per parameter/tag.
237
+ ```python
238
+ def custom_plot_par(data):
239
+ fig = plt.figure()
240
+ plt.xlabel("n")
241
+ plt.ylabel("jit_mean_ms")
242
+ plt.plot(data["n"], data["jit_mean_ms"])
243
+ return fig
244
+
245
+ @pytest.mark.ptjb(plot_summary=custom_plot_par, only_last=True)
246
+ @pytest.mark.parametrize("n", [128, 170, 220, 270])
247
+ def test_pars_with_custom_plot(jax_bench, n):
248
+ x = jnp.ones((n, n, n), dtype=jnp.float32)
249
+
250
+ jb = jax_bench(jit_rounds=10, jit_warmup=1)
251
+ jb.measure(fn_jit=jax.jit(rfft), x=x)
252
+ ```
253
+
254
+
255
+ ### Plotting SVG Graphs
256
+ You can autocreate SVG graphs of your jitted function by passing the option "--ptjb-save-graph". A new run's graph will only be saved if it differs from the last saved graph. (The difference detection is a bit challenging and may be slightly noisy.) Be aware that some graphs may get quite large!
257
+ You can also toggle this per test by setting `@pytest.mark.ptjb(save_graph=True)`
@@ -0,0 +1,235 @@
1
+ # pytest-jax-bench
2
+ A pytest plugin to benchmark memory usage, compilation time and run time of jitted JAX functions. This code is inspired by [pytest-benchmark](https://pytest-benchmark.readthedocs.io/en/latest/). It has only been tested on GPU with jax=0.7.2 and CUDA13 so far.
3
+
4
+ ## Installation
5
+ First install [jax](https://docs.jax.dev/en/latest/installation.html) with GPU support and then...
6
+
7
+ ```bash
8
+ pip install -e .[plot] # With optional plotting support (requires matplotlib)
9
+ pip install -e . # In general
10
+ ```
11
+ If you don't want to edit the project, you can skip the "-e"
12
+
13
+ ## Usage
14
+
15
+ Define a [pytest](https://docs.pytest.org/en/stable/index.html) unit test, e.g. in a file "tests/test_benchmark.py":
16
+ ```python
17
+ import jax
18
+ import jax.numpy as jnp
19
+
20
+ def fft(x): # An example function we want to profile
21
+ return jnp.fft.ifftn(jnp.fft.fftn(x))
22
+
23
+ def test_fft(jax_bench): # jax_bench is a fixture that creates a JaxBench object.
24
+ x = jnp.ones((256, 256, 256), dtype=jnp.float32)
25
+
26
+ jb = jax_bench(jit_rounds=20, jit_loops=1, jit_warmup=1, eager_rounds=10, eager_warmup=1)
27
+ jb.measure(fn=fft, fn_jit=jax.jit(fft), x=x)
28
+ ```
29
+ Then simply run your tests as usual with [pytest](https://docs.pytest.org/en/stable/getting-started.html). E.g.
30
+ ```
31
+ pytest -v
32
+ ```
33
+ The benchmark results will only be displayed if you use the "-v" (verbose) option. However, they will always be saved to a ".csv" file in a simple to read table -- by default in the `.benchmarks` directory.
34
+
35
+ The `jb.measure` call in the example above will take the following steps:
36
+
37
+ * An eager execution warmup run using `fn`
38
+ * Save the measured peak memory usage. (This measurement has additional requirements as discussed below.)
39
+ * Average the run-time of eager execution over 10 runs using `fn`.
40
+ * Compile the jitted function using `fn_jit`
41
+ * Save the predicted memory usage of the jitted function (including peak memory, temporary memory and memory used by folded constants)
42
+ * Average the run-time of the jitted function over 20 runs, using `fn_jit`
43
+
44
+ Different stages can be skipped by setting the measurement parameters to 0 or by not passing `fn` or `fn_jit`.
45
+
46
+ ## jit_loops
47
+ The `jit_loops` parameter can be used to improve profiling -- especially of functions that have a large launch or synchronization overhead. When it is > 1, we will run a compiled for loop with `jit_loops` iterations `jit_rounds`+ `jit_warmup` times. The profiling will still calculate the average run time per call, but each individual measurement will already be averaged of the inner loop iterations so that this gives more accurate results per sample.
48
+
49
+ ### Eager exeuction memory
50
+
51
+ So far I didn't find a reliable way to measure the eager execution peak-memory usage that does not require restarting the measuring process. Therefore, this part of the measurement will be invalid unless you execute with the `--forked` flag provided by `pytest-forked`
52
+ ```bash
53
+ #pip install pytest-forked # If you didn't install it already
54
+ pytest --forked
55
+ ```
56
+ However, this may significantly slow down execution and create a bunch of other problems. So I don't recommend using this, unless you really need an eager-memory report.
57
+
58
+ ### Optional parameters
59
+ All the optional parameters are listed in ```pytest --help```. Since the help file can be a bit overwhelming, you can specifically find all the options defined by pytest-jax-bench (ptjb) as follows:
60
+ ```bash
61
+ pytest --help | grep ptjb -A 2
62
+ ```
63
+
64
+ ### Alternative usage:
65
+ Fixtures in pytest don't go too well with syntax highlighting. If you want proper code completion, you can also create the `JaxBench` object explicitly in your unit test, leading to the exact same result.
66
+ ```python
67
+ from pytest_jax_bench import JaxBench
68
+
69
+ def test_fft_alt(request):
70
+ x = jnp.ones((256, 256, 256), dtype=jnp.float32)
71
+
72
+ jb = JaxBench(request, jit_rounds=20, jit_warmup=1, eager_rounds=10, eager_warmup=1)
73
+ jb.measure(fn_jit=jax.jit(fft), x=x)
74
+ ```
75
+ > Note: We still need to pass the `request` fixture to the JaxBench object.
76
+
77
+ ### Tags
78
+ It is possible to do several measurements inside of the same test if you provide a tag to each run:
79
+ ```python
80
+ def rfft(x):
81
+ return jnp.fft.irfftn(jnp.fft.rfftn(x*2.))
82
+
83
+ def fft(x):
84
+ return jnp.fft.ifftn(jnp.fft.fftn(x*2.))
85
+
86
+ def test_tags(request):
87
+ x = jnp.ones((256, 256, 256), dtype=jnp.float32)
88
+
89
+ jb = JaxBench(request, jit_rounds=10, jit_warmup=1, eager_rounds=5, eager_warmup=1)
90
+
91
+ jb.measure(fn=fft, fn_jit=jax.jit(fft), x=x, tag="fft")
92
+ jb.measure(fn=rfft, fn_jit=jax.jit(rfft), x=x, tag="rfft")
93
+ ```
94
+ So far, this doesn't support eager memory at all (even when using `--forked`)
95
+
96
+ In this case tests with several tags will be saved to the same file and they will be plotted together by default. Note that the plots skip some less relevant aspects in this case to keep it simple.
97
+
98
+ ### Usage outside of pytest
99
+ You can also use the benchmark class independently of pytest:
100
+ ```python
101
+ from pytest_jax_bench import JaxBench
102
+
103
+ jb = JaxBench(jit_rounds=10, jit_warmup=2, eager_rounds=5, eager_warmup=1)
104
+ res, out = jb.measure(fn=rfft, fn_jit=jax.jit(rfft), x=x, write=False)
105
+ print(res)
106
+ ```
107
+
108
+ ### Examples:
109
+ For more examples check the [examples](tests/test_examples.py).
110
+
111
+ ## Outputs
112
+
113
+ Outputs of tests come in three different varieties. (1) Files (.csv) that log the results of the benchmarks (one per test). (2) The terminal output displayed if using "-v" (3) Overview plots that can be created optionally.
114
+
115
+ ### The .csv files
116
+
117
+ Each test creates a csv file in `--ptjb-output-dir` (defaults to `.benchmarks`) named after the nodeid of the test. For example this is the file ".benchmarks/tests:test_interface::test_full.csv" that was creates by running the unit tests in this directory several times:
118
+ ```
119
+ # pytest-jax-bench
120
+ # created: 2025-10-16T19:58:11Z
121
+ # test_nodeid: tests/test_interface.py::test_full
122
+ # backend: gpu
123
+ # device: NVIDIA GeForce RTX 4070 Laptop GPU
124
+ # First commit: 6bc9501
125
+ # (1) run_id
126
+ # (2) commit
127
+ # (3) commit_run
128
+ # (4) tag
129
+ # (5) compile_ms
130
+ # (6) jit_mean_ms
131
+ # (7) jit_std_ms
132
+ # (8) eager_mean_ms
133
+ # (9) eager_std_ms
134
+ # (10) jit_peak_bytes
135
+ # (11) jit_constants_bytes
136
+ # (12) jit_temporary_bytes
137
+ # (13) eager_peak_bytes
138
+ # (14) jit_rounds
139
+ # (15) jit_warmup
140
+ # (16) eager_rounds
141
+ # (17) eager_warmup
142
+ # (1) (2) (3) (4) (5) (6) (7) (8) (9) (10) (11) (12) (13) (14) (15) (16) (17)
143
+ 0 6bc9501 0 base 40.65 1.11 0.46 0.78 0.51 25296896 4 8519680 33816576 10 2 5 1
144
+ 1 6bc9501+ 1 base 46.39 0.99 0.49 1.01 0.52 25296896 4 8519680 33816576 10 2 5 1
145
+ 2 76640ba 0 base 43.14 1.14 0.41 0.85 0.57 25296896 4 8519680 33816576 10 2 5 1
146
+ 3 76640ba 1 base 43.19 0.91 0.49 0.54 0.02 25296896 4 8519680 33816576 10 2 5 1
147
+ [...]
148
+ ```
149
+ Each run creates a line in this table. The active git-commit is logged (a "+" indicates a "dirty" commit with some uncommited changes in the directory.) anda per-commit run-id is tracked additionally for convenience. If you want to work with the raw data of these ".csv" files you can use
150
+ ```python
151
+ from pytest_jax_bench import load_bench_data
152
+ data = load_bench_data(".benchmarks/tests:test_interface::test_full.csv")
153
+ ```
154
+ This reads the data into a [numpy structured array](https://numpy.org/doc/stable/user/basics.rec.html) that you can easily index with strings, e.g.
155
+ ```python
156
+ print(data[-2:]["commit"], data[-2:]["jit_mean_ms"], "+-", data[-2:]["jit_std_ms"])
157
+ ```
158
+ to print the last two runs' commit, average runtime and measurement uncertainty. Measurements may be set to "np.nan" for invalid timings or "-1" for invalid memory values.
159
+
160
+ ### The terminal output
161
+ If you run pytest with "-v" option you will get a terminal output similar to this:
162
+
163
+ ![pytest-jax-bench terminal example](assets/terminal_example.png)
164
+ <!-- ```
165
+ ===================================================== Pytest Jax Benchmark (PTJB) results ======================================================
166
+ Test C.Run Tag Compile(ms) Jit-Run(ms) Eager-Run(ms) Jit-Peak(MB) Eager-Peak(MB)
167
+ tests/test_interface.py::test_full 0->4 base 45.0->54.0 1.1->0.9+-0.7 0.7->0.8+-0.7 24.1->24.1 32.2->32.2
168
+ tests/test_interface.py::test_fixture 0->4 base 40.6->44.7 1.1->1.2+-0.6 1.2->1.0+-0.8 24.1->24.1 32.2->32.2
169
+ tests/test_interface.py::test_only_jit 0->4 base 46.1->48.5 0.7->1.2+-0.6 24.1->24.1
170
+ tests/test_interface.py::test_only_eager 0->4 base 0.8->0.8+-0.7 32.2->32.2
171
+ tests/test_interface.py::test_no_warmup 0->4 base 40.9->42.7 1.0->1.0+-0.7 1.0->0.8+-0.7 24.1->24.1 32.2->32.2
172
+ tests/test_interface.py::test_no_rounds 0->4 base 43.7->45.2 24.1->24.1 32.2->32.2
173
+ tests/test_interface.py::test_nothing 0->4 base 42.2->40.3 24.1->24.1
174
+ tests/test_interface.py::test_parameters[128] 0->4 base 40.9->38.5 1.0->1.1+-0.6 1.0->0.8+-0.7 24.1->24.1 32.2->32.2
175
+ tests/test_interface.py::test_parameters[256] 0->4 base 39.8->40.8 7.1->7.0+-0.1 6.4->6.5+-0.1 192->192 257->257
176
+ tests/test_tags.py::test_tags 0->4 fft 43.0->43.7 11.3->11.5+-0.4 11.9->11.9+-0.1 320->320 384->384
177
+ tests/test_tags.py::test_tags 0->4 rfft 40.5->39.8 5.9->6.0+-0.1 6.4->6.3+-0.2 192->192
178
+ ============================================================== 10 passed in 8.34s ==============================================================
179
+ ``` -->
180
+ (Irrelevant output columns may be ommitted.) Each result is compared to a previous run. For now, the comparison run is always the first run that was run within the same active commmit. The intended workflow is to run the benchmark on your clean commit once before you make any changes. Then afterwards you can repeat it frequently while you experiment with the code.
181
+
182
+ Results that may be particularly relevant are marked in green (improvement) or red (worsened). Benchmarks can fluctuate randomly so don't panic immediately if something flashes up red -- it just means that it *might* be worth your attention. Also be aware that functions with runtime <~ 1ms are not really well profiled (as you can see in the example above), due to the synchronization overhead -- so prefer to profile runs that take >~ 5 ms.
183
+
184
+ In the example at hand, you can see that I had improved the function that is called bin `test_tags` with a very significant reduction in run time and memory usage -- leading to a lot of green marks. However, you can also see that the compile time fluctuated sufficiently for two other tests and the run time for a third one to flash up in color.
185
+
186
+ ### Plotting results
187
+ You can create plots in two different ways:
188
+
189
+ * By directly passing `--ptjb-plot` to the `pytest` command
190
+ * By using the `ptjb-plot` command line tool (supporting the same + some additional options -- see `ptjb-plot --help`)
191
+
192
+ Depending on the chosen options, this will either create one big summary plot or an individual plot for each test. For example, this is how one of my individual plots looked, after I had "accidentally" increased the size of my FFT, then panicked and made it too small and finally reverted it to the correct state:
193
+ ![pytest-jax-bench plot example](assets/plot_example.png)
194
+
195
+ ### Custom plotting functions
196
+ You can define custom plotting functions as follows:
197
+ ```python
198
+ def custom_plot(data):
199
+ fig = plt.figure()
200
+ plt.xlabel("run_id")
201
+ plt.plot(data["run_id"], data["compile_ms"])
202
+ plt.ylabel("compile_ms")
203
+ return fig
204
+
205
+ @pytest.mark.ptjb(plot=custom_plot)
206
+ def test_with_custom_plot(jax_bench):
207
+ x = jnp.ones((128, 128, 128), dtype=jnp.float32)
208
+
209
+ jb = jax_bench(jit_rounds=10, jit_warmup=1)
210
+ jb.measure(fn_jit=jax.jit(rfft), x=x)
211
+ ```
212
+ The plot will be saved automatically in a reasonable path if a figure is returned, but of course you also have the option to save the figure yourself and not return anything.
213
+
214
+ For parameterized tests it is additionally possible to define a summary plot via `plot_summary`. In this case the data will contain the merged information of the tests with different parameters (`plot` would create one plot per parameter instead). For convenience it is also possible to set the `only_last` flag that will pre-filter the data, so that it only contains the result of the most recent run per parameter/tag.
215
+ ```python
216
+ def custom_plot_par(data):
217
+ fig = plt.figure()
218
+ plt.xlabel("n")
219
+ plt.ylabel("jit_mean_ms")
220
+ plt.plot(data["n"], data["jit_mean_ms"])
221
+ return fig
222
+
223
+ @pytest.mark.ptjb(plot_summary=custom_plot_par, only_last=True)
224
+ @pytest.mark.parametrize("n", [128, 170, 220, 270])
225
+ def test_pars_with_custom_plot(jax_bench, n):
226
+ x = jnp.ones((n, n, n), dtype=jnp.float32)
227
+
228
+ jb = jax_bench(jit_rounds=10, jit_warmup=1)
229
+ jb.measure(fn_jit=jax.jit(rfft), x=x)
230
+ ```
231
+
232
+
233
+ ### Plotting SVG Graphs
234
+ You can autocreate SVG graphs of your jitted function by passing the option "--ptjb-save-graph". A new run's graph will only be saved if it differs from the last saved graph. (The difference detection is a bit challenging and may be slightly noisy.) Be aware that some graphs may get quite large!
235
+ You can also toggle this per test by setting `@pytest.mark.ptjb(save_graph=True)`
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "pytest-jax-bench"
7
+ version = "0.5.0"
8
+ description = "Pytest plugin to profile jitted JAX functions (compile time, runtime, memory)."
9
+ readme = "README.md"
10
+ authors = [{ name = "Jens Stücker", email = "jens.stuecker@univie.ac.at" }]
11
+ license = "MIT"
12
+ license-files = ["LICEN[CS]E"]
13
+ requires-python = ">=3.9"
14
+ dependencies = [
15
+ "pytest>=7",
16
+ "jax>=0.4.26",
17
+ "numpy>=1.24",
18
+ "nvtx"
19
+ ]
20
+ classifiers = [
21
+ "Programming Language :: Python :: 3",
22
+ "Operating System :: OS Independent",
23
+ ]
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/jstuecker/pytest-jax-bench"
27
+ Issues = "https://github.com/jstuecker/pytest-jax-bench/issues"
28
+
29
+ [project.optional-dependencies]
30
+ plot = ["matplotlib>=3.6", "graphviz>=0.20"]
31
+
32
+ [project.entry-points.pytest11]
33
+ pytest_jax_bench = "pytest_jax_bench.plugin"
34
+
35
+ [project.scripts]
36
+ ptjb-plot = "pytest_jax_bench.cli_plot:main"
37
+
38
+ [tool.pytest.ini_options]
39
+ addopts = "-q"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,6 @@
1
+ __all__ = ["__version__"]
2
+ __version__ = "0.1.0"
3
+
4
+ from .data import BenchData, load_bench_data
5
+ from . import utils
6
+ from .plugin import JaxBench
@@ -0,0 +1,32 @@
1
+ """Command-line tool for plotting pytest-jax-bench results.
2
+
3
+ Usage examples:
4
+ pjax-plot -d .benchmarks
5
+ pjax-plot --bench-dir .benchmarks --save pdf --xaxis commit
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ from typing import Optional
11
+
12
+ from . import plots
13
+
14
+
15
+ def _parse_args(argv: Optional[list[str]] = None) -> argparse.Namespace:
16
+ p = argparse.ArgumentParser(prog="pjax-plot", description="Plot pytest-jax-bench results")
17
+ p.add_argument("-d", "--bench-dir", default=".benchmarks", help="Directory containing benchmark .csv files")
18
+ p.add_argument("-x", "--xaxis", choices=("commit", "run"), default="run", help="x-axis for plots")
19
+ p.add_argument("-s", "--save", choices=("png", "pdf"), default="png", help="Save plots to files (png/pdf) or 'show' to only show")
20
+ return p.parse_args(argv)
21
+
22
+
23
+ def main(argv: Optional[list[str]] = None) -> int:
24
+ args = _parse_args(argv)
25
+
26
+ plots.plot_all_benchmarks(bench_dir=args.bench_dir, xaxis=args.xaxis, save=args.save, trep="print")
27
+
28
+ return 0
29
+
30
+
31
+ if __name__ == "__main__":
32
+ raise SystemExit(main())