mintchip 0.2.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.
- mintchip/__init__.py +101 -0
- mintchip/__main__.py +7 -0
- mintchip/chips/__init__.py +7 -0
- mintchip/chips/bar.py +233 -0
- mintchip/chips/ci.py +194 -0
- mintchip/chips/delta.py +164 -0
- mintchip/chips/dist.py +384 -0
- mintchip/chips/funnel.py +129 -0
- mintchip/chips/gauge.py +197 -0
- mintchip/chips/num.py +55 -0
- mintchip/chips/rank.py +182 -0
- mintchip/chips/ratio.py +141 -0
- mintchip/chips/share.py +164 -0
- mintchip/chips/spark.py +278 -0
- mintchip/chips/strip.py +173 -0
- mintchip/chips/timeline.py +257 -0
- mintchip/chips/waterfall.py +212 -0
- mintchip/cli.py +691 -0
- mintchip/diff.py +645 -0
- mintchip/directives.py +782 -0
- mintchip/doctor.py +145 -0
- mintchip/fmt.py +135 -0
- mintchip/guide.py +189 -0
- mintchip/ingest.py +725 -0
- mintchip/prose.py +225 -0
- mintchip/render/__init__.py +1 -0
- mintchip/render/html.py +295 -0
- mintchip/render/svg_base.py +337 -0
- mintchip/render/text_base.py +215 -0
- mintchip/scales.py +117 -0
- mintchip/skill.py +332 -0
- mintchip/spec.py +659 -0
- mintchip/tables.py +1043 -0
- mintchip/themes.py +102 -0
- mintchip-0.2.0.dist-info/METADATA +274 -0
- mintchip-0.2.0.dist-info/RECORD +39 -0
- mintchip-0.2.0.dist-info/WHEEL +4 -0
- mintchip-0.2.0.dist-info/entry_points.txt +2 -0
- mintchip-0.2.0.dist-info/licenses/LICENSE +21 -0
mintchip/diff.py
ADDED
|
@@ -0,0 +1,645 @@
|
|
|
1
|
+
"""Zero-dependency benchmark diffing for ``mintchip diff BASE HEAD``.
|
|
2
|
+
|
|
3
|
+
Compares two JSON, CSV, hyperfine, pytest-benchmark, Go benchmark, or Cargo benchmark runs
|
|
4
|
+
and renders a shared-scale ``mintchip table`` with base, head, ``delta``, and ``ci`` (when
|
|
5
|
+
intervals or samples exist) plus a one-line takeaway. Exits 1 if any regression exceeds
|
|
6
|
+
``--fail-on-regression PCT``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import csv
|
|
13
|
+
import html as _html
|
|
14
|
+
import json
|
|
15
|
+
import math
|
|
16
|
+
from collections.abc import Sequence
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
import mintchip as mc
|
|
21
|
+
|
|
22
|
+
from . import fmt as _fmt
|
|
23
|
+
from .ingest import (
|
|
24
|
+
_TIME_TO_SEC,
|
|
25
|
+
BenchEntry,
|
|
26
|
+
detect_format,
|
|
27
|
+
parse_cargo_bench,
|
|
28
|
+
parse_go_bench,
|
|
29
|
+
parse_hyperfine,
|
|
30
|
+
parse_pytest_bench,
|
|
31
|
+
pick_time_unit,
|
|
32
|
+
)
|
|
33
|
+
from .spec import ChipError
|
|
34
|
+
|
|
35
|
+
__all__ = [
|
|
36
|
+
"DiffResult",
|
|
37
|
+
"DiffRow",
|
|
38
|
+
"add_diff_parser",
|
|
39
|
+
"cmd_diff",
|
|
40
|
+
"diff_benchmarks",
|
|
41
|
+
"load_benchmark_entries",
|
|
42
|
+
"render_diff",
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
OUTPUT_FORMATS: tuple[str, ...] = ("text", "ansi", "md", "html", "json")
|
|
46
|
+
|
|
47
|
+
_HIGHER_HINTS = (
|
|
48
|
+
"acc",
|
|
49
|
+
"accuracy",
|
|
50
|
+
"throughput",
|
|
51
|
+
"ops",
|
|
52
|
+
"rps",
|
|
53
|
+
"qps",
|
|
54
|
+
"score",
|
|
55
|
+
"f1",
|
|
56
|
+
"pass",
|
|
57
|
+
"speed",
|
|
58
|
+
"fps",
|
|
59
|
+
"bandwidth",
|
|
60
|
+
"hit",
|
|
61
|
+
"recall",
|
|
62
|
+
"precision",
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True)
|
|
67
|
+
class DiffRow:
|
|
68
|
+
name: str
|
|
69
|
+
base: float
|
|
70
|
+
head: float
|
|
71
|
+
delta: float
|
|
72
|
+
pct_change: float
|
|
73
|
+
regression_pct: float
|
|
74
|
+
unit: str | None
|
|
75
|
+
ci: tuple[float, float] | None
|
|
76
|
+
higher_is_better: bool
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass(frozen=True)
|
|
80
|
+
class DiffResult:
|
|
81
|
+
table: mc.Table
|
|
82
|
+
rows: tuple[DiffRow, ...]
|
|
83
|
+
takeaway: str
|
|
84
|
+
regressions: tuple[DiffRow, ...]
|
|
85
|
+
fail_threshold: float | None
|
|
86
|
+
failed: bool
|
|
87
|
+
warnings: tuple[str, ...]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _infer_higher_is_better(metric_name: str | None, unit: str | None) -> bool:
|
|
91
|
+
if unit and unit.lower() in _TIME_TO_SEC:
|
|
92
|
+
return False
|
|
93
|
+
low = (metric_name or "").lower()
|
|
94
|
+
if any(tok in low for tok in ("time", "latency", "dur", "ms", "sec", "mem", "err", "loss")):
|
|
95
|
+
return False
|
|
96
|
+
return any(tok in low for tok in _HIGHER_HINTS)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _to_float(val: Any) -> float | None:
|
|
100
|
+
if isinstance(val, bool) or val is None:
|
|
101
|
+
return None
|
|
102
|
+
if isinstance(val, (int, float)):
|
|
103
|
+
f = float(val)
|
|
104
|
+
return f if math.isfinite(f) else None
|
|
105
|
+
if isinstance(val, str):
|
|
106
|
+
s = val.strip().replace(",", "")
|
|
107
|
+
if not s:
|
|
108
|
+
return None
|
|
109
|
+
try:
|
|
110
|
+
f = float(s)
|
|
111
|
+
return f if math.isfinite(f) else None
|
|
112
|
+
except ValueError:
|
|
113
|
+
return None
|
|
114
|
+
return None
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _parse_generic_json(text: str) -> list[BenchEntry]:
|
|
118
|
+
data = json.loads(text)
|
|
119
|
+
entries: list[BenchEntry] = []
|
|
120
|
+
|
|
121
|
+
if isinstance(data, dict):
|
|
122
|
+
for name, raw in data.items():
|
|
123
|
+
if isinstance(raw, (int, float)) and not isinstance(raw, bool):
|
|
124
|
+
entries.append(BenchEntry(name=str(name), value=float(raw)))
|
|
125
|
+
elif isinstance(raw, list) and raw and all(_to_float(x) is not None for x in raw):
|
|
126
|
+
xs = [float(x) for x in raw]
|
|
127
|
+
mean = sum(xs) / len(xs)
|
|
128
|
+
sd = (
|
|
129
|
+
math.sqrt(sum((x - mean) ** 2 for x in xs) / (len(xs) - 1))
|
|
130
|
+
if len(xs) >= 2
|
|
131
|
+
else None
|
|
132
|
+
)
|
|
133
|
+
entries.append(
|
|
134
|
+
BenchEntry(
|
|
135
|
+
name=str(name),
|
|
136
|
+
value=mean,
|
|
137
|
+
samples=tuple(xs) if len(xs) >= 2 else (),
|
|
138
|
+
stddev=sd,
|
|
139
|
+
n=len(xs),
|
|
140
|
+
)
|
|
141
|
+
)
|
|
142
|
+
elif isinstance(raw, dict):
|
|
143
|
+
entry = _entry_from_mapping(str(name), raw)
|
|
144
|
+
if entry is not None:
|
|
145
|
+
entries.append(entry)
|
|
146
|
+
elif isinstance(data, list):
|
|
147
|
+
for idx, item in enumerate(data):
|
|
148
|
+
if not isinstance(item, dict):
|
|
149
|
+
continue
|
|
150
|
+
entry = _entry_from_row(item, idx)
|
|
151
|
+
if entry is not None:
|
|
152
|
+
entries.append(entry)
|
|
153
|
+
|
|
154
|
+
if not entries:
|
|
155
|
+
raise ChipError(
|
|
156
|
+
"mintchip diff: could not extract benchmark rows from JSON.",
|
|
157
|
+
fix_hint=(
|
|
158
|
+
'Use hyperfine/pytest-bench JSON, [{"name": "a", "mean": 12.0}], '
|
|
159
|
+
'or {"a": 12.0}.'
|
|
160
|
+
),
|
|
161
|
+
)
|
|
162
|
+
return entries
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _entry_from_mapping(name: str, obj: dict[str, Any]) -> BenchEntry | None:
|
|
166
|
+
unit = str(obj["unit"]) if obj.get("unit") is not None else None
|
|
167
|
+
raw_samples = obj.get("times") or obj.get("samples") or obj.get("data")
|
|
168
|
+
samples: tuple[float, ...] = ()
|
|
169
|
+
if isinstance(raw_samples, list):
|
|
170
|
+
parsed = [f for x in raw_samples if (f := _to_float(x)) is not None]
|
|
171
|
+
if len(parsed) >= 2:
|
|
172
|
+
samples = tuple(parsed)
|
|
173
|
+
|
|
174
|
+
val: float | None = None
|
|
175
|
+
metric_key: str | None = None
|
|
176
|
+
for k in ("mean", "value", "median", "time", "latency", "score", "acc", "ops"):
|
|
177
|
+
if k in obj and (f := _to_float(obj[k])) is not None:
|
|
178
|
+
val = f
|
|
179
|
+
metric_key = k
|
|
180
|
+
break
|
|
181
|
+
if val is None and samples:
|
|
182
|
+
val = sum(samples) / len(samples)
|
|
183
|
+
if val is None:
|
|
184
|
+
return None
|
|
185
|
+
|
|
186
|
+
stddev = _to_float(obj.get("stddev") or obj.get("std") or obj.get("sd"))
|
|
187
|
+
n_val = _to_float(obj.get("rounds") or obj.get("n"))
|
|
188
|
+
n = int(n_val) if n_val is not None and n_val >= 1 else (len(samples) if samples else None)
|
|
189
|
+
|
|
190
|
+
ci_bounds: tuple[float, float] | None = None
|
|
191
|
+
raw_ci = obj.get("ci") or obj.get("interval")
|
|
192
|
+
if isinstance(raw_ci, list) and len(raw_ci) == 2:
|
|
193
|
+
lo, hi = _to_float(raw_ci[0]), _to_float(raw_ci[1])
|
|
194
|
+
if lo is not None and hi is not None and lo <= hi:
|
|
195
|
+
ci_bounds = (lo, hi)
|
|
196
|
+
elif obj.get("ci_low") is not None and obj.get("ci_high") is not None:
|
|
197
|
+
lo, hi = _to_float(obj.get("ci_low")), _to_float(obj.get("ci_high"))
|
|
198
|
+
if lo is not None and hi is not None and lo <= hi:
|
|
199
|
+
ci_bounds = (lo, hi)
|
|
200
|
+
|
|
201
|
+
return BenchEntry(
|
|
202
|
+
name=name,
|
|
203
|
+
value=val,
|
|
204
|
+
unit=unit,
|
|
205
|
+
samples=samples,
|
|
206
|
+
stddev=stddev,
|
|
207
|
+
n=n,
|
|
208
|
+
ci=ci_bounds,
|
|
209
|
+
higher_is_better=_infer_higher_is_better(metric_key, unit),
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _entry_from_row(row: dict[str, Any], idx: int) -> BenchEntry | None:
|
|
214
|
+
name: str | None = None
|
|
215
|
+
for k in ("name", "benchmark", "command", "model", "metric", "test", "id", "label"):
|
|
216
|
+
if k in row and row[k] is not None and str(row[k]).strip():
|
|
217
|
+
name = str(row[k]).strip()
|
|
218
|
+
break
|
|
219
|
+
if name is None:
|
|
220
|
+
for v in row.values():
|
|
221
|
+
if isinstance(v, str) and v.strip() and _to_float(v) is None:
|
|
222
|
+
name = v.strip()
|
|
223
|
+
break
|
|
224
|
+
if name is None:
|
|
225
|
+
name = f"row-{idx + 1}"
|
|
226
|
+
|
|
227
|
+
entry = _entry_from_mapping(name, row)
|
|
228
|
+
if entry is not None:
|
|
229
|
+
return entry
|
|
230
|
+
|
|
231
|
+
# Fall back to first numeric column in the row
|
|
232
|
+
for k, v in row.items():
|
|
233
|
+
if k.lower() in ("stddev", "std", "sd", "n", "rounds", "ci_low", "ci_high"):
|
|
234
|
+
continue
|
|
235
|
+
f = _to_float(v)
|
|
236
|
+
if f is not None:
|
|
237
|
+
unit = str(row["unit"]) if row.get("unit") is not None else None
|
|
238
|
+
stddev = _to_float(row.get("stddev") or row.get("std") or row.get("sd"))
|
|
239
|
+
n_val = _to_float(row.get("rounds") or row.get("n"))
|
|
240
|
+
ci_bounds: tuple[float, float] | None = None
|
|
241
|
+
lo, hi = _to_float(row.get("ci_low")), _to_float(row.get("ci_high"))
|
|
242
|
+
if lo is not None and hi is not None and lo <= hi:
|
|
243
|
+
ci_bounds = (lo, hi)
|
|
244
|
+
return BenchEntry(
|
|
245
|
+
name=name,
|
|
246
|
+
value=f,
|
|
247
|
+
unit=unit,
|
|
248
|
+
stddev=stddev,
|
|
249
|
+
n=int(n_val) if n_val is not None and n_val >= 1 else None,
|
|
250
|
+
ci=ci_bounds,
|
|
251
|
+
higher_is_better=_infer_higher_is_better(k, unit),
|
|
252
|
+
)
|
|
253
|
+
return None
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _parse_generic_csv(text: str) -> list[BenchEntry]:
|
|
257
|
+
lines = [ln for ln in text.splitlines() if ln.strip()]
|
|
258
|
+
if len(lines) < 2:
|
|
259
|
+
raise ChipError(
|
|
260
|
+
"mintchip diff: CSV input needs a header and at least one data row.",
|
|
261
|
+
fix_hint="Provide CSV with at least name and numeric columns.",
|
|
262
|
+
)
|
|
263
|
+
delimiter = "\t" if "\t" in lines[0] and "," not in lines[0] else ","
|
|
264
|
+
reader = csv.DictReader(lines, delimiter=delimiter)
|
|
265
|
+
entries: list[BenchEntry] = []
|
|
266
|
+
for idx, row in enumerate(reader):
|
|
267
|
+
clean = {k.strip(): (v.strip() if isinstance(v, str) else v) for k, v in row.items() if k}
|
|
268
|
+
entry = _entry_from_row(clean, idx)
|
|
269
|
+
if entry is not None:
|
|
270
|
+
entries.append(entry)
|
|
271
|
+
if not entries:
|
|
272
|
+
raise ChipError(
|
|
273
|
+
"mintchip diff: no numeric benchmark rows found in CSV.",
|
|
274
|
+
fix_hint="Provide CSV rows with a name column and a numeric measurement column.",
|
|
275
|
+
)
|
|
276
|
+
return entries
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def load_benchmark_entries(text: str, *, source: str = "<input>") -> list[BenchEntry]:
|
|
280
|
+
"""Auto-detect and parse any supported benchmark format into :class:`BenchEntry` records."""
|
|
281
|
+
stripped = text.lstrip()
|
|
282
|
+
if not stripped:
|
|
283
|
+
raise ChipError(
|
|
284
|
+
f"mintchip diff: {source!r} is empty.",
|
|
285
|
+
fix_hint="Pass two non-empty benchmark files (JSON, CSV, hyperfine, pytest/go/cargo bench).",
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
# Try structured SWE tool detectors first
|
|
289
|
+
try:
|
|
290
|
+
detected = detect_format(text)
|
|
291
|
+
except ChipError:
|
|
292
|
+
detected = ""
|
|
293
|
+
|
|
294
|
+
if detected == "hyperfine":
|
|
295
|
+
return parse_hyperfine(text)
|
|
296
|
+
if detected == "pytest-bench":
|
|
297
|
+
return parse_pytest_bench(text)
|
|
298
|
+
if detected == "go-bench":
|
|
299
|
+
return parse_go_bench(text)
|
|
300
|
+
if detected == "cargo-bench":
|
|
301
|
+
return parse_cargo_bench(text)
|
|
302
|
+
|
|
303
|
+
if stripped[0] in ("{", "["):
|
|
304
|
+
try:
|
|
305
|
+
return _parse_generic_json(text)
|
|
306
|
+
except json.JSONDecodeError as e:
|
|
307
|
+
raise ChipError(
|
|
308
|
+
f"mintchip diff: {source!r} is not valid JSON (line {e.lineno}: {e.msg}).",
|
|
309
|
+
fix_hint="Pass valid JSON, CSV, or benchmark text output.",
|
|
310
|
+
) from None
|
|
311
|
+
|
|
312
|
+
if "," in stripped.splitlines()[0] or "\t" in stripped.splitlines()[0]:
|
|
313
|
+
return _parse_generic_csv(text)
|
|
314
|
+
|
|
315
|
+
raise ChipError(
|
|
316
|
+
f"mintchip diff: could not parse benchmark format in {source!r}.",
|
|
317
|
+
fix_hint="Supported inputs: JSON, CSV, hyperfine, pytest-bench, go-bench, cargo-bench.",
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _entry_se_or_half(entry: BenchEntry, scale: float) -> tuple[float | None, float | None]:
|
|
322
|
+
"""Return ``(standard_error, half_width_95)`` scaled by ``scale``."""
|
|
323
|
+
if len(entry.samples) >= 2:
|
|
324
|
+
xs = [x * scale for x in entry.samples]
|
|
325
|
+
mean = sum(xs) / len(xs)
|
|
326
|
+
var = sum((x - mean) ** 2 for x in xs) / (len(xs) - 1)
|
|
327
|
+
se = math.sqrt(var / len(xs))
|
|
328
|
+
return se, 1.96 * se
|
|
329
|
+
if entry.ci is not None:
|
|
330
|
+
half = ((entry.ci[1] - entry.ci[0]) * scale) / 2.0
|
|
331
|
+
return half / 1.96, half
|
|
332
|
+
if entry.stddev is not None and entry.stddev > 0:
|
|
333
|
+
sd = entry.stddev * scale
|
|
334
|
+
se = sd / math.sqrt(entry.n) if entry.n and entry.n > 1 else sd
|
|
335
|
+
return se, 1.96 * se
|
|
336
|
+
return None, None
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def _diff_ci(
|
|
340
|
+
base: BenchEntry, head: BenchEntry, scale_b: float, scale_h: float
|
|
341
|
+
) -> tuple[float, float] | None:
|
|
342
|
+
"""Compute a 95% confidence interval for ``head - base`` when uncertainty info exists."""
|
|
343
|
+
_se_b, half_b = _entry_se_or_half(base, scale_b)
|
|
344
|
+
_se_h, half_h = _entry_se_or_half(head, scale_h)
|
|
345
|
+
if half_b is None and half_h is None:
|
|
346
|
+
return None
|
|
347
|
+
half = math.hypot(half_b or 0.0, half_h or 0.0)
|
|
348
|
+
diff = head.value * scale_h - base.value * scale_b
|
|
349
|
+
return (diff - half, diff + half)
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _scale_pair(
|
|
353
|
+
base_entries: Sequence[BenchEntry], head_entries: Sequence[BenchEntry]
|
|
354
|
+
) -> tuple[float, float, str | None]:
|
|
355
|
+
"""Harmonize units when both sides are time measurements (ns/us/ms/s)."""
|
|
356
|
+
units_b = {e.unit for e in base_entries if e.unit}
|
|
357
|
+
units_h = {e.unit for e in head_entries if e.unit}
|
|
358
|
+
if (
|
|
359
|
+
len(units_b) == 1
|
|
360
|
+
and len(units_h) == 1
|
|
361
|
+
and next(iter(units_b)) in _TIME_TO_SEC
|
|
362
|
+
and next(iter(units_h)) in _TIME_TO_SEC
|
|
363
|
+
):
|
|
364
|
+
to_sec_b = _TIME_TO_SEC[next(iter(units_b))]
|
|
365
|
+
to_sec_h = _TIME_TO_SEC[next(iter(units_h))]
|
|
366
|
+
all_secs = [e.value * to_sec_b for e in base_entries] + [
|
|
367
|
+
e.value * to_sec_h for e in head_entries
|
|
368
|
+
]
|
|
369
|
+
mult, unit = pick_time_unit(all_secs)
|
|
370
|
+
return to_sec_b * mult, to_sec_h * mult, unit
|
|
371
|
+
common = next(iter(units_b)) if len(units_b) == 1 and units_b == units_h else None
|
|
372
|
+
return 1.0, 1.0, common
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _format_pct(pct: float) -> str:
|
|
376
|
+
sign = "+" if pct > 0 else ("-" if pct < 0 else "")
|
|
377
|
+
return f"{sign}{abs(pct):.1f}%"
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def diff_benchmarks(
|
|
381
|
+
base_entries: Sequence[BenchEntry],
|
|
382
|
+
head_entries: Sequence[BenchEntry],
|
|
383
|
+
*,
|
|
384
|
+
higher_is_better: bool | None = None,
|
|
385
|
+
fail_on_regression: float | None = None,
|
|
386
|
+
title: str | None = None,
|
|
387
|
+
) -> DiffResult:
|
|
388
|
+
"""Compare two benchmark runs and produce a shared-scale table + takeaway."""
|
|
389
|
+
head_map = {e.name: e for e in head_entries}
|
|
390
|
+
matched: list[tuple[BenchEntry, BenchEntry]] = [
|
|
391
|
+
(b, head_map[b.name]) for b in base_entries if b.name in head_map
|
|
392
|
+
]
|
|
393
|
+
if not matched:
|
|
394
|
+
base_names = ", ".join(e.name for e in base_entries[:4])
|
|
395
|
+
head_names = ", ".join(e.name for e in head_entries[:4])
|
|
396
|
+
raise ChipError(
|
|
397
|
+
"mintchip diff: no matching benchmark names between BASE and HEAD.",
|
|
398
|
+
fix_hint=f"BASE has [{base_names}]; HEAD has [{head_names}].",
|
|
399
|
+
)
|
|
400
|
+
|
|
401
|
+
scale_b, scale_h, common_unit = _scale_pair(
|
|
402
|
+
[b for b, _ in matched], [h for _, h in matched]
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
rows: list[DiffRow] = []
|
|
406
|
+
for b, h in matched:
|
|
407
|
+
hib = higher_is_better if higher_is_better is not None else b.higher_is_better
|
|
408
|
+
bv = b.value * scale_b
|
|
409
|
+
hv = h.value * scale_h
|
|
410
|
+
dv = hv - bv
|
|
411
|
+
pct = (dv / abs(bv) * 100.0) if bv != 0 else 0.0
|
|
412
|
+
reg_pct = -pct if hib else pct
|
|
413
|
+
ci_bounds = _diff_ci(b, h, scale_b, scale_h)
|
|
414
|
+
rows.append(
|
|
415
|
+
DiffRow(
|
|
416
|
+
name=b.name,
|
|
417
|
+
base=bv,
|
|
418
|
+
head=hv,
|
|
419
|
+
delta=dv,
|
|
420
|
+
pct_change=pct,
|
|
421
|
+
regression_pct=reg_pct,
|
|
422
|
+
unit=common_unit or b.unit or h.unit,
|
|
423
|
+
ci=ci_bounds,
|
|
424
|
+
higher_is_better=hib,
|
|
425
|
+
)
|
|
426
|
+
)
|
|
427
|
+
|
|
428
|
+
has_ci = any(r.ci is not None for r in rows)
|
|
429
|
+
table_rows: list[dict[str, Any]] = []
|
|
430
|
+
for r in rows:
|
|
431
|
+
trow: dict[str, Any] = {
|
|
432
|
+
"name": r.name,
|
|
433
|
+
"base": mc.num(r.base, unit=r.unit),
|
|
434
|
+
"head": mc.num(r.head, unit=r.unit),
|
|
435
|
+
"change": mc.delta(
|
|
436
|
+
r.base, r.head, higher_is_better=r.higher_is_better, unit=r.unit
|
|
437
|
+
),
|
|
438
|
+
}
|
|
439
|
+
if has_ci:
|
|
440
|
+
if r.ci is not None:
|
|
441
|
+
trow["ci"] = mc.ci(r.delta, r.ci, reference=0.0, level=0.95, unit=r.unit)
|
|
442
|
+
else:
|
|
443
|
+
trow["ci"] = None
|
|
444
|
+
table_rows.append(trow)
|
|
445
|
+
|
|
446
|
+
columns: dict[str, Any] = {
|
|
447
|
+
"name": {"chip": "text", "header": "Benchmark"},
|
|
448
|
+
"base": {"chip": "num", "header": "Base"},
|
|
449
|
+
"head": {"chip": "num", "header": "Head"},
|
|
450
|
+
"change": {"chip": "delta", "header": "Delta"},
|
|
451
|
+
}
|
|
452
|
+
if has_ci:
|
|
453
|
+
columns["ci"] = {"chip": "ci", "header": "95% CI"}
|
|
454
|
+
|
|
455
|
+
tbl = mc.table(table_rows, columns, title=title)
|
|
456
|
+
|
|
457
|
+
# Classify outcomes (treat < 0.1% as unchanged)
|
|
458
|
+
improved = [r for r in rows if r.regression_pct < -0.1]
|
|
459
|
+
regressed = [r for r in rows if r.regression_pct > 0.1]
|
|
460
|
+
unchanged = len(rows) - len(improved) - len(regressed)
|
|
461
|
+
|
|
462
|
+
worst = max(rows, key=lambda r: r.regression_pct)
|
|
463
|
+
best = min(rows, key=lambda r: r.regression_pct)
|
|
464
|
+
|
|
465
|
+
regressions_over = (
|
|
466
|
+
tuple(r for r in rows if r.regression_pct > fail_on_regression)
|
|
467
|
+
if fail_on_regression is not None
|
|
468
|
+
else ()
|
|
469
|
+
)
|
|
470
|
+
failed = bool(regressions_over)
|
|
471
|
+
|
|
472
|
+
parts = [
|
|
473
|
+
(
|
|
474
|
+
f"Compared {len(rows)} benchmark{'s' if len(rows) != 1 else ''}: "
|
|
475
|
+
f"{len(improved)} improved, {len(regressed)} regressed, {unchanged} unchanged"
|
|
476
|
+
)
|
|
477
|
+
]
|
|
478
|
+
if worst.regression_pct > 0.1:
|
|
479
|
+
parts.append(
|
|
480
|
+
f"worst regression {worst.name} ({_format_pct(worst.pct_change)}, "
|
|
481
|
+
f"{_fmt.num(worst.base)}→{_fmt.num(worst.head, unit=worst.unit)})"
|
|
482
|
+
)
|
|
483
|
+
elif best.regression_pct < -0.1:
|
|
484
|
+
parts.append(
|
|
485
|
+
f"largest improvement {best.name} ({_format_pct(best.pct_change)}, "
|
|
486
|
+
f"{_fmt.num(best.base)}→{_fmt.num(best.head, unit=best.unit)})"
|
|
487
|
+
)
|
|
488
|
+
if failed and fail_on_regression is not None:
|
|
489
|
+
names = ", ".join(r.name for r in regressions_over)
|
|
490
|
+
parts.append(f"FAILED >{fail_on_regression:g}% gate ({names})")
|
|
491
|
+
|
|
492
|
+
takeaway = "; ".join(parts) + "."
|
|
493
|
+
return DiffResult(
|
|
494
|
+
table=tbl,
|
|
495
|
+
rows=tuple(rows),
|
|
496
|
+
takeaway=takeaway,
|
|
497
|
+
regressions=regressions_over,
|
|
498
|
+
fail_threshold=fail_on_regression,
|
|
499
|
+
failed=failed,
|
|
500
|
+
warnings=tbl.warnings,
|
|
501
|
+
)
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def render_diff(result: DiffResult, *, format: str = "text", ascii: bool = False) -> str:
|
|
505
|
+
"""Render a :class:`DiffResult` in text, ANSI, Markdown, HTML, or JSON."""
|
|
506
|
+
from .cli import _bad_format
|
|
507
|
+
|
|
508
|
+
if format not in OUTPUT_FORMATS:
|
|
509
|
+
raise _bad_format(format, OUTPUT_FORMATS)
|
|
510
|
+
|
|
511
|
+
takeaway = result.takeaway.replace("→", "->") if ascii else result.takeaway
|
|
512
|
+
|
|
513
|
+
if format == "json":
|
|
514
|
+
payload = {
|
|
515
|
+
"takeaway": takeaway,
|
|
516
|
+
"failed": result.failed,
|
|
517
|
+
"fail_threshold": result.fail_threshold,
|
|
518
|
+
"regressions": [
|
|
519
|
+
{
|
|
520
|
+
"name": r.name,
|
|
521
|
+
"base": r.base,
|
|
522
|
+
"head": r.head,
|
|
523
|
+
"delta": r.delta,
|
|
524
|
+
"pct_change": round(r.pct_change, 4),
|
|
525
|
+
"regression_pct": round(r.regression_pct, 4),
|
|
526
|
+
"unit": r.unit,
|
|
527
|
+
}
|
|
528
|
+
for r in result.regressions
|
|
529
|
+
],
|
|
530
|
+
"rows": [
|
|
531
|
+
{
|
|
532
|
+
"name": r.name,
|
|
533
|
+
"base": r.base,
|
|
534
|
+
"head": r.head,
|
|
535
|
+
"delta": r.delta,
|
|
536
|
+
"pct_change": round(r.pct_change, 4),
|
|
537
|
+
"regression_pct": round(r.regression_pct, 4),
|
|
538
|
+
"unit": r.unit,
|
|
539
|
+
"ci": list(r.ci) if r.ci is not None else None,
|
|
540
|
+
}
|
|
541
|
+
for r in result.rows
|
|
542
|
+
],
|
|
543
|
+
"table": result.table.to_dict(),
|
|
544
|
+
}
|
|
545
|
+
return json.dumps(payload, indent=2, ensure_ascii=ascii)
|
|
546
|
+
|
|
547
|
+
if format == "md":
|
|
548
|
+
return f"{result.table.markdown()}\n\n{takeaway}"
|
|
549
|
+
|
|
550
|
+
if format == "html":
|
|
551
|
+
return f'{result.table.html()}\n<p class="mc-takeaway">{_html.escape(takeaway)}</p>'
|
|
552
|
+
|
|
553
|
+
body = result.table.text(ascii=ascii, color=format == "ansi")
|
|
554
|
+
return f"{body}\n\n{takeaway}"
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
def add_diff_parser(sub: Any, formatter_class: Any) -> argparse.ArgumentParser:
|
|
558
|
+
"""Register the ``mintchip diff`` subcommand."""
|
|
559
|
+
p = sub.add_parser(
|
|
560
|
+
"diff",
|
|
561
|
+
help="Compare two benchmark runs (JSON, CSV, hyperfine, pytest/go/cargo bench).",
|
|
562
|
+
description=(
|
|
563
|
+
"Compare BASE and HEAD benchmark files with zero dependencies. Outputs a shared-scale\n"
|
|
564
|
+
"table with Base, Head, Delta, and 95% CI (when samples or intervals exist) plus a\n"
|
|
565
|
+
"one-line takeaway. Exits 1 if any regression exceeds --fail-on-regression PCT."
|
|
566
|
+
),
|
|
567
|
+
epilog="example:\n $ mintchip diff base.json head.json --fail-on-regression 5",
|
|
568
|
+
formatter_class=formatter_class,
|
|
569
|
+
)
|
|
570
|
+
p.add_argument("base", metavar="BASE", help="Baseline benchmark file (or - for stdin).")
|
|
571
|
+
p.add_argument("head", metavar="HEAD", help="Candidate benchmark file.")
|
|
572
|
+
p.add_argument(
|
|
573
|
+
"--format",
|
|
574
|
+
choices=OUTPUT_FORMATS,
|
|
575
|
+
default="text",
|
|
576
|
+
help="Output format: text (default), ansi, md, html or json.",
|
|
577
|
+
)
|
|
578
|
+
p.add_argument("--ascii", action="store_true", help="Pure ASCII output.")
|
|
579
|
+
p.add_argument("--strict", action="store_true", help="Exit 1 on any warning.")
|
|
580
|
+
p.add_argument(
|
|
581
|
+
"--fail-on-regression",
|
|
582
|
+
type=float,
|
|
583
|
+
default=None,
|
|
584
|
+
metavar="PCT",
|
|
585
|
+
help="Exit 1 if any benchmark regresses by more than PCT percent (e.g. 5).",
|
|
586
|
+
)
|
|
587
|
+
direction = p.add_mutually_exclusive_group()
|
|
588
|
+
direction.add_argument(
|
|
589
|
+
"--higher-is-better",
|
|
590
|
+
action="store_true",
|
|
591
|
+
help="Treat higher values as better (e.g. throughput or accuracy).",
|
|
592
|
+
)
|
|
593
|
+
direction.add_argument(
|
|
594
|
+
"--lower-is-better",
|
|
595
|
+
action="store_true",
|
|
596
|
+
help="Treat lower values as better (default for timings/latency).",
|
|
597
|
+
)
|
|
598
|
+
p.add_argument("--title", help="Optional title above the table.")
|
|
599
|
+
p.set_defaults(func=cmd_diff, _parser=p)
|
|
600
|
+
return p
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
def cmd_diff(args: argparse.Namespace) -> int:
|
|
604
|
+
"""Execute ``mintchip diff``."""
|
|
605
|
+
from .cli import _err, _error, _out, _read, _warn
|
|
606
|
+
|
|
607
|
+
if args.fail_on_regression is not None and args.fail_on_regression < 0:
|
|
608
|
+
return _error(
|
|
609
|
+
ChipError(
|
|
610
|
+
f"mintchip diff: --fail-on-regression must be >= 0; got {args.fail_on_regression}.",
|
|
611
|
+
fix_hint="Pass a non-negative percentage, e.g. --fail-on-regression 5.",
|
|
612
|
+
)
|
|
613
|
+
)
|
|
614
|
+
|
|
615
|
+
hib: bool | None = None
|
|
616
|
+
if args.higher_is_better:
|
|
617
|
+
hib = True
|
|
618
|
+
elif args.lower_is_better:
|
|
619
|
+
hib = False
|
|
620
|
+
|
|
621
|
+
try:
|
|
622
|
+
base_entries = load_benchmark_entries(_read(args.base), source=args.base)
|
|
623
|
+
head_entries = load_benchmark_entries(_read(args.head), source=args.head)
|
|
624
|
+
res = diff_benchmarks(
|
|
625
|
+
base_entries,
|
|
626
|
+
head_entries,
|
|
627
|
+
higher_is_better=hib,
|
|
628
|
+
fail_on_regression=args.fail_on_regression,
|
|
629
|
+
title=args.title,
|
|
630
|
+
)
|
|
631
|
+
out = render_diff(res, format=args.format, ascii=args.ascii)
|
|
632
|
+
except ChipError as e:
|
|
633
|
+
return _error(e, "mintchip diff base.json head.json")
|
|
634
|
+
|
|
635
|
+
_out(out)
|
|
636
|
+
warn_code = _warn(res.warnings, args.strict)
|
|
637
|
+
if res.failed:
|
|
638
|
+
names = ", ".join(
|
|
639
|
+
f"{r.name} ({_format_pct(r.pct_change)})" for r in res.regressions
|
|
640
|
+
)
|
|
641
|
+
_err(
|
|
642
|
+
f"mintchip: diff: regression exceeded {res.fail_threshold:g}% threshold: {names}"
|
|
643
|
+
)
|
|
644
|
+
return 1
|
|
645
|
+
return warn_code
|