amagi-draftbench 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,6 @@
1
+ """amagi-draftbench: find the draft model (or n-gram lookup) that actually speeds up your local LLM.
2
+
3
+ Fork of draftbench by Alex Ziskind (MIT), github.com/alexziskind1/draftbench.
4
+ """
5
+
6
+ __version__ = "0.1.0"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,165 @@
1
+ """Benchmark one running OpenAI-compatible endpoint: TTFT, decode tok/s and draft acceptance rate.
2
+
3
+ Based on bench.py from draftbench by Alex Ziskind (MIT). Rewritten on the standard library, with server-side
4
+ timings preferred over client chunk counting when the server reports them (llama.cpp does).
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import statistics
9
+ import sys
10
+ import time
11
+ from dataclasses import dataclass, field
12
+
13
+ from . import stream
14
+
15
+
16
+ @dataclass
17
+ class RunSummary:
18
+ label: str
19
+ metrics: list = field(default_factory=list) # RequestMetrics
20
+ errors: list = field(default_factory=list) # str
21
+ windows: list = field(default_factory=list) # (wall start, wall end) of each successful request
22
+
23
+ def values(self, key: str) -> list:
24
+ return [getattr(m, key) for m in self.metrics if getattr(m, key) is not None]
25
+
26
+ def stat(self, key: str) -> dict:
27
+ vals = sorted(self.values(key))
28
+ if not vals:
29
+ return {}
30
+ return {
31
+ "min": vals[0],
32
+ "max": vals[-1],
33
+ "mean": statistics.mean(vals),
34
+ "median": statistics.median(vals),
35
+ "p95": vals[min(len(vals) - 1, int(round(0.95 * (len(vals) - 1))))],
36
+ }
37
+
38
+ @property
39
+ def gen_tokens(self) -> int:
40
+ return sum(m.completion_tokens for m in self.metrics)
41
+
42
+ @property
43
+ def decode_tps(self) -> float | None:
44
+ """Generated tokens / generation time. Uses the server's own timings when every request has them
45
+ (llama.cpp), otherwise the client-side mean. None when nothing succeeded."""
46
+ if not self.metrics:
47
+ return None
48
+ if all(m.predicted_n and m.predicted_ms for m in self.metrics):
49
+ ms = sum(m.predicted_ms for m in self.metrics)
50
+ return sum(m.predicted_n for m in self.metrics) / (ms / 1000.0) if ms > 0 else None
51
+ tps = self.values("client_tps")
52
+ return statistics.mean(tps) if tps else None
53
+
54
+ @property
55
+ def decode_source(self) -> str:
56
+ if self.metrics and all(m.predicted_n and m.predicted_ms for m in self.metrics):
57
+ return "server"
58
+ return "client"
59
+
60
+ @property
61
+ def acceptance_rate(self) -> float | None:
62
+ drafted = sum(m.draft_n or 0 for m in self.metrics)
63
+ if not drafted:
64
+ return None
65
+ return sum(m.draft_accepted or 0 for m in self.metrics) / drafted
66
+
67
+ def summary(self) -> dict:
68
+ ttft = self.stat("ttft")
69
+ total = self.stat("total_time")
70
+ client = self.stat("client_tps")
71
+ return {
72
+ "requests": len(self.metrics) + len(self.errors),
73
+ "errors": len(self.errors),
74
+ "gen_tokens": self.gen_tokens,
75
+ "decode_tps": _r(self.decode_tps, 2),
76
+ "decode_source": self.decode_source,
77
+ "client_tps_mean": _r(client.get("mean"), 2),
78
+ "client_tps_median": _r(client.get("median"), 2),
79
+ "mean_ttft": _r(ttft.get("mean"), 3),
80
+ "mean_total_time": _r(total.get("mean"), 2),
81
+ "acceptance_rate": _r(self.acceptance_rate, 4),
82
+ "draft_n": sum(m.draft_n or 0 for m in self.metrics) or None,
83
+ "draft_accepted": sum(m.draft_accepted or 0 for m in self.metrics) or None,
84
+ }
85
+
86
+ def table(self) -> str:
87
+ rows = []
88
+ for key, unit in (("ttft", "s"), ("client_tps", "tok/s"), ("server_tps", "tok/s"), ("total_time", "s"),
89
+ ("completion_tokens", "tok")):
90
+ s = self.stat(key)
91
+ if not s:
92
+ continue
93
+ rows.append(f" {key:<18s} min={s['min']:>8.2f}{unit} median={s['median']:>8.2f}{unit} "
94
+ f"mean={s['mean']:>8.2f}{unit} max={s['max']:>8.2f}{unit}")
95
+ acc = self.acceptance_rate
96
+ if acc is not None:
97
+ rows.append(f" {'acceptance_rate':<18s} {acc:.1%}")
98
+ if self.errors:
99
+ rows.append(f" errors {len(self.errors)}: {self.errors[0]}")
100
+ return "\n".join(rows)
101
+
102
+
103
+ def _r(v, nd):
104
+ return round(v, nd) if isinstance(v, (int, float)) else None
105
+
106
+
107
+ def run_bench(label: str, base_url: str, model: str, prompts: dict, runs: int = 1, max_tokens: int = 512,
108
+ temperature: float = 0.0, api_key: str | None = None, warmup: int = 0, timeout: float = 600,
109
+ out=None, keep_text: bool = True, extra_body: dict | None = None,
110
+ before_request=None, index_offset: int = 0, total: int | None = None) -> RunSummary:
111
+ """Send every prompt `runs` times (after `warmup` unscored requests) and collect metrics.
112
+
113
+ `before_request()` runs before each scored request (the sweep uses it to let a hot card cool down).
114
+ `index_offset` and `total` only change the "request i/N" progress text, for callers that split a run up.
115
+ """
116
+ out = sys.stdout if out is None else out
117
+ summary = RunSummary(label=label)
118
+ items = list(prompts.items())
119
+ if warmup and items:
120
+ for _ in range(warmup):
121
+ try:
122
+ stream.stream_chat(base_url, model, items[0][1], max_tokens=min(max_tokens, 32),
123
+ temperature=temperature, api_key=api_key, timeout=timeout,
124
+ extra_body=extra_body)
125
+ except Exception: # noqa: BLE001 - a failed warm-up shows up again in the scored requests
126
+ pass
127
+ total = total or runs * len(items)
128
+ idx = index_offset
129
+ for _ in range(runs):
130
+ for pid, text in items:
131
+ idx += 1
132
+ if before_request is not None:
133
+ before_request()
134
+ out.write(f" [{label}] request {idx}/{total} ({pid}) ... ")
135
+ out.flush()
136
+ w0 = time.time()
137
+ try:
138
+ m = stream.stream_chat(base_url, model, text, max_tokens=max_tokens, temperature=temperature,
139
+ api_key=api_key, timeout=timeout, prompt_id=pid, extra_body=extra_body)
140
+ except stream.ServerError as e:
141
+ summary.errors.append(str(e))
142
+ out.write(f"ERROR {e}\n")
143
+ continue
144
+ except OSError as e:
145
+ summary.errors.append(f"connection: {e}")
146
+ out.write(f"ERROR connection: {e}\n")
147
+ continue
148
+ if not keep_text:
149
+ m.text = m.reasoning = ""
150
+ summary.metrics.append(m)
151
+ summary.windows.append((w0, time.time()))
152
+ rate = m.server_tps if m.server_tps else m.client_tps
153
+ extra = ""
154
+ if m.draft_n:
155
+ extra = f" accept={m.draft_accepted / m.draft_n:.0%}"
156
+ out.write(f"ttft={m.ttft:.3f}s {rate:.1f} tok/s tokens={m.completion_tokens}{extra}\n")
157
+ return summary
158
+
159
+
160
+ def pick_model(base_url: str, model: str | None, api_key: str | None = None) -> str:
161
+ """Use the given model name, or ask the server (GET /v1/models) and take the first one."""
162
+ if model:
163
+ return model
164
+ ids = stream.list_models(base_url, api_key)
165
+ return ids[0] if ids else "default"
@@ -0,0 +1,283 @@
1
+ """amagi-draftbench command line: bench, sweep, report, recommend, find-server, init-config."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import os
7
+ import sys
8
+
9
+ from . import __version__, bench, power, prompts, report, servers, stream, sweep
10
+
11
+
12
+ def _prompts(args) -> dict:
13
+ if args.prompt:
14
+ return prompts.custom(args.prompt)
15
+ return prompts.get(args.prompts)
16
+
17
+
18
+ def _extra_body(args) -> dict | None:
19
+ body = json.loads(args.extra_body) if args.extra_body else {}
20
+ if not isinstance(body, dict):
21
+ raise ValueError("--extra-body must be a JSON object")
22
+ if args.no_think:
23
+ body.setdefault("chat_template_kwargs", {})["enable_thinking"] = False
24
+ return body or None
25
+
26
+
27
+ def cmd_bench(args) -> int:
28
+ chosen = _prompts(args)
29
+ targets = [("server", args.url)]
30
+ if args.compare_url:
31
+ targets = [("baseline", args.compare_url), ("draft", args.url)]
32
+ results = {}
33
+ for label, url in targets:
34
+ base = stream.normalize_base_url(url)
35
+ model = bench.pick_model(base, args.model, args.api_key)
36
+ print(f"\n{label}: {base} model={model}")
37
+ summary = bench.run_bench(label, base, model, chosen, runs=args.runs, max_tokens=args.max_tokens,
38
+ temperature=args.temperature, api_key=args.api_key, warmup=args.warmup,
39
+ timeout=args.timeout, extra_body=_extra_body(args))
40
+ print(summary.table())
41
+ results[label] = summary
42
+ out = {k: v.summary() for k, v in results.items()}
43
+ if args.compare_url and out["baseline"]["decode_tps"] and out["draft"]["decode_tps"]:
44
+ sp = out["draft"]["decode_tps"] / out["baseline"]["decode_tps"]
45
+ out["speedup"] = round(sp, 3)
46
+ print(f"\nSpeedup: {sp:.2f}x ({out['baseline']['decode_tps']:.1f} -> {out['draft']['decode_tps']:.1f} tok/s)")
47
+ if args.json:
48
+ with open(args.json, "w", encoding="utf-8") as f:
49
+ json.dump({"tool": f"amagi-draftbench {__version__}", **out,
50
+ "requests": {k: [m.as_dict() for m in v.metrics] for k, v in results.items()}}, f, indent=2)
51
+ print(f"Saved {args.json}")
52
+ failed = any(not v.metrics for v in results.values())
53
+ return 1 if failed else 0
54
+
55
+
56
+ def _sampler(args):
57
+ if args.no_power:
58
+ return None
59
+ s = power.GpuSampler(args.smi, gpu=args.gpu, temp_cmd=args.temp_cmd, abort_core_c=args.abort_core,
60
+ abort_mem_c=args.abort_mem)
61
+ if s.snapshot() is None:
62
+ print(f"note: no reading from `{args.smi}`, so no power/VRAM numbers (use --no-power to hide this)")
63
+ return None
64
+ return s.start()
65
+
66
+
67
+ def cmd_sweep(args) -> int:
68
+ paths = list(args.configs)
69
+ if args.config_dir:
70
+ paths += sweep.configs_in(args.config_dir)
71
+ if not paths:
72
+ print("no config given: pass config files or --config-dir (amagi-draftbench init-config writes one)")
73
+ return 2
74
+ if args.out and len(paths) > 1:
75
+ print("-o/--out works with one config; use --out-dir for several")
76
+ return 2
77
+ try:
78
+ cfgs = [(p, sweep.load_config(p)) for p in paths]
79
+ except sweep.ConfigError as e:
80
+ print(f"config error: {e}")
81
+ return 2
82
+ sampler = None if args.dry_run else _sampler(args)
83
+ status = 0
84
+ try:
85
+ for p, cfg in cfgs:
86
+ out = args.out or sweep.default_results_path(cfg, args.out_dir)
87
+ rows = sweep.run_sweep(cfg, out, sampler=sampler, dry_run=args.dry_run, log_dir=args.log_dir,
88
+ pause=args.pause, cool_at=args.cool_at, cool_to=args.cool_to)
89
+ if not args.dry_run:
90
+ print(f"\nSaved {len(rows)} results to {out}")
91
+ if rows:
92
+ print("\n" + report.markdown(report.load([out])))
93
+ if sampler is not None and sampler.too_hot:
94
+ status = 3
95
+ break
96
+ finally:
97
+ if sampler is not None:
98
+ sampler.stop()
99
+ return status
100
+
101
+
102
+ def _result_paths(args) -> list:
103
+ paths = []
104
+ for p in args.results:
105
+ if os.path.isdir(p):
106
+ paths += sorted(os.path.join(p, f) for f in os.listdir(p) if f.endswith(".json"))
107
+ else:
108
+ paths.append(p)
109
+ return paths
110
+
111
+
112
+ def cmd_report(args) -> int:
113
+ paths = _result_paths(args)
114
+ if not paths:
115
+ print("no result files found")
116
+ return 2
117
+ data = report.load(paths)
118
+ md = report.markdown(data)
119
+ if args.by_prompt:
120
+ md += "\n" + report.by_prompt(data)
121
+ print(md)
122
+ if args.md:
123
+ with open(args.md, "w", encoding="utf-8") as f:
124
+ f.write(md)
125
+ print(f"Saved {args.md}")
126
+ if args.html:
127
+ with open(args.html, "w", encoding="utf-8") as f:
128
+ f.write(report.html_report(data))
129
+ print(f"Saved {args.html}")
130
+ return 0
131
+
132
+
133
+ def cmd_recommend(args) -> int:
134
+ paths = _result_paths(args)
135
+ if not paths:
136
+ print("no result files found")
137
+ return 2
138
+ try:
139
+ budgets = [float(b) for b in args.budgets.split(",") if b.strip()]
140
+ except ValueError:
141
+ print(f"--budgets must be numbers like 8,12,16,24, got {args.budgets!r}")
142
+ return 2
143
+ print(report.recommend_text(report.recommend(report.load(paths), budgets, args.min_gain)), end="")
144
+ print("\nVRAM is the measured peak for that run unless marked est. (file sizes + 1 GiB).")
145
+ return 0
146
+
147
+
148
+ def cmd_find_server(args) -> int:
149
+ path = servers.find_llama_server(args.path)
150
+ if not path:
151
+ print("llama-server not found on PATH or in the usual build folders; pass its path in settings.llama_bin")
152
+ return 1
153
+ f = servers.llama_features([path])
154
+ print(path)
155
+ print(f" --spec-type (n-gram drafting): {'yes' if f.spec_type else 'no'}")
156
+ if f.ngram_types:
157
+ print(f" n-gram types: {', '.join(f.ngram_types)}")
158
+ print(f" draft size flag: {f.draft_n_max_flag}")
159
+ print(f" -np (slots): {'yes' if f.parallel else 'no'}")
160
+ return 0
161
+
162
+
163
+ def cmd_init_config(args) -> int:
164
+ cfg = {
165
+ "name": args.name,
166
+ "hardware": args.hardware,
167
+ "backend": args.backend,
168
+ "targets": [{"label": os.path.basename(t), "path": t} for t in (args.target or ["/path/to/target.gguf"])],
169
+ "drafts": [{"label": os.path.basename(d), "path": d} for d in (args.draft or [])],
170
+ "settings": {"runs": 1, "max_tokens": 512, "temperature": 0.0, "prompts": "all", "port": 8080},
171
+ }
172
+ if args.ngram:
173
+ cfg["drafts"].append({"label": "ngram-mod", "type": "ngram"})
174
+ if not cfg["drafts"]:
175
+ cfg["drafts"] = [{"label": "draft", "path": "/path/to/draft.gguf"}, {"label": "ngram-mod", "type": "ngram"}]
176
+ if args.backend == "llamacpp":
177
+ cfg["settings"]["gpu_layers"] = 99
178
+ text = json.dumps(cfg, indent=2) + "\n"
179
+ if args.out:
180
+ if os.path.exists(args.out) and not args.force:
181
+ print(f"{args.out} exists; pass --force to overwrite")
182
+ return 1
183
+ os.makedirs(os.path.dirname(args.out) or ".", exist_ok=True)
184
+ with open(args.out, "w", encoding="utf-8") as f:
185
+ f.write(text)
186
+ print(f"Wrote {args.out}")
187
+ else:
188
+ sys.stdout.write(text)
189
+ return 0
190
+
191
+
192
+ def build_parser() -> argparse.ArgumentParser:
193
+ p = argparse.ArgumentParser(prog="amagi-draftbench",
194
+ description="Find the draft model (or n-gram lookup) that speeds up your local LLM.")
195
+ p.add_argument("--version", action="version", version=f"amagi-draftbench {__version__}")
196
+ sub = p.add_subparsers(dest="cmd")
197
+
198
+ b = sub.add_parser("bench", help="benchmark a server that is already running")
199
+ b.add_argument("--url", default="http://127.0.0.1:8080", help="server address (default %(default)s)")
200
+ b.add_argument("--compare-url", help="a second server without a draft; prints the speedup")
201
+ b.add_argument("--model", help="model name to send (default: first one the server lists)")
202
+ b.add_argument("--runs", type=int, default=1, help="times to send each prompt (default 1)")
203
+ b.add_argument("--max-tokens", type=int, default=512)
204
+ b.add_argument("--temperature", type=float, default=0.0)
205
+ b.add_argument("--prompts", default="default", choices=sorted(prompts.SETS), help="built-in prompt set")
206
+ b.add_argument("--prompt", action="append", help="your own prompt (repeat for more); replaces --prompts")
207
+ b.add_argument("--warmup", type=int, default=1, help="unscored warm-up requests (default 1)")
208
+ b.add_argument("--timeout", type=float, default=600)
209
+ b.add_argument("--api-key", default=os.environ.get("DRAFTBENCH_API_KEY"), help="bearer token if the server needs one (env DRAFTBENCH_API_KEY)")
210
+ b.add_argument("--no-think", action="store_true", help="ask Qwen3-style models not to think "
211
+ "(chat_template_kwargs.enable_thinking=false)")
212
+ b.add_argument("--extra-body", help="JSON merged into every request body")
213
+ b.add_argument("--json", help="also save the numbers to this file")
214
+ b.set_defaults(func=cmd_bench)
215
+
216
+ s = sub.add_parser("sweep", help="start the server for every target x draft in a config and benchmark each")
217
+ s.add_argument("configs", nargs="*", help="sweep config JSON files")
218
+ s.add_argument("--config-dir", help="run every *.json in this folder (except example*)")
219
+ s.add_argument("-o", "--out", help="results file (one config only)")
220
+ s.add_argument("--out-dir", default="results", help="results folder (default %(default)s)")
221
+ s.add_argument("--dry-run", action="store_true", help="print the server commands and exit")
222
+ s.add_argument("--smi", default="nvidia-smi", help="nvidia-smi command, e.g. 'ssh box nvidia-smi'")
223
+ s.add_argument("--gpu", type=int, default=0, help="GPU index for power/VRAM sampling")
224
+ s.add_argument("--no-power", action="store_true", help="skip power, tok/J and VRAM sampling")
225
+ s.add_argument("--temp-cmd", help="command that prints memory temperature (e.g. a GDDR6X reader)")
226
+ s.add_argument("--abort-core", type=float, default=87.0, help="stop the sweep at this core temp C")
227
+ s.add_argument("--abort-mem", type=float, default=106.0, help="stop the sweep at this memory temp C")
228
+ s.add_argument("--cool-at", type=float,
229
+ help="before each request, wait if memory or core temp is at or above this C")
230
+ s.add_argument("--cool-to", type=float, help="resume once temps are at or below this C (default: cool-at - 8)")
231
+ s.add_argument("--pause", type=float, default=3.0, help="seconds between runs (default 3)")
232
+ s.add_argument("--log-dir", help="where server logs go (default: temp folder)")
233
+ s.set_defaults(func=cmd_sweep)
234
+
235
+ r = sub.add_parser("report", help="Markdown table (and optional HTML chart) from result files")
236
+ r.add_argument("results", nargs="+", help="result JSON files or folders")
237
+ r.add_argument("--md", help="save the Markdown here")
238
+ r.add_argument("--html", help="save an HTML chart here")
239
+ r.add_argument("--by-prompt", action="store_true", help="add a tok/s-per-prompt table")
240
+ r.set_defaults(func=cmd_report)
241
+
242
+ rc = sub.add_parser("recommend", help="best draft per VRAM budget, from measured results")
243
+ rc.add_argument("results", nargs="+", help="result JSON files or folders")
244
+ rc.add_argument("--budgets", default="8,12,16,24", help="card sizes in GB (default %(default)s)")
245
+ rc.add_argument("--min-gain", type=float, default=report.MIN_GAIN,
246
+ help="a draft must be this many times faster than no draft to be picked (default %(default)s)")
247
+ rc.set_defaults(func=cmd_recommend)
248
+
249
+ f = sub.add_parser("find-server", help="locate llama-server and show which draft features it has")
250
+ f.add_argument("path", nargs="?", help="check this binary instead of searching")
251
+ f.set_defaults(func=cmd_find_server)
252
+
253
+ i = sub.add_parser("init-config", help="write a starter sweep config")
254
+ i.add_argument("--target", action="append", help="target GGUF path (repeat for more)")
255
+ i.add_argument("--draft", action="append", help="draft GGUF path (repeat for more)")
256
+ i.add_argument("--ngram", action="store_true", help="add an n-gram (no draft model) run")
257
+ i.add_argument("--backend", default="llamacpp", choices=["llamacpp", "vllm", "command"])
258
+ i.add_argument("--name", default="my-sweep")
259
+ i.add_argument("--hardware", default="my-gpu")
260
+ i.add_argument("-o", "--out", help="write here instead of stdout")
261
+ i.add_argument("--force", action="store_true")
262
+ i.set_defaults(func=cmd_init_config)
263
+ return p
264
+
265
+
266
+ def main(argv=None) -> int:
267
+ parser = build_parser()
268
+ args = parser.parse_args(argv)
269
+ if not getattr(args, "func", None):
270
+ parser.print_help()
271
+ return 0
272
+ try:
273
+ return args.func(args)
274
+ except KeyboardInterrupt:
275
+ print("\ninterrupted")
276
+ return 130
277
+ except ValueError as e:
278
+ print(f"error: {e}")
279
+ return 2
280
+
281
+
282
+ if __name__ == "__main__": # pragma: no cover
283
+ raise SystemExit(main())
@@ -0,0 +1,191 @@
1
+ """GPU power, VRAM and temperature sampling through nvidia-smi, for tokens-per-joule and peak VRAM.
2
+
3
+ nvidia-smi can be local or remote: pass e.g. `ssh gpu-box nvidia-smi`. An optional temperature command
4
+ (for GDDR6X junction temperature on RTX 30/40 cards, which nvidia-smi does not report) can abort a sweep
5
+ before the memory gets too hot.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ import shlex
11
+ import subprocess
12
+ import threading
13
+ import time
14
+
15
+ FIELDS = "power.draw,memory.used,temperature.gpu"
16
+
17
+
18
+ def parse_smi_line(line: str):
19
+ """'123.45, 20480, 61' -> (123.45, 20480.0, 61.0); None for headers, blanks and [N/A]."""
20
+ parts = [p.strip() for p in line.strip().split(",")]
21
+ if len(parts) < 3:
22
+ return None
23
+ try:
24
+ return tuple(float(p) for p in parts[:3])
25
+ except ValueError:
26
+ return None
27
+
28
+
29
+ def parse_temp(text: str):
30
+ """Last temperature in command output: '... 92°C' / '92 C' / a bare '92'. None if there is none."""
31
+ hits = re.findall(r"(\d+(?:\.\d+)?)\s*(?:°\s*C|C\b)", text)
32
+ if hits:
33
+ return float(hits[-1])
34
+ bare = text.strip()
35
+ try:
36
+ return float(bare)
37
+ except ValueError:
38
+ return None
39
+
40
+
41
+ def energy_j(samples, t0: float, t1: float) -> float:
42
+ """Trapezoid integral of watts over [t0, t1]; samples are (t, watts, ...) sorted by t. Endpoints are
43
+ interpolated so a short window between two samples still gets its share."""
44
+ pts = [(s[0], s[1]) for s in samples]
45
+ if len(pts) < 2 or t1 <= t0:
46
+ return 0.0
47
+
48
+ def at(t):
49
+ if t <= pts[0][0]:
50
+ return pts[0][1]
51
+ for (ta, wa), (tb, wb) in zip(pts, pts[1:]):
52
+ if ta <= t <= tb:
53
+ return wa + (wb - wa) * (t - ta) / (tb - ta) if tb > ta else wa
54
+ return pts[-1][1]
55
+
56
+ xs = [(t0, at(t0))] + [p for p in pts if t0 < p[0] < t1] + [(t1, at(t1))]
57
+ return sum((tb - ta) * (wa + wb) / 2 for (ta, wa), (tb, wb) in zip(xs, xs[1:]))
58
+
59
+
60
+ def window_stats(samples, temps, t0: float, t1: float) -> dict:
61
+ inside = [s for s in samples if t0 <= s[0] <= t1]
62
+ e = energy_j(samples, t0, t1)
63
+ return {
64
+ "energy_j": round(e, 1),
65
+ "mean_w": round(e / (t1 - t0), 1) if t1 > t0 and e else None,
66
+ "peak_w": max((s[1] for s in inside), default=None),
67
+ "vram_used_mib_max": max((s[2] for s in inside), default=None),
68
+ "core_c_max": max((s[3] for s in inside), default=None),
69
+ "mem_c_max": max((c for t, c in temps if t0 - 3 <= t <= t1 + 3), default=None),
70
+ "samples": len(inside),
71
+ }
72
+
73
+
74
+ class TooHot(RuntimeError):
75
+ """Raised between requests once a temperature limit has been crossed."""
76
+
77
+
78
+ class GpuSampler:
79
+ """Background `nvidia-smi --query-gpu=... --loop-ms=N`. `too_hot` is set when a limit is crossed."""
80
+
81
+ def __init__(self, smi_cmd="nvidia-smi", gpu: int = 0, interval_ms: int = 200, temp_cmd=None,
82
+ abort_core_c: float | None = None, abort_mem_c: float | None = None, temp_every: float = 2.0):
83
+ self.smi = shlex.split(smi_cmd) if isinstance(smi_cmd, str) else list(smi_cmd)
84
+ self.gpu, self.interval_ms = gpu, interval_ms
85
+ self.temp_cmd = (shlex.split(temp_cmd) if isinstance(temp_cmd, str) else temp_cmd) if temp_cmd else None
86
+ self.abort_core_c, self.abort_mem_c, self.temp_every = abort_core_c, abort_mem_c, temp_every
87
+ self.samples = [] # (t, watts, mem_mib, core_c)
88
+ self.temps = [] # (t, mem_c)
89
+ self.too_hot = None
90
+ self.error = None
91
+ self._stop = threading.Event()
92
+ self.proc = None
93
+
94
+ def command(self) -> list:
95
+ return self.smi + ["-i", str(self.gpu), f"--query-gpu={FIELDS}", "--format=csv,noheader,nounits",
96
+ f"--loop-ms={self.interval_ms}"]
97
+
98
+ def snapshot(self, timeout: float = 30):
99
+ """One reading (watts, mem_mib, core_c) without the loop, or None."""
100
+ cmd = self.smi + ["-i", str(self.gpu), f"--query-gpu={FIELDS}", "--format=csv,noheader,nounits"]
101
+ try:
102
+ out = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout).stdout
103
+ except (OSError, subprocess.SubprocessError):
104
+ return None
105
+ for line in out.splitlines():
106
+ v = parse_smi_line(line)
107
+ if v:
108
+ return v
109
+ return None
110
+
111
+ def start(self) -> "GpuSampler":
112
+ try:
113
+ self.proc = subprocess.Popen(self.command(), stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
114
+ text=True, bufsize=1)
115
+ except OSError as e:
116
+ self.error = str(e)
117
+ return self
118
+ threading.Thread(target=self._read, daemon=True).start()
119
+ if self.temp_cmd:
120
+ threading.Thread(target=self._temps, daemon=True).start()
121
+ return self
122
+
123
+ def feed(self, line: str, t: float | None = None) -> None:
124
+ v = parse_smi_line(line)
125
+ if not v:
126
+ return
127
+ self.samples.append((time.time() if t is None else t, *v))
128
+ if self.abort_core_c and v[2] >= self.abort_core_c and not self.too_hot:
129
+ self.too_hot = f"GPU core {v[2]:.0f} C >= {self.abort_core_c:.0f} C"
130
+
131
+ def feed_temp(self, c: float, t: float | None = None) -> None:
132
+ self.temps.append((time.time() if t is None else t, c))
133
+ if self.abort_mem_c and c >= self.abort_mem_c and not self.too_hot:
134
+ self.too_hot = f"memory {c:.0f} C >= {self.abort_mem_c:.0f} C"
135
+
136
+ def latest_temps(self):
137
+ """(core C, memory C) from the newest readings, None where there is no reading."""
138
+ core = self.samples[-1][3] if self.samples else None
139
+ mem = self.temps[-1][1] if self.temps else None
140
+ return core, mem
141
+
142
+ def wait_cool(self, cool_at: float, cool_to: float, out=None, max_wait: float = 900, poll: float = 2.0,
143
+ sleep=time.sleep) -> float:
144
+ """If the memory (or core) temperature is at or above `cool_at`, wait until both are at or below
145
+ `cool_to`. Returns the seconds spent waiting. Gives up after `max_wait`."""
146
+ def hot(limit):
147
+ return any(c is not None and c >= limit for c in self.latest_temps())
148
+
149
+ if not hot(cool_at):
150
+ return 0.0
151
+ core, mem = self.latest_temps()
152
+ if out is not None:
153
+ out.write(f"\n cooling down (core {core} C, memory {mem} C) to {cool_to:g} C ... ")
154
+ out.flush()
155
+ waited = 0.0
156
+ while waited < max_wait and any(c is not None and c > cool_to for c in self.latest_temps()):
157
+ sleep(poll)
158
+ waited += poll
159
+ if out is not None:
160
+ out.write(f"{waited:.0f}s\n")
161
+ return waited
162
+
163
+ def _read(self):
164
+ for line in self.proc.stdout:
165
+ if self._stop.is_set():
166
+ break
167
+ self.feed(line)
168
+
169
+ def _temps(self):
170
+ while not self._stop.is_set():
171
+ try:
172
+ out = subprocess.run(self.temp_cmd, capture_output=True, text=True, timeout=10,
173
+ encoding="utf-8", errors="replace").stdout
174
+ c = parse_temp(out.replace("\r", "\n"))
175
+ if c is not None:
176
+ self.feed_temp(c)
177
+ except (OSError, subprocess.SubprocessError):
178
+ pass
179
+ self._stop.wait(self.temp_every)
180
+
181
+ def stop(self) -> None:
182
+ self._stop.set()
183
+ if self.proc and self.proc.poll() is None:
184
+ self.proc.terminate()
185
+ try:
186
+ self.proc.wait(timeout=5)
187
+ except subprocess.TimeoutExpired:
188
+ self.proc.kill()
189
+
190
+ def window(self, t0: float, t1: float) -> dict:
191
+ return window_stats(self.samples, self.temps, t0, t1)