pytest-jax-bench 0.5.0__py3-none-any.whl

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,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())
@@ -0,0 +1,196 @@
1
+ from dataclasses import dataclass
2
+ import numpy as np
3
+ from numpy.lib import recfunctions as rfn
4
+ import os
5
+ import re
6
+
7
+ # ---------------------------
8
+ # Core measurement container
9
+ # ---------------------------
10
+
11
+ @dataclass
12
+ class BenchData:
13
+ run_id: int = 0
14
+ commit: str = "unknown"
15
+ commit_run: int = 0
16
+ tag: str = "base"
17
+ parameters: str = ""
18
+
19
+ compile_ms: float = float('nan')
20
+ jit_mean_ms: float = float('nan')
21
+ jit_std_ms: float = float('nan')
22
+ eager_mean_ms: float = float('nan')
23
+ eager_std_ms: float = float('nan')
24
+
25
+ jit_peak_bytes: int = -1
26
+ jit_constants_bytes: int = -1
27
+ jit_temporary_bytes: int = -1
28
+ eager_peak_bytes: int = -1
29
+
30
+ jit_rounds: int = 0
31
+ jit_warmup: int = 0
32
+ eager_rounds: int = 0
33
+ eager_warmup: int = 0
34
+
35
+ def get_column_header(self):
36
+ txt = ""
37
+ for i,name in enumerate(self.__dataclass_fields__):
38
+ txt += f"# {f'({i+1})':>4} {name}\n"
39
+ txt += "#"
40
+ for i,name in enumerate(self.__dataclass_fields__):
41
+ txt += f"{f'({i+1}) ':>12}"
42
+ return txt
43
+
44
+ def formatted_line(self) -> str:
45
+ line = ""
46
+ for i, field in enumerate(self.__dataclass_fields__.values()):
47
+ value = getattr(self, field.name)
48
+ if isinstance(value, (int, np.integer)):
49
+ fmt = f" {value:11d}"
50
+ elif isinstance(value, (float, np.floating)):
51
+ fmt = f" {value:11.2f}"
52
+ elif isinstance(value, (str, np.str_)):
53
+ fmt = f" {value:>11s}"
54
+ else:
55
+ raise TypeError(f"Unsupported type {type(value)} for field {field.name}")
56
+
57
+ line += fmt
58
+ return line
59
+
60
+ @classmethod
61
+ def data_type(cls) -> str:
62
+ """Return a numpy dtype string matching the fields of BenchData."""
63
+ fields = []
64
+ for f in cls.__dataclass_fields__.values():
65
+ if f.type == str:
66
+ fields.append((f.name, 'U32'))
67
+ else:
68
+ fields.append((f.name, np.dtype(f.type).str))
69
+ return np.dtype(fields)
70
+
71
+ # Precompiled once (module scope) — no matches for inf/nan variants
72
+ _INT_RE = re.compile(r'^[+-]?\d+$')
73
+ _FLOAT_RE = re.compile(r'^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$')
74
+
75
+ _LITERALS = {
76
+ "true": True,
77
+ "false": False,
78
+ "null": None,
79
+ "none": None,
80
+ }
81
+
82
+ def parse_best(s: str):
83
+ """
84
+ Convert a string to the 'most appropriate' Python type:
85
+ - "3" -> int
86
+ - "0.3" -> float (incl. 3., .3, 1e6)
87
+ - "true"/"false" -> bool (case-insensitive)
88
+ - "null"/"none" -> None
89
+ - everything else -> str
90
+ """
91
+ s = s.strip()
92
+ if s == "":
93
+ return s # keep empty strings as-is
94
+
95
+ lower = s.lower()
96
+
97
+ # Fast path for simple literals (O(1) dict lookup)
98
+ lit = _LITERALS.get(lower)
99
+ if lit is not None:
100
+ return lit
101
+
102
+ # Strict int: optional single leading sign, then digits only
103
+ if _INT_RE.fullmatch(s):
104
+ # no exceptions in the common path
105
+ return int(s)
106
+
107
+ # Strict float: decimal and/or exponent; excludes inf/nan by design
108
+ if _FLOAT_RE.fullmatch(s):
109
+ # float() here should not raise given the regex
110
+ return float(s)
111
+
112
+ return s
113
+
114
+ def encode_pardict(par_dict: dict) -> str:
115
+ """Encode a parameter dictionary as a string for storage in BenchData."""
116
+ if par_dict is None or len(par_dict) == 0:
117
+ return "None"
118
+ txt = ",".join([f"{k}-{v}" for k,v in par_dict.items()])
119
+ return txt
120
+
121
+ def decode_pardict(par_str: str) -> dict:
122
+ """Decode a parameter dictionary string from BenchData back into a dictionary."""
123
+ par_dict = {}
124
+ if par_str is None or par_str == "None" or par_str == "":
125
+ return par_dict
126
+
127
+ if par_str:
128
+ items = par_str.split(",")
129
+ for item in items:
130
+ k, v = item.split("-", 1)
131
+ par_dict[k] = parse_best(v)
132
+ return par_dict
133
+
134
+ def load_file_data(file: str, remove_dirty_mark=True, interprete_parameters=False) -> np.ndarray:
135
+ """Load benchmark data from a CSV file into a structured numpy array."""
136
+ try:
137
+ data = np.genfromtxt(file, dtype=BenchData.data_type(), comments="#", ndmin=1)
138
+ except ValueError as e:
139
+ raise ValueError(f"Found file with an outdated format. Best to recreate {file}: {e}")
140
+
141
+ if remove_dirty_mark:
142
+ data["commit"] = np.char.rstrip(data["commit"], "+")
143
+
144
+ if interprete_parameters:
145
+ pars = {}
146
+ for i in range(len(data)):
147
+ par_dict = decode_pardict(data["parameters"][i])
148
+ for k,v in par_dict.items():
149
+ if k not in pars:
150
+ pars[k] = []
151
+ pars[k].append(v)
152
+ for k in pars:
153
+ pars[k] = np.array(pars[k])
154
+ # create a structured data array with the parameters
155
+ # pars = np.core.records.fromarrays(list(pars.values()), names=list(pars.keys()))
156
+ if len(pars) == 0:
157
+ return data, None
158
+ else:
159
+ pars = np.rec.fromarrays(list(pars.values()), names=list(pars.keys()))
160
+ return data, pars
161
+
162
+ return data
163
+
164
+ def load_bench_data(file: str, remove_dirty_mark=True, interprete_parameters=False, merge_param=False) -> np.ndarray:
165
+ if os.path.isfile(file):
166
+ data, pars = load_file_data(file, remove_dirty_mark, interprete_parameters=True)
167
+ elif os.path.isdir(file):
168
+ all_data = []
169
+ all_par = []
170
+ for fname in os.listdir(file):
171
+ if fname.endswith(".csv"):
172
+ fpath = os.path.join(file, fname)
173
+ data, pars = load_file_data(fpath, remove_dirty_mark, interprete_parameters=True)
174
+ all_data.append(data)
175
+ all_par.append(pars)
176
+ if len(all_data) == 0:
177
+ raise FileNotFoundError(f"No CSV files found in directory {file}")
178
+
179
+ data = np.concatenate(all_data)
180
+ pars = np.concatenate(all_par)
181
+ else:
182
+ data, pars = None, None
183
+
184
+ if merge_param:
185
+ if pars is not None:
186
+ data = rfn.merge_arrays((data, pars), flatten=True, usemask=False)
187
+ return data
188
+ elif interprete_parameters:
189
+ return data, pars
190
+ else:
191
+ return data
192
+
193
+ def last_entries_with(data, keys=("tag",)):
194
+ pairs = data[list(keys)]
195
+ last_idx = len(data) - 1 - np.unique(pairs[::-1], return_index=True)[1]
196
+ return data[last_idx]
@@ -0,0 +1,241 @@
1
+ try:
2
+ import matplotlib.pyplot as plt
3
+ except ImportError:
4
+ raise ImportError("matplotlib is required for plotting. Please install it via "
5
+ "'pip install pytest-jax-bench[plot]' or 'pip install matplotlib'.")
6
+ import numpy as np
7
+ import os
8
+ from .data import load_bench_data, last_entries_with
9
+ import re
10
+ from numpy.lib import recfunctions as rfn
11
+
12
+ def get_commit_info(arr):
13
+ # First get each commit once. Note this will screw up the order, we'll fix it later
14
+ commits = np.sort(np.unique(arr["commit"]))
15
+
16
+ # per commit info
17
+ first_occ = np.array([np.min(np.where(arr["commit"] == c)[0]) for c in commits])
18
+ com_runs_tot = np.array([np.max(arr["commit_run"][arr["commit"] == c]) for c in commits])
19
+
20
+ # per run info
21
+ com_of_run = np.searchsorted(commits, arr["commit"])
22
+
23
+ # restore order
24
+ isort = np.argsort(first_occ)
25
+ inv = np.zeros(len(commits), dtype=int)
26
+ inv[isort] = np.arange(len(isort))
27
+
28
+ commits = commits[isort]
29
+ first_occ = first_occ[isort]
30
+ com_runs_tot = com_runs_tot[isort]
31
+ com_of_run = inv[com_of_run]
32
+
33
+ # add intra-commmit offset
34
+ com_of_run = com_of_run + arr["commit_run"] / (1 + com_runs_tot[com_of_run])
35
+
36
+ return commits, first_occ, com_runs_tot, com_of_run
37
+
38
+ def prepare_xaxis(data, xaxis="commit", ax=None):
39
+ if ax is None:
40
+ ax = plt.gca()
41
+
42
+ if xaxis == "run":
43
+ commits, first_occ, com_runs_tot, com_of_run = get_commit_info(data)
44
+
45
+ x = data["run_id"]
46
+
47
+ ax.set_xlabel("Run")
48
+
49
+ ax2 = ax.twiny()
50
+ ax2.set_xlim(0, len(data))
51
+ ax2.set_xticks(first_occ)
52
+ ax2.set_xticklabels(commits, fontsize=8, rotation=90)
53
+ elif xaxis == "commit":
54
+ commits, first_occ, com_runs_tot, com_of_run = get_commit_info(data)
55
+
56
+ x = com_of_run
57
+
58
+ ax.set_xlabel("Commit")
59
+ ax.set_xticks(np.arange(len(commits)), commits, rotation=90 if len(commits) > 10 else 0)
60
+ ax.grid("on")
61
+ elif xaxis == "tag":
62
+ uq_tag = np.unique(data["tag"])
63
+ last_of_tag = np.array([np.max(np.where(data["tag"] == t)[0]) for t in uq_tag])
64
+ data = data[last_of_tag]
65
+ x = np.arange(len(uq_tag))
66
+ # remove [] brackets for parameterized tests_
67
+ lean_tag = [re.sub(r"[\[\]]", "", t) for t in uq_tag]
68
+ tags_are_long = np.any([len(t) > 40/len(lean_tag) for t in lean_tag])
69
+ ax.set_xticks(np.arange(len(lean_tag)), lean_tag, rotation=90 if tags_are_long else 0)
70
+ elif xaxis in data.dtype.names:
71
+ ax.set_xlabel(xaxis)
72
+ x = data[xaxis]
73
+ if (np.max(x) / np.min(x) > 20) and np.all(x > 0):
74
+ ax.set_xscale("log")
75
+ else:
76
+ raise ValueError(f"Unknown xaxis {xaxis}, must be 'commit' or 'run'")
77
+
78
+ return x, ax, data
79
+
80
+ def plot_performance(data, title=None, xaxis="commit", ax=None):
81
+ x, ax, data = prepare_xaxis(data, xaxis=xaxis, ax=ax)
82
+
83
+ ax.set_title(title)
84
+ if np.any(data["jit_mean_ms"] > 0):
85
+ ax.plot(x, data["jit_mean_ms"], marker="o", label="jitted", alpha=0.8)
86
+ ax.fill_between(x, data["jit_mean_ms"]-data["jit_std_ms"], data["jit_mean_ms"]+data["jit_std_ms"], alpha=0.3)
87
+
88
+ if np.any(data["eager_mean_ms"] > 0):
89
+ ax.plot(x, data["eager_mean_ms"], marker="o", label="eager", alpha=0.8)
90
+ ax.fill_between(x, data["eager_mean_ms"]-data["eager_std_ms"], data["eager_mean_ms"]+data["eager_std_ms"], alpha=0.3)
91
+
92
+ ax.plot(x, data["compile_ms"], marker="o", label="compile", alpha=0.8)
93
+
94
+ ax.set_ylabel("Time (ms)")
95
+ ax.legend()
96
+ if np.any((data["jit_mean_ms"] > 0) | (data["eager_mean_ms"] > 0)):
97
+ ax.set_yscale("log")
98
+
99
+ return ax
100
+
101
+ def plot_performance_tagged(data, title=None, xaxis="commit", ax=None):
102
+ x, ax, data = prepare_xaxis(data, xaxis=xaxis, ax=ax)
103
+ ax.set_title(title)
104
+
105
+ tags = np.unique(data["tag"])
106
+ for i,tag in enumerate(tags):
107
+ data_t = data[data["tag"] == tag]
108
+ xt = x[data["tag"] == tag]
109
+
110
+ color = f"C{i}"
111
+ ax.plot(xt, data_t["jit_mean_ms"], marker="o", label=tag, alpha=0.8, color=color)
112
+ ax.fill_between(xt, data_t["jit_mean_ms"]-data_t["jit_std_ms"], data_t["jit_mean_ms"]+data_t["jit_std_ms"], alpha=0.6, color=color)
113
+
114
+ ax.plot(xt, data_t["eager_mean_ms"], marker="o", alpha=0.2, color=color, ls="dashed")
115
+ ax.fill_between(xt, data_t["eager_mean_ms"]-data_t["eager_std_ms"], data_t["eager_mean_ms"]+data_t["eager_std_ms"], alpha=0.2, color=color)
116
+
117
+ if np.any((data_t["jit_mean_ms"] > 0) | (data_t["eager_mean_ms"] > 0)):
118
+ ax.set_yscale("log")
119
+
120
+ if np.any(data["jit_mean_ms"] > 0) and np.any(data["eager_mean_ms"] > 0):
121
+ ax.plot([], [], label="jitted", color="k", marker="o", alpha=0.8)
122
+ ax.plot([], [], label="eager", color="k", marker="o", alpha=0.2, ls="dashed")
123
+
124
+ ax.set_ylabel("Time (ms)")
125
+ ax.legend()
126
+
127
+ return ax
128
+
129
+ def plot_memory_usage(data, title=None, xaxis="commit", ax=None):
130
+ x, ax, data = prepare_xaxis(data, xaxis=xaxis, ax=ax)
131
+
132
+ ax.set_title(title)
133
+ ax.plot(x, data["jit_peak_bytes"]/1024.**2, label="jit (peak)", marker="o", alpha=0.8)
134
+ if np.any(data["eager_peak_bytes"] >= 0):
135
+ ax.plot(x[data["eager_peak_bytes"]>=0], data["eager_peak_bytes"][data["eager_peak_bytes"]>=0]/1024.**2, label="eager (peak)", marker="o", alpha=0.8)
136
+
137
+ ax.plot(x, data["jit_temporary_bytes"]/1024.**2, label="jit (temp)", ls="dashed", marker="o", alpha=0.8)
138
+ if np.any(data["jit_constants_bytes"] > data["jit_peak_bytes"] * 0.01):
139
+ ax.plot(x, data["jit_constants_bytes"]/1024.**2, label="jit (const)", ls="dashed", marker="o", alpha=0.8)
140
+
141
+ ax.set_ylabel("Memory (MB)")
142
+ ax.legend()
143
+ if np.any((data["jit_peak_bytes"] > 0) | (data["eager_peak_bytes"] > 0)):
144
+ ax.set_yscale("log")
145
+
146
+ return ax
147
+
148
+ def plot_memory_usage_tagged(data, title=None, xaxis="commit", ax=None):
149
+ x, ax, data = prepare_xaxis(data, xaxis=xaxis, ax=ax)
150
+ ax.set_title(title)
151
+
152
+ tags = np.unique(data["tag"])
153
+ for i,tag in enumerate(tags):
154
+ data_t = data[data["tag"] == tag]
155
+ xt = x[data["tag"] == tag]
156
+ label = tag if tag != "base" else ""
157
+
158
+ color = f"C{i}"
159
+
160
+ ax.plot(xt, data_t["jit_peak_bytes"]/1024.**2, label=f"{label}", marker="o", alpha=0.8, color=color)
161
+ # So far, eager memory doesn't work well with tags. Disable for now.
162
+ # ax.plot(xt, data_t["eager_peak_bytes"]/1024.**2, marker="x", alpha=0.8, color=color, ls="dashed")
163
+ if np.any((data["jit_peak_bytes"] > 0) | (data["eager_peak_bytes"] > 0)):
164
+ ax.set_yscale("log")
165
+
166
+ ax.set_ylabel("Jit-Peak-Memory (MB)")
167
+ ax.legend()
168
+
169
+ return ax
170
+
171
+ def find_files(bench_dir="../.benchmarks"):
172
+ files = os.listdir(bench_dir)
173
+ files = [f for f in files if f.endswith(".csv")]
174
+ return [os.path.join(bench_dir, f) for f in files]
175
+
176
+ def create_and_save(data, path, xaxis="run", tagged=False, save="png", trep=None):
177
+ title = path.split("--")[-1] #.split(":")[-1]
178
+ fig, axs = plt.subplots(1, 2, figsize=(10, 4))
179
+ if tagged:
180
+ plot_performance_tagged(data, title=title, xaxis=xaxis, ax=axs[0])
181
+ plot_memory_usage_tagged(data, title=title, xaxis=xaxis, ax=axs[1])
182
+ else:
183
+ plot_performance(data, title=title, xaxis=xaxis, ax=axs[0])
184
+ plot_memory_usage(data, title=title, xaxis=xaxis, ax=axs[1])
185
+ try:
186
+ fig.tight_layout()
187
+ except UserWarning:
188
+ pass
189
+ fig.savefig(path + "." + save)
190
+ plt.close(fig)
191
+
192
+ if trep == "print":
193
+ print(f"Generated plot {path}.{save}")
194
+ elif trep is not None:
195
+ trep.write_line(f"Generated plot {path}.{save}")
196
+
197
+ def plot_normal_benchmark(path, xaxis="run", save="png", trep=None):
198
+ data = load_bench_data(path + ".csv")
199
+ if data is None: return
200
+
201
+ if len(np.unique(data["tag"])) > 1:
202
+ create_and_save(data, path=path, xaxis=xaxis, tagged=True, save=save, trep=trep)
203
+ create_and_save(data, path=path + "_xtag", xaxis="tag", tagged=False, save=save, trep=trep)
204
+ else:
205
+ create_and_save(data, path=path, xaxis=xaxis, tagged=False, save=save, trep=trep)
206
+
207
+ def plot_parametrized_benchmark(path, xaxis="commit", save="png", trep=None):
208
+ data, pars = load_bench_data(path, interprete_parameters=True)
209
+ if data is None: return
210
+
211
+ data_with_par = rfn.merge_arrays((data, pars), flatten=True, usemask=False)
212
+
213
+ for k in pars.dtype.names:
214
+ # Find the last locations of unique pairs of tag and k
215
+ data_sel = last_entries_with(data_with_par, keys=("tag", k))
216
+
217
+ if len(np.unique(data["tag"])) > 1:
218
+ create_and_save(data_sel, path=path + f"/{k}", xaxis=k, tagged=True, save=save, trep=trep)
219
+ else:
220
+ create_and_save(data_sel, path=path + f"/{k}", xaxis=k, tagged=False, save=save, trep=trep)
221
+
222
+ def plot_all_benchmarks(bench_dir="../.benchmarks", xaxis="commit", save="png", trep=None):
223
+ files = os.listdir(bench_dir)
224
+ files_csv = [f for f in files if f.endswith(".csv")]
225
+
226
+ dirs = [f for f in files if os.path.isdir(os.path.join(bench_dir, f))]
227
+ dirs_csv = []
228
+
229
+ for d in dirs:
230
+ sub_files = os.listdir(os.path.join(bench_dir, d))
231
+ sub_csv = [f for f in sub_files if f.endswith(".csv")]
232
+ files_csv.extend( [os.path.join(d, f) for f in sub_csv] )
233
+ if len(sub_csv) > 0:
234
+ dirs_csv.append(d)
235
+
236
+ for f in files_csv:
237
+ path = os.path.join(bench_dir, f.strip(".csv"))
238
+ plot_normal_benchmark(path, xaxis=xaxis, save=save, trep=trep)
239
+ for d in dirs_csv:
240
+ path = os.path.join(bench_dir, d)
241
+ plot_parametrized_benchmark(path, xaxis=xaxis, save=save, trep=trep)