specbench-cli 0.1.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,1228 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import math
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ from typing import Any, Literal
8
+
9
+ import matplotlib
10
+
11
+ matplotlib.use("Agg")
12
+
13
+ import matplotlib.patheffects as pe
14
+ import matplotlib.pyplot as plt
15
+ import numpy as np
16
+ from matplotlib.axes import Axes
17
+ from matplotlib.colors import LinearSegmentedColormap
18
+ from matplotlib.figure import Figure
19
+ from matplotlib.patches import FancyBboxPatch
20
+
21
+ ThemeName = Literal["light", "dark"]
22
+
23
+ _CAPABILITY_LABELS: dict[str, str] = {
24
+ "coding": "Coding",
25
+ "livecodebench": "LiveCodeBench",
26
+ "swe_atlas_qna": "SWE-Atlas QnA",
27
+ "swe-atlas-qna": "SWE-Atlas QnA",
28
+ "multimodal": "Multimodal",
29
+ "mmmu_pro": "MMMU-Pro",
30
+ "mmmu-pro": "MMMU-Pro",
31
+ "knowledge_work": "Knowledge Work",
32
+ "aa_briefcase_lite": "AA-Briefcase-Lite",
33
+ "aa-briefcase-lite": "AA-Briefcase-Lite",
34
+ "smoke_coding": "Smoke Coding",
35
+ "smoke_multimodal": "Smoke Multimodal",
36
+ }
37
+
38
+ _SPEC_TYPE_SHORT: dict[str, str] = {
39
+ "draft-dflash": "dflash",
40
+ "draft-mtp": "MTP",
41
+ "draft-eagle3": "EAGLE-3",
42
+ "draft-dspark": "dspark",
43
+ "draft-simple": "draft",
44
+ "ngram-mod": "ngram",
45
+ "ngram-simple": "ngram",
46
+ }
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class Theme:
51
+ name: ThemeName
52
+ canvas_bg: str
53
+ card_bg: str
54
+ card_edge: str
55
+ card_shadow: str
56
+ text_primary: str
57
+ text_secondary: str
58
+ text_muted: str
59
+ grid: str
60
+ baseline_line: str
61
+ pill_bg: str
62
+ pill_edge: str
63
+ palette: tuple[str, ...]
64
+ heatmap_stops: tuple[str, ...]
65
+ mem_base: str
66
+ mem_extra: str
67
+
68
+
69
+ THEMES: dict[ThemeName, Theme] = {
70
+ "light": Theme(
71
+ name="light",
72
+ canvas_bg="#F4F6FA",
73
+ card_bg="#FFFFFF",
74
+ card_edge="#E2E8F0",
75
+ card_shadow="#CBD5E1",
76
+ text_primary="#0F172A",
77
+ text_secondary="#334155",
78
+ text_muted="#64748B",
79
+ grid="#EDF2F7",
80
+ baseline_line="#94A3B8",
81
+ pill_bg="#F1F5F9",
82
+ pill_edge="#CBD5E1",
83
+ palette=(
84
+ "#2563EB", # royal cobalt
85
+ "#E11D48", # crimson rose
86
+ "#0D9488", # deep teal
87
+ "#D97706", # warm amber
88
+ "#7C3AED", # electric violet
89
+ "#059669", # emerald
90
+ ),
91
+ heatmap_stops=("#EFF6FF", "#93C5FD", "#3B82F6", "#1D4ED8"),
92
+ mem_base="#3B82F6",
93
+ mem_extra="#F43F5E",
94
+ ),
95
+ "dark": Theme(
96
+ name="dark",
97
+ canvas_bg="#0B1120",
98
+ card_bg="#111827",
99
+ card_edge="#1F2937",
100
+ card_shadow="#020617",
101
+ text_primary="#F8FAFC",
102
+ text_secondary="#CBD5E1",
103
+ text_muted="#94A3B8",
104
+ grid="#1E293B",
105
+ baseline_line="#64748B",
106
+ pill_bg="#1E293B",
107
+ pill_edge="#334155",
108
+ palette=(
109
+ "#60A5FA", # sky blue
110
+ "#FB7185", # coral rose
111
+ "#2DD4BF", # mint teal
112
+ "#FBBF24", # warm gold
113
+ "#A78BFA", # soft lavender
114
+ "#34D399", # emerald
115
+ ),
116
+ heatmap_stops=("#172554", "#0E7490", "#10B981", "#6EE7B7"),
117
+ mem_base="#60A5FA",
118
+ mem_extra="#FB7185",
119
+ ),
120
+ }
121
+
122
+
123
+ def _configure_matplotlib(theme: Theme) -> None:
124
+ plt.rcParams.update(
125
+ {
126
+ "font.family": "sans-serif",
127
+ "font.sans-serif": ["Cantarell", "Ubuntu", "Liberation Sans", "DejaVu Sans"],
128
+ "axes.facecolor": theme.card_bg,
129
+ "figure.facecolor": theme.canvas_bg,
130
+ "savefig.facecolor": theme.canvas_bg,
131
+ "axes.edgecolor": theme.card_edge,
132
+ "axes.linewidth": 0.9,
133
+ "text.color": theme.text_primary,
134
+ "axes.labelcolor": theme.text_secondary,
135
+ "xtick.color": theme.text_muted,
136
+ "ytick.color": theme.text_muted,
137
+ "axes.titlesize": 11.5,
138
+ "axes.titleweight": "bold",
139
+ "axes.labelsize": 9.5,
140
+ "xtick.labelsize": 9.0,
141
+ "ytick.labelsize": 9.0,
142
+ "legend.frameon": False,
143
+ }
144
+ )
145
+
146
+
147
+ def _format_capability(cap: str) -> str:
148
+ key = cap.strip().lower()
149
+ if key in _CAPABILITY_LABELS:
150
+ return _CAPABILITY_LABELS[key]
151
+ return cap.replace("_", " ").replace("-", " ").title()
152
+
153
+
154
+ def _short_spec_type(spec_type: str) -> str:
155
+ key = spec_type.strip().lower()
156
+ return _SPEC_TYPE_SHORT.get(key, spec_type)
157
+
158
+
159
+ def load_summary_rows(
160
+ source: str | Path,
161
+ *,
162
+ model_filter: str | None = None,
163
+ capabilities: list[str] | None = None,
164
+ run_ids: list[str] | None = None,
165
+ ) -> list[dict[str, Any]]:
166
+ """Load summary rows from a local run dir, summary.parquet, summary.json, or HF dataset repo."""
167
+ source_str = str(source).strip()
168
+ path = Path(source_str)
169
+ rows: list[dict[str, Any]]
170
+
171
+ if path.exists():
172
+ if path.is_dir():
173
+ parquet_path = path / "summary.parquet"
174
+ json_path = path / "summary.json"
175
+ if parquet_path.exists():
176
+ from datasets import Dataset
177
+
178
+ rows = [dict(r) for r in Dataset.from_parquet(str(parquet_path))]
179
+ elif json_path.exists():
180
+ rows = json.loads(json_path.read_text(encoding="utf-8"))
181
+ else:
182
+ raise FileNotFoundError(
183
+ f"Directory {path} does not contain summary.parquet or summary.json."
184
+ )
185
+ elif path.suffix.lower() == ".parquet":
186
+ from datasets import Dataset
187
+
188
+ rows = [dict(r) for r in Dataset.from_parquet(str(path))]
189
+ elif path.suffix.lower() == ".json":
190
+ loaded = json.loads(path.read_text(encoding="utf-8"))
191
+ rows = loaded if isinstance(loaded, list) else loaded.get("summary", [])
192
+ else:
193
+ raise ValueError(f"Unsupported local file format: {path.suffix}")
194
+ else:
195
+ from datasets import load_dataset
196
+
197
+ repo_id = source_str.removeprefix("hf:").strip()
198
+ ds = load_dataset(repo_id, name="summary", split="train")
199
+ rows = [dict(r) for r in ds]
200
+
201
+ filtered: list[dict[str, Any]] = []
202
+ cap_set = {c.strip() for c in capabilities} if capabilities else None
203
+ run_set = {r.strip() for r in run_ids} if run_ids else None
204
+
205
+ for row in rows:
206
+ if model_filter:
207
+ hay = f"{row.get('model_repo', '')} {row.get('model_quant', '')} {row.get('spec_type', '')}".lower()
208
+ if model_filter.lower() not in hay:
209
+ continue
210
+ if cap_set is not None and str(row.get("capability", "")) not in cap_set:
211
+ continue
212
+ if run_set is not None and str(row.get("run_id", "")) not in run_set:
213
+ continue
214
+ filtered.append(row)
215
+
216
+ if not filtered:
217
+ raise ValueError(f"No summary rows matched source={source_str!r} with the given filters.")
218
+ return filtered
219
+
220
+
221
+ def _full_model_name(row: dict[str, Any]) -> str:
222
+ repo = str(row.get("model_repo") or "model")
223
+ base = repo.split("/")[-1]
224
+ quant = str(row.get("model_quant") or "").strip()
225
+ if ":" in base:
226
+ return base
227
+ if quant and quant.lower() not in base.lower():
228
+ return f"{base}:{quant}"
229
+ return base
230
+
231
+
232
+ def _compact_model_labels(rows: list[dict[str, Any]]) -> tuple[str | None, dict[str, str]]:
233
+ """Strip common repo prefix (e.g. `Qwen3-30B-GGUF:`) when comparing quants of the same model."""
234
+ full_names = sorted({_full_model_name(r) for r in rows})
235
+ if len(full_names) <= 1:
236
+ return (full_names[0] if full_names else None), {n: n for n in full_names}
237
+
238
+ # Check if all share `<repo_base>:<quant>` prefix
239
+ bases = {n.split(":", 1)[0] for n in full_names if ":" in n}
240
+ if len(bases) == 1 and all(":" in n for n in full_names):
241
+ shared_base = next(iter(bases))
242
+ return shared_base, {n: n.split(":", 1)[1] for n in full_names}
243
+ return None, {n: n for n in full_names}
244
+
245
+
246
+ def _series_key_and_label(
247
+ rows: list[dict[str, Any]],
248
+ ) -> tuple[str | None, dict[str, list[dict[str, Any]]], dict[str, str]]:
249
+ """Group rows into concise readable chart series + compact model label lookup."""
250
+ shared_base, compact_map = _compact_model_labels(rows)
251
+
252
+ unique_models = {
253
+ (_full_model_name(r), str(r.get("spec_type") or ""))
254
+ for r in rows
255
+ if int(r.get("draft_n_max") or 0) > 0
256
+ }
257
+ if not unique_models:
258
+ unique_models = {(_full_model_name(r), "") for r in rows}
259
+ multi_model = len(unique_models) > 1
260
+
261
+ spec_by_group: dict[tuple[str, str], str] = {}
262
+ for r in rows:
263
+ if int(r.get("draft_n_max") or 0) > 0:
264
+ spec_by_group[(_full_model_name(r), str(r.get("capability", "")))] = _short_spec_type(
265
+ str(r.get("spec_type") or "")
266
+ )
267
+
268
+ grouped: dict[str, list[dict[str, Any]]] = {}
269
+ for r in rows:
270
+ full_m = _full_model_name(r)
271
+ short_m = compact_map[full_m]
272
+ cap = _format_capability(str(r.get("capability") or "unknown"))
273
+ if multi_model:
274
+ spec = spec_by_group.get((full_m, str(r.get("capability", ""))), "")
275
+ label = f"{short_m} ({spec}) · {cap}" if spec else f"{short_m} · {cap}"
276
+ else:
277
+ label = cap
278
+ grouped.setdefault(label, []).append(r)
279
+
280
+ for label in grouped:
281
+ grouped[label].sort(key=lambda r: int(r.get("draft_n_max") or 0))
282
+ return shared_base, grouped, compact_map
283
+
284
+
285
+ def _create_card_panel(
286
+ fig: Figure,
287
+ rect: tuple[float, float, float, float],
288
+ theme: Theme,
289
+ *,
290
+ title: str,
291
+ subtitle: str | None = None,
292
+ inner_left: float = 0.055,
293
+ inner_right: float = 0.028,
294
+ inner_top: float = 0.068,
295
+ inner_bottom: float = 0.055,
296
+ ) -> Axes:
297
+ """Draw a rounded elevated card and return an Axes cleanly inset inside it."""
298
+ x0, y0, w, h = rect
299
+
300
+ # Soft shadow layer
301
+ shadow = FancyBboxPatch(
302
+ (x0 + 0.0025, y0 - 0.004),
303
+ w,
304
+ h,
305
+ boxstyle="round,pad=0.0,rounding_size=0.016",
306
+ transform=fig.transFigure,
307
+ facecolor=theme.card_shadow,
308
+ edgecolor="none",
309
+ alpha=0.22 if theme.name == "light" else 0.45,
310
+ zorder=0,
311
+ )
312
+ fig.patches.append(shadow)
313
+
314
+ # Main card surface
315
+ card = FancyBboxPatch(
316
+ (x0, y0),
317
+ w,
318
+ h,
319
+ boxstyle="round,pad=0.0,rounding_size=0.016",
320
+ transform=fig.transFigure,
321
+ facecolor=theme.card_bg,
322
+ edgecolor=theme.card_edge,
323
+ linewidth=1.0,
324
+ zorder=1,
325
+ )
326
+ fig.patches.append(card)
327
+
328
+ # Panel title inside card header
329
+ fig.text(
330
+ x0 + 0.018,
331
+ y0 + h - 0.026,
332
+ title,
333
+ fontsize=11.5,
334
+ fontweight="bold",
335
+ color=theme.text_primary,
336
+ va="top",
337
+ ha="left",
338
+ zorder=5,
339
+ )
340
+ if subtitle:
341
+ fig.text(
342
+ x0 + 0.018,
343
+ y0 + h - 0.050,
344
+ subtitle,
345
+ fontsize=8.4,
346
+ color=theme.text_muted,
347
+ va="top",
348
+ ha="left",
349
+ zorder=5,
350
+ )
351
+
352
+ ax = fig.add_axes(
353
+ [
354
+ x0 + inner_left,
355
+ y0 + inner_bottom,
356
+ max(0.05, w - inner_left - inner_right),
357
+ max(0.05, h - inner_top - inner_bottom),
358
+ ],
359
+ zorder=3,
360
+ )
361
+ ax.set_facecolor(theme.card_bg)
362
+ return ax
363
+
364
+
365
+ def _style_card_axes(ax: Axes, theme: Theme) -> None:
366
+ ax.set_facecolor(theme.card_bg)
367
+ ax.spines["top"].set_visible(False)
368
+ ax.spines["right"].set_visible(False)
369
+ ax.spines["left"].set_color(theme.card_edge)
370
+ ax.spines["bottom"].set_color(theme.card_edge)
371
+ ax.grid(axis="y", color=theme.grid, linestyle="-", linewidth=0.8, alpha=0.95, zorder=0)
372
+ ax.grid(axis="x", visible=False)
373
+ ax.set_axisbelow(True)
374
+ ax.tick_params(axis="both", length=0, pad=6)
375
+
376
+
377
+ def _repel_y_positions(
378
+ ys: list[float],
379
+ y_min: float,
380
+ y_max: float,
381
+ min_gap: float,
382
+ ) -> list[float]:
383
+ """Spread colliding y label positions cleanly while staying within [y_min, y_max]."""
384
+ if len(ys) <= 1:
385
+ return list(ys)
386
+ order = sorted(range(len(ys)), key=lambda i: ys[i])
387
+ placed = [ys[i] for i in order]
388
+
389
+ for _ in range(12):
390
+ moved = False
391
+ for k in range(1, len(placed)):
392
+ diff = placed[k] - placed[k - 1]
393
+ if diff < min_gap:
394
+ shift = (min_gap - diff) * 0.52
395
+ placed[k - 1] -= shift
396
+ placed[k] += shift
397
+ moved = True
398
+ for k in range(len(placed)):
399
+ placed[k] = max(y_min, min(y_max, placed[k]))
400
+ if not moved:
401
+ break
402
+
403
+ # Final upward/downward sweep if clamped at ceiling/floor
404
+ for k in range(1, len(placed)):
405
+ if placed[k] - placed[k - 1] < min_gap:
406
+ placed[k] = placed[k - 1] + min_gap
407
+ if placed[-1] > y_max:
408
+ overflow = placed[-1] - y_max
409
+ placed = [p - overflow for p in placed]
410
+ for k in range(len(placed) - 2, -1, -1):
411
+ if placed[k + 1] - placed[k] < min_gap:
412
+ placed[k] = placed[k + 1] - min_gap
413
+
414
+ out = [0.0] * len(ys)
415
+ for idx, val in zip(order, placed):
416
+ out[idx] = val
417
+ return out
418
+
419
+
420
+ def _draw_acceptance_panel(
421
+ ax: Axes,
422
+ series_map: dict[str, list[dict[str, Any]]],
423
+ theme: Theme,
424
+ color_map: dict[str, str],
425
+ ) -> None:
426
+ _style_card_axes(ax, theme)
427
+ all_x: list[int] = []
428
+ clamped_effs: set[int] = set()
429
+ n_series = len(series_map)
430
+ dense = n_series >= 3
431
+
432
+ # Collect points for collision-free labeling
433
+ labels_by_x: dict[int, list[tuple[float, str, str]]] = {}
434
+ end_labels: list[tuple[int, float, str, str]] = []
435
+
436
+ for label, srows in series_map.items():
437
+ pts = [
438
+ r
439
+ for r in srows
440
+ if int(r.get("draft_n_max") or 0) > 0 and r.get("acceptance_rate") is not None
441
+ ]
442
+ if not pts:
443
+ continue
444
+ xs = [int(r["draft_n_max"]) for r in pts]
445
+ ys = [float(r["acceptance_rate"]) * 100.0 for r in pts]
446
+ effs = [int(r.get("effective_draft_n_max") or r["draft_n_max"]) for r in pts]
447
+ all_x.extend(xs)
448
+ color = color_map[label]
449
+
450
+ if n_series <= 2:
451
+ ax.fill_between(xs, ys, 0, color=color, alpha=0.09, zorder=1)
452
+
453
+ ax.plot(
454
+ xs,
455
+ ys,
456
+ color=color,
457
+ linewidth=2.5,
458
+ zorder=3,
459
+ label=label,
460
+ )
461
+
462
+ for x, y, eff in zip(xs, ys, effs):
463
+ is_clamped = eff != x
464
+ if is_clamped:
465
+ clamped_effs.add(eff)
466
+ ax.scatter(
467
+ [x],
468
+ [y],
469
+ s=58 if not is_clamped else 66,
470
+ marker="D" if is_clamped else "o",
471
+ facecolor=color,
472
+ edgecolor=theme.card_bg,
473
+ linewidth=1.8,
474
+ zorder=4,
475
+ )
476
+ if not dense:
477
+ txt = f"{y:.1f}%"
478
+ labels_by_x.setdefault(x, []).append((y, txt, color))
479
+
480
+ if dense:
481
+ end_labels.append((xs[-1], ys[-1], f"{ys[-1]:.1f}%", color))
482
+
483
+ ax.set_xlabel("Requested Draft Tokens (--spec-draft-n-max)", labelpad=6)
484
+ ax.set_ylabel("Acceptance Rate (%)", labelpad=6)
485
+ ax.set_ylim(0, 106)
486
+
487
+ if all_x:
488
+ uniq_x = sorted(set(all_x))
489
+ ax.set_xticks(uniq_x)
490
+ span = max(uniq_x) - min(uniq_x) if len(uniq_x) > 1 else 2
491
+ right_pad = 0.24 * span if dense else 0.14 * span
492
+ ax.set_xlim(min(uniq_x) - 0.12 * span, max(uniq_x) + right_pad)
493
+
494
+ if dense and end_labels:
495
+ x_end = max(uniq_x)
496
+ y_targets = _repel_y_positions(
497
+ [item[1] for item in end_labels],
498
+ y_min=8.0,
499
+ y_max=98.0,
500
+ min_gap=7.2,
501
+ )
502
+ for (_, orig_y, txt, color), placed_y in zip(end_labels, y_targets):
503
+ if abs(placed_y - orig_y) > 2.2:
504
+ ax.plot(
505
+ [x_end + 0.02 * span, x_end + 0.055 * span],
506
+ [orig_y, placed_y],
507
+ color=color,
508
+ linewidth=0.9,
509
+ alpha=0.55,
510
+ zorder=4,
511
+ )
512
+ ax.text(
513
+ x_end + 0.065 * span,
514
+ placed_y,
515
+ txt,
516
+ va="center",
517
+ ha="left",
518
+ fontsize=8.3,
519
+ fontweight="bold",
520
+ color=color,
521
+ zorder=5,
522
+ )
523
+ else:
524
+ for x_val, items in labels_by_x.items():
525
+ y_targets = _repel_y_positions(
526
+ [it[0] + 4.5 for it in items],
527
+ y_min=8.0,
528
+ y_max=101.0,
529
+ min_gap=7.8,
530
+ )
531
+ for (_, txt, color), placed_y in zip(items, y_targets):
532
+ ax.text(
533
+ x_val,
534
+ placed_y,
535
+ txt,
536
+ ha="center",
537
+ va="bottom",
538
+ fontsize=8.5,
539
+ fontweight="bold",
540
+ color=color,
541
+ path_effects=[pe.withStroke(linewidth=2.4, foreground=theme.card_bg)],
542
+ zorder=5,
543
+ )
544
+
545
+ if clamped_effs:
546
+ eff_str = ", ".join(f"N={e}" for e in sorted(clamped_effs))
547
+ ax.text(
548
+ 0.02,
549
+ 0.05,
550
+ f"Diamond markers: clamped by engine to {eff_str}",
551
+ transform=ax.transAxes,
552
+ fontsize=8.0,
553
+ color=theme.text_muted,
554
+ bbox={
555
+ "boxstyle": "round,pad=0.35",
556
+ "facecolor": theme.pill_bg,
557
+ "edgecolor": theme.pill_edge,
558
+ "linewidth": 0.7,
559
+ },
560
+ zorder=6,
561
+ )
562
+
563
+
564
+ def _draw_throughput_panel(
565
+ ax: Axes,
566
+ series_map: dict[str, list[dict[str, Any]]],
567
+ theme: Theme,
568
+ color_map: dict[str, str],
569
+ ) -> None:
570
+ _style_card_axes(ax, theme)
571
+ all_x: list[int] = []
572
+ max_y = 0.0
573
+ n_series = len(series_map)
574
+ dense = n_series >= 3
575
+
576
+ drawn_baselines: set[float] = set()
577
+ baseline_labels: list[tuple[float, str, str]] = []
578
+ labels_by_x: dict[int, list[tuple[float, str, str]]] = {}
579
+ end_labels: list[tuple[int, float, str, str]] = []
580
+
581
+ for label, srows in series_map.items():
582
+ pts = [r for r in srows if r.get("avg_predicted_per_second") is not None]
583
+ if not pts:
584
+ continue
585
+ xs = [int(r["draft_n_max"]) for r in pts]
586
+ ys = [float(r["avg_predicted_per_second"]) for r in pts]
587
+ speedups = [r.get("speedup_vs_baseline") for r in pts]
588
+ all_x.extend(xs)
589
+ max_y = max(max_y, max(ys))
590
+ color = color_map[label]
591
+
592
+ for x, y in zip(xs, ys):
593
+ if x == 0:
594
+ rounded = round(y, 1)
595
+ if rounded not in drawn_baselines:
596
+ drawn_baselines.add(rounded)
597
+ ax.axhline(
598
+ y,
599
+ color=theme.baseline_line,
600
+ linestyle="--",
601
+ linewidth=1.0,
602
+ alpha=0.55,
603
+ zorder=1,
604
+ )
605
+ baseline_labels.append((y, f"{y:.1f} base", theme.text_muted))
606
+
607
+ ax.plot(
608
+ xs,
609
+ ys,
610
+ color=color,
611
+ linewidth=2.5,
612
+ marker="o",
613
+ markersize=6.8,
614
+ markerfacecolor=color,
615
+ markeredgecolor=theme.card_bg,
616
+ markeredgewidth=1.8,
617
+ label=label,
618
+ zorder=3,
619
+ )
620
+
621
+ if dense:
622
+ spd_end = speedups[-1]
623
+ txt = f"{ys[-1]:.1f} ({spd_end:.2f}×)" if isinstance(spd_end, (int, float)) else f"{ys[-1]:.1f}"
624
+ end_labels.append((xs[-1], ys[-1], txt, color))
625
+ else:
626
+ for x, y, spd in zip(xs, ys, speedups):
627
+ if x == 0:
628
+ continue
629
+ txt = f"{y:.1f} ({spd:.2f}×)" if isinstance(spd, (int, float)) else f"{y:.1f}"
630
+ labels_by_x.setdefault(x, []).append((y, txt, color))
631
+
632
+ ax.set_xlabel("Draft Tokens (0 = No-Speculation Baseline)", labelpad=6)
633
+ ax.set_ylabel("Decode Speed (tokens / sec)", labelpad=6)
634
+ y_top = max(10.0, max_y * 1.18)
635
+ ax.set_ylim(0, y_top)
636
+
637
+ if all_x:
638
+ uniq_x = sorted(set(all_x))
639
+ ax.set_xticks(uniq_x)
640
+ span = max(uniq_x) - min(uniq_x) if len(uniq_x) > 1 else 2
641
+ right_pad = 0.34 * span if dense else 0.16 * span
642
+ ax.set_xlim(min(uniq_x) - 0.12 * span, max(uniq_x) + right_pad)
643
+
644
+ # Baseline tags cleanly above/beside x=0
645
+ if baseline_labels:
646
+ b_targets = _repel_y_positions(
647
+ [b[0] + y_top * 0.045 for b in baseline_labels],
648
+ y_min=y_top * 0.06,
649
+ y_max=y_top * 0.94,
650
+ min_gap=y_top * 0.075,
651
+ )
652
+ for (_, txt, col), py in zip(baseline_labels, b_targets):
653
+ ax.text(
654
+ 0,
655
+ py,
656
+ txt,
657
+ ha="center",
658
+ va="bottom",
659
+ fontsize=8.0,
660
+ fontweight="bold",
661
+ color=col,
662
+ path_effects=[pe.withStroke(linewidth=2.4, foreground=theme.card_bg)],
663
+ zorder=5,
664
+ )
665
+
666
+ if dense and end_labels:
667
+ x_end = max(uniq_x)
668
+ y_targets = _repel_y_positions(
669
+ [item[1] for item in end_labels],
670
+ y_min=y_top * 0.08,
671
+ y_max=y_top * 0.95,
672
+ min_gap=y_top * 0.072,
673
+ )
674
+ for (_, orig_y, txt, color), placed_y in zip(end_labels, y_targets):
675
+ if abs(placed_y - orig_y) > y_top * 0.02:
676
+ ax.plot(
677
+ [x_end + 0.02 * span, x_end + 0.055 * span],
678
+ [orig_y, placed_y],
679
+ color=color,
680
+ linewidth=0.9,
681
+ alpha=0.55,
682
+ zorder=4,
683
+ )
684
+ ax.text(
685
+ x_end + 0.065 * span,
686
+ placed_y,
687
+ txt,
688
+ va="center",
689
+ ha="left",
690
+ fontsize=8.1,
691
+ fontweight="bold",
692
+ color=color,
693
+ zorder=5,
694
+ )
695
+ else:
696
+ for x_val, items in labels_by_x.items():
697
+ y_targets = _repel_y_positions(
698
+ [it[0] + y_top * 0.04 for it in items],
699
+ y_min=y_top * 0.08,
700
+ y_max=y_top * 0.95,
701
+ min_gap=y_top * 0.082,
702
+ )
703
+ for (_, txt, color), placed_y in zip(items, y_targets):
704
+ ax.text(
705
+ x_val,
706
+ placed_y,
707
+ txt,
708
+ ha="center",
709
+ va="bottom",
710
+ fontsize=8.2,
711
+ fontweight="bold",
712
+ color=color,
713
+ path_effects=[pe.withStroke(linewidth=2.4, foreground=theme.card_bg)],
714
+ zorder=5,
715
+ )
716
+
717
+
718
+ def _draw_memory_panel(
719
+ ax: Axes,
720
+ rows: list[dict[str, Any]],
721
+ theme: Theme,
722
+ compact_map: dict[str, str],
723
+ ) -> None:
724
+ _style_card_axes(ax, theme)
725
+ ax.grid(axis="x", color=theme.grid, linestyle="-", linewidth=0.8, alpha=0.95, zorder=0)
726
+ ax.grid(axis="y", visible=False)
727
+
728
+ mem_by_key: dict[tuple[str, int], tuple[float, float | None]] = {}
729
+ for r in rows:
730
+ peak = r.get("gpu_memory_peak_mib")
731
+ if peak is None:
732
+ continue
733
+ short_m = compact_map.get(_full_model_name(r), _full_model_name(r))
734
+ key = (short_m, int(r.get("draft_n_max") or 0))
735
+ extra = r.get("speculator_extra_gpu_memory_mib")
736
+ prev = mem_by_key.get(key)
737
+ if prev is None or float(peak) > prev[0]:
738
+ mem_by_key[key] = (float(peak), float(extra) if extra is not None else None)
739
+
740
+ if not mem_by_key:
741
+ ax.text(
742
+ 0.5,
743
+ 0.5,
744
+ "No GPU memory readings recorded\n(run on NVIDIA GPU with draft_tokens including 0)",
745
+ ha="center",
746
+ va="center",
747
+ transform=ax.transAxes,
748
+ color=theme.text_muted,
749
+ fontsize=9.5,
750
+ )
751
+ ax.set_xticks([])
752
+ ax.set_yticks([])
753
+ return
754
+
755
+ items = sorted(mem_by_key.items(), key=lambda kv: (kv[0][0], kv[0][1]))
756
+ unique_models = {k[0] for k, _ in items}
757
+ labels: list[str] = []
758
+ base_gb: list[float] = []
759
+ extra_gb: list[float] = []
760
+ total_gb: list[float] = []
761
+
762
+ for (model_name, draft_n), (peak_mib, extra_mib) in items:
763
+ prefix = f"{model_name} · " if len(unique_models) > 1 else ""
764
+ step_lbl = "Base (0)" if draft_n == 0 else f"N={draft_n}"
765
+ labels.append(f"{prefix}{step_lbl}")
766
+ p_gb = peak_mib / 1024.0
767
+ total_gb.append(p_gb)
768
+ if extra_mib is not None and extra_mib > 0:
769
+ e_gb = extra_mib / 1024.0
770
+ base_gb.append(max(0.0, p_gb - e_gb))
771
+ extra_gb.append(e_gb)
772
+ else:
773
+ base_gb.append(p_gb)
774
+ extra_gb.append(0.0)
775
+
776
+ y_pos = np.arange(len(labels))
777
+ bar_h = 0.58
778
+
779
+ ax.barh(
780
+ y_pos,
781
+ base_gb,
782
+ height=bar_h,
783
+ color=theme.mem_base,
784
+ alpha=0.88,
785
+ label="Base Model + KV",
786
+ zorder=3,
787
+ )
788
+ has_extra = any(e > 0 for e in extra_gb)
789
+ if has_extra:
790
+ ax.barh(
791
+ y_pos,
792
+ extra_gb,
793
+ left=base_gb,
794
+ height=bar_h,
795
+ color=theme.mem_extra,
796
+ alpha=0.95,
797
+ label="Extra Speculator",
798
+ zorder=3,
799
+ )
800
+
801
+ max_gb = max(total_gb) if total_gb else 1.0
802
+ for idx, (tot, ext) in enumerate(zip(total_gb, extra_gb)):
803
+ base_txt = f"{tot:.2f} GB"
804
+ ax.text(
805
+ tot + max_gb * 0.02,
806
+ idx,
807
+ base_txt,
808
+ va="center",
809
+ ha="left",
810
+ fontsize=8.4,
811
+ fontweight="bold",
812
+ color=theme.text_primary,
813
+ zorder=5,
814
+ )
815
+ if ext > 0:
816
+ ax.text(
817
+ tot + max_gb * 0.21,
818
+ idx,
819
+ f"(+{ext:.2f} GB)",
820
+ va="center",
821
+ ha="left",
822
+ fontsize=8.1,
823
+ fontweight="bold",
824
+ color=theme.mem_extra,
825
+ zorder=5,
826
+ )
827
+
828
+ ax.set_yticks(y_pos)
829
+ ax.set_yticklabels(labels, fontsize=8.6, color=theme.text_secondary)
830
+ ax.invert_yaxis()
831
+ ax.set_xlabel("GPU Memory (GiB)", labelpad=6)
832
+ ax.set_xlim(0, max_gb * 1.46)
833
+ # Place compact inline legend cleanly above the bars (never collides with bars!)
834
+ ax.legend(
835
+ loc="upper right",
836
+ bbox_to_anchor=(1.0, 1.13),
837
+ ncol=2,
838
+ fontsize=8.1,
839
+ handlelength=1.2,
840
+ columnspacing=1.0,
841
+ frameon=False,
842
+ )
843
+
844
+
845
+ def _draw_matrix_panel(
846
+ ax: Axes,
847
+ series_map: dict[str, list[dict[str, Any]]],
848
+ theme: Theme,
849
+ ) -> None:
850
+ ax.set_facecolor(theme.card_bg)
851
+ for spine in ax.spines.values():
852
+ spine.set_visible(False)
853
+
854
+ series_labels = list(series_map.keys())
855
+ draft_ns = sorted(
856
+ {
857
+ int(r["draft_n_max"])
858
+ for srows in series_map.values()
859
+ for r in srows
860
+ if int(r.get("draft_n_max") or 0) > 0
861
+ }
862
+ )
863
+
864
+ if not series_labels or not draft_ns:
865
+ ax.text(0.5, 0.5, "No speculative steps to tabulate", ha="center", va="center", color=theme.text_muted)
866
+ ax.set_xticks([])
867
+ ax.set_yticks([])
868
+ return
869
+
870
+ grid = np.full((len(series_labels), len(draft_ns)), np.nan)
871
+ tps_grid: list[list[float | None]] = [[None for _ in draft_ns] for _ in series_labels]
872
+ spd_grid: list[list[float | None]] = [[None for _ in draft_ns] for _ in series_labels]
873
+
874
+ for i, label in enumerate(series_labels):
875
+ by_n = {int(r["draft_n_max"]): r for r in series_map[label]}
876
+ for j, n in enumerate(draft_ns):
877
+ row = by_n.get(n)
878
+ if row and row.get("acceptance_rate") is not None:
879
+ grid[i, j] = float(row["acceptance_rate"]) * 100.0
880
+ if row and row.get("avg_predicted_per_second") is not None:
881
+ tps_grid[i][j] = float(row["avg_predicted_per_second"])
882
+ if row and isinstance(row.get("speedup_vs_baseline"), (int, float)):
883
+ spd_grid[i][j] = float(row["speedup_vs_baseline"])
884
+
885
+ cmap = LinearSegmentedColormap.from_list(f"specbench_{theme.name}", list(theme.heatmap_stops))
886
+ ax.imshow(
887
+ np.ma.masked_invalid(grid),
888
+ cmap=cmap,
889
+ vmin=20,
890
+ vmax=95,
891
+ aspect="auto",
892
+ alpha=0.95,
893
+ )
894
+
895
+ for i in range(len(series_labels)):
896
+ for j in range(len(draft_ns)):
897
+ val = grid[i, j]
898
+ tps = tps_grid[i][j]
899
+ spd = spd_grid[i][j]
900
+ if np.isnan(val):
901
+ cell_text = "—"
902
+ txt_color = theme.text_muted
903
+ else:
904
+ line2_parts = []
905
+ if tps is not None:
906
+ line2_parts.append(f"{tps:.1f} t/s")
907
+ if spd is not None:
908
+ line2_parts.append(f"{spd:.2f}×")
909
+ cell_text = f"{val:.1f}%"
910
+ if line2_parts:
911
+ cell_text += f"\n{' · '.join(line2_parts)}"
912
+ if theme.name == "light":
913
+ txt_color = "#FFFFFF" if val >= 58.0 else "#0F172A"
914
+ else:
915
+ txt_color = "#0B1120" if val >= 68.0 else "#F8FAFC"
916
+ ax.text(
917
+ j,
918
+ i,
919
+ cell_text,
920
+ ha="center",
921
+ va="center",
922
+ fontsize=8.3,
923
+ fontweight="bold",
924
+ color=txt_color,
925
+ linespacing=1.25,
926
+ )
927
+
928
+ ax.set_xticks(range(len(draft_ns)))
929
+ ax.set_xticklabels([f"N={n}" for n in draft_ns], fontsize=9.0, fontweight="bold", color=theme.text_secondary)
930
+ ax.set_yticks(range(len(series_labels)))
931
+ ax.set_yticklabels(series_labels, fontsize=8.3, color=theme.text_secondary)
932
+ ax.tick_params(axis="both", length=0, pad=6)
933
+
934
+ # Crisp card-colored cell dividers
935
+ ax.set_xticks(np.arange(-0.5, len(draft_ns), 1), minor=True)
936
+ ax.set_yticks(np.arange(-0.5, len(series_labels), 1), minor=True)
937
+ ax.grid(which="minor", color=theme.card_bg, linestyle="-", linewidth=3.5)
938
+ ax.tick_params(which="minor", bottom=False, left=False)
939
+
940
+
941
+ def _build_header_strings(
942
+ rows: list[dict[str, Any]],
943
+ shared_base: str | None,
944
+ compact_map: dict[str, str],
945
+ custom_title: str | None,
946
+ ) -> tuple[str, str]:
947
+ full_models = sorted({_full_model_name(r) for r in rows})
948
+ spec_types = sorted(
949
+ {_short_spec_type(str(r.get("spec_type"))) for r in rows if str(r.get("spec_type") or "") not in {"", "none"}}
950
+ )
951
+ hardwares = sorted({str(r.get("hardware")) for r in rows if r.get("hardware")})
952
+ versions = sorted({str(r.get("llama_version")) for r in rows if r.get("llama_version")})
953
+
954
+ if custom_title:
955
+ title = custom_title
956
+ elif len(full_models) == 1:
957
+ spec_str = f" ({', '.join(spec_types)})" if spec_types else ""
958
+ title = f"Speculative Decoding Benchmark — {full_models[0]}{spec_str}"
959
+ elif shared_base:
960
+ variants = " vs ".join(compact_map[m] for m in full_models[:4])
961
+ title = f"Speculative Decoding Benchmark — {shared_base} ({variants})"
962
+ else:
963
+ title = f"Speculative Decoding Benchmark — {' vs '.join(full_models[:3])}"
964
+
965
+ meta_parts: list[str] = []
966
+ if hardwares:
967
+ meta_parts.append(f"Hardware: {hardwares[0]}")
968
+ if versions:
969
+ meta_parts.append(f"llama.cpp {versions[0]}")
970
+ caps = sorted({_format_capability(str(r.get("capability"))) for r in rows if r.get("capability")})
971
+ if caps:
972
+ meta_parts.append(f"Suites: {', '.join(caps)}")
973
+ subtitle = " · ".join(meta_parts)
974
+ return title, subtitle
975
+
976
+
977
+ def _save_single_chart(
978
+ draw_fn: Any,
979
+ out_path: Path,
980
+ theme: Theme,
981
+ header_title: str,
982
+ subtitle: str,
983
+ panel_title: str,
984
+ *,
985
+ panel_subtitle: str | None = None,
986
+ legend_entries: list[tuple[str, str]] | None = None,
987
+ inner_left: float = 0.095,
988
+ ) -> Path:
989
+ n_leg = len(legend_entries) if legend_entries else 0
990
+ leg_ncols = min(max(n_leg, 1), 3)
991
+ leg_rows = math.ceil(n_leg / leg_ncols) if n_leg else 0
992
+ legend_h = 0.045 * leg_rows + (0.018 if leg_rows else 0.0)
993
+
994
+ fig_h = 5.8 + 0.30 * leg_rows
995
+ fig = plt.figure(figsize=(10.2, fig_h), dpi=240)
996
+ fig.patch.set_facecolor(theme.canvas_bg)
997
+
998
+ fig.text(0.035, 0.955, header_title, fontsize=14.0, fontweight="bold", color=theme.text_primary, va="top")
999
+ if subtitle:
1000
+ fig.text(0.035, 0.905, subtitle, fontsize=9.0, color=theme.text_muted, va="top")
1001
+
1002
+ card_top = 0.855 - legend_h
1003
+ if legend_entries:
1004
+ from matplotlib.lines import Line2D
1005
+
1006
+ handles = [
1007
+ Line2D(
1008
+ [0],
1009
+ [0],
1010
+ color=col,
1011
+ lw=2.5,
1012
+ marker="o",
1013
+ markersize=6,
1014
+ markerfacecolor=col,
1015
+ markeredgecolor=theme.card_bg,
1016
+ markeredgewidth=1.4,
1017
+ )
1018
+ for _, col in legend_entries
1019
+ ]
1020
+ labels = [lbl for lbl, _ in legend_entries]
1021
+ fig.legend(
1022
+ handles,
1023
+ labels,
1024
+ loc="upper left",
1025
+ bbox_to_anchor=(0.032, 0.868),
1026
+ ncol=leg_ncols,
1027
+ fontsize=8.6,
1028
+ frameon=False,
1029
+ handlelength=1.8,
1030
+ columnspacing=1.4,
1031
+ )
1032
+
1033
+ card_rect = (0.03, 0.04, 0.94, card_top - 0.04)
1034
+ ax = _create_card_panel(
1035
+ fig,
1036
+ card_rect,
1037
+ theme,
1038
+ title=panel_title,
1039
+ subtitle=panel_subtitle,
1040
+ inner_left=inner_left,
1041
+ inner_right=0.035,
1042
+ inner_top=0.095 if panel_subtitle else 0.075,
1043
+ inner_bottom=0.095,
1044
+ )
1045
+ draw_fn(ax)
1046
+
1047
+ fig.savefig(out_path, dpi=240, facecolor=theme.canvas_bg)
1048
+ plt.close(fig)
1049
+ return out_path
1050
+
1051
+
1052
+ def generate_visualizations(
1053
+ rows: list[dict[str, Any]],
1054
+ output_dir: str | Path,
1055
+ *,
1056
+ theme_name: ThemeName = "dark",
1057
+ fmt: Literal["png", "svg"] = "png",
1058
+ title: str | None = None,
1059
+ ) -> dict[str, Path]:
1060
+ """Generate a polished 2x2 benchmark dashboard and standalone charts locally."""
1061
+ theme = THEMES[theme_name]
1062
+ _configure_matplotlib(theme)
1063
+
1064
+ out_dir = Path(output_dir)
1065
+ out_dir.mkdir(parents=True, exist_ok=True)
1066
+
1067
+ shared_base, series_map, compact_map = _series_key_and_label(rows)
1068
+ color_map = {
1069
+ label: theme.palette[idx % len(theme.palette)]
1070
+ for idx, label in enumerate(series_map.keys())
1071
+ }
1072
+ header_title, subtitle = _build_header_strings(rows, shared_base, compact_map, title)
1073
+
1074
+ # Compute exact dynamic layout geometry for 2x2 dashboard (zero collisions possible)
1075
+ series_labels = list(series_map.keys())
1076
+ leg_ncols = min(max(len(series_labels), 1), 3)
1077
+ leg_rows = math.ceil(len(series_labels) / leg_ncols) if series_labels else 0
1078
+ legend_band = 0.028 * leg_rows + (0.016 if leg_rows else 0.0)
1079
+
1080
+ fig_h = 10.6 + 0.32 * max(leg_rows - 1, 0)
1081
+ fig = plt.figure(figsize=(16.0, fig_h), dpi=240)
1082
+ fig.patch.set_facecolor(theme.canvas_bg)
1083
+
1084
+ # Header
1085
+ fig.text(0.028, 0.968, header_title, fontsize=16.5, fontweight="bold", color=theme.text_primary, va="top")
1086
+ if subtitle:
1087
+ fig.text(0.028, 0.935, subtitle, fontsize=9.8, color=theme.text_muted, va="top")
1088
+
1089
+ # Shared Legend Strip cleanly between subtitle and top row of cards
1090
+ if series_labels:
1091
+ from matplotlib.lines import Line2D
1092
+
1093
+ handles = [
1094
+ Line2D(
1095
+ [0],
1096
+ [0],
1097
+ color=color_map[lbl],
1098
+ lw=2.6,
1099
+ marker="o",
1100
+ markersize=6.5,
1101
+ markerfacecolor=color_map[lbl],
1102
+ markeredgecolor=theme.card_bg,
1103
+ markeredgewidth=1.4,
1104
+ )
1105
+ for lbl in series_labels
1106
+ ]
1107
+ fig.legend(
1108
+ handles,
1109
+ series_labels,
1110
+ loc="upper left",
1111
+ bbox_to_anchor=(0.025, 0.910),
1112
+ ncol=leg_ncols,
1113
+ fontsize=9.1,
1114
+ frameon=False,
1115
+ handlelength=2.0,
1116
+ columnspacing=1.8,
1117
+ )
1118
+
1119
+ # 2x2 Card Grid in figure coordinates
1120
+ margin_x = 0.026
1121
+ gap_x = 0.022
1122
+ gap_y = 0.028
1123
+ bottom_y = 0.030
1124
+ top_y = 0.895 - legend_band
1125
+ card_w = (1.0 - 2 * margin_x - gap_x) / 2.0
1126
+ card_h = (top_y - bottom_y - gap_y) / 2.0
1127
+
1128
+ row1_y = bottom_y + card_h + gap_y
1129
+ row2_y = bottom_y
1130
+ col1_x = margin_x
1131
+ col2_x = margin_x + card_w + gap_x
1132
+
1133
+ # Adaptive left padding for bottom panels based on longest tick label
1134
+ max_matrix_lbl = max((len(lbl) for lbl in series_labels), default=12)
1135
+ matrix_inner_left = min(0.185, max(0.095, 0.0056 * max_matrix_lbl + 0.022))
1136
+
1137
+ max_mem_lbl = max((len(v) + 9 for v in compact_map.values()), default=14)
1138
+ mem_inner_left = min(0.155, max(0.088, 0.0054 * max_mem_lbl + 0.022))
1139
+
1140
+ ax_acc = _create_card_panel(
1141
+ fig,
1142
+ (col1_x, row1_y, card_w, card_h),
1143
+ theme,
1144
+ title="Token Acceptance Rate vs Draft Tokens",
1145
+ inner_left=0.056,
1146
+ inner_right=0.026,
1147
+ inner_top=0.058,
1148
+ inner_bottom=0.056,
1149
+ )
1150
+ ax_tps = _create_card_panel(
1151
+ fig,
1152
+ (col2_x, row1_y, card_w, card_h),
1153
+ theme,
1154
+ title="Decode Throughput & Speedup",
1155
+ inner_left=0.056,
1156
+ inner_right=0.026,
1157
+ inner_top=0.058,
1158
+ inner_bottom=0.056,
1159
+ )
1160
+ ax_mem = _create_card_panel(
1161
+ fig,
1162
+ (col1_x, row2_y, card_w, card_h),
1163
+ theme,
1164
+ title="Peak GPU Memory & Speculator Overhead",
1165
+ inner_left=mem_inner_left,
1166
+ inner_right=0.026,
1167
+ inner_top=0.072,
1168
+ inner_bottom=0.056,
1169
+ )
1170
+ ax_mat = _create_card_panel(
1171
+ fig,
1172
+ (col2_x, row2_y, card_w, card_h),
1173
+ theme,
1174
+ title="Acceptance & Speedup Matrix",
1175
+ inner_left=matrix_inner_left,
1176
+ inner_right=0.024,
1177
+ inner_top=0.058,
1178
+ inner_bottom=0.048,
1179
+ )
1180
+
1181
+ _draw_acceptance_panel(ax_acc, series_map, theme, color_map)
1182
+ _draw_throughput_panel(ax_tps, series_map, theme, color_map)
1183
+ _draw_memory_panel(ax_mem, rows, theme, compact_map)
1184
+ _draw_matrix_panel(ax_mat, series_map, theme)
1185
+
1186
+ dashboard_path = out_dir / f"dashboard.{fmt}"
1187
+ fig.savefig(dashboard_path, dpi=240, facecolor=theme.canvas_bg)
1188
+ plt.close(fig)
1189
+
1190
+ # Standalone shareable charts
1191
+ legend_entries = [(lbl, color_map[lbl]) for lbl in series_labels]
1192
+ acc_path = _save_single_chart(
1193
+ lambda ax: _draw_acceptance_panel(ax, series_map, theme, color_map),
1194
+ out_dir / f"acceptance_rate.{fmt}",
1195
+ theme,
1196
+ header_title,
1197
+ subtitle,
1198
+ "Token Acceptance Rate vs Draft Tokens",
1199
+ legend_entries=legend_entries,
1200
+ inner_left=0.088,
1201
+ )
1202
+ tps_path = _save_single_chart(
1203
+ lambda ax: _draw_throughput_panel(ax, series_map, theme, color_map),
1204
+ out_dir / f"throughput_speedup.{fmt}",
1205
+ theme,
1206
+ header_title,
1207
+ subtitle,
1208
+ "Decode Throughput & Speedup",
1209
+ legend_entries=legend_entries,
1210
+ inner_left=0.088,
1211
+ )
1212
+ mem_path = _save_single_chart(
1213
+ lambda ax: _draw_memory_panel(ax, rows, theme, compact_map),
1214
+ out_dir / f"memory_overhead.{fmt}",
1215
+ theme,
1216
+ header_title,
1217
+ subtitle,
1218
+ "Peak GPU Memory & Speculator Overhead",
1219
+ legend_entries=None,
1220
+ inner_left=min(0.24, max(0.14, 0.0082 * max_mem_lbl + 0.03)),
1221
+ )
1222
+
1223
+ return {
1224
+ "dashboard": dashboard_path,
1225
+ "acceptance_rate": acc_path,
1226
+ "throughput_speedup": tps_path,
1227
+ "memory_overhead": mem_path,
1228
+ }