inferplan 0.1.0a1__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.
inferplan/__init__.py ADDED
@@ -0,0 +1,53 @@
1
+ """
2
+ InferPlan: cost-aware inference planning for LLM serving.
3
+
4
+ Measures a few serving configurations on the GPU you actually have, learns a
5
+ cost model from those measurements, and then prices the rest of the search
6
+ space without running it - so you get a `vllm serve` command that meets your
7
+ latency and accuracy limits at the lowest cost per request.
8
+
9
+ What makes it different from a benchmark script is what it refuses to do:
10
+
11
+ - It does not recommend a configuration it has never seen measured without
12
+ labelling the figure as an extrapolation.
13
+ - It does not plan at all when the measurements in its ledger do not look
14
+ like measurements.
15
+ - It re-measures a fixed reference configuration during every sweep, and
16
+ throws the sweep away if the machine drifted while it ran. On the laptop
17
+ this was developed on, one configuration read 4730, 3083 and 801 tokens/s
18
+ within 25 hours, each reading repeatable to 0.2%. Without that control,
19
+ a 6x platform effect gets attributed to whichever knob was being turned.
20
+
21
+ The modules, in the order a session uses them:
22
+
23
+ serve start exactly one vLLM server and wait until it answers
24
+ bench measure one running server (TTFT, TPOT, ITL, cost, noise)
25
+ runner sweep configurations, with the reference control
26
+ costmodel learn from the ledger; leave-one-out validation
27
+ planner search the space, rank by cost, print the serve command
28
+ quality measure what quantization costs in output quality
29
+ gpuwatch sample the GPU during a run and say what it saw
30
+ mergeledger combine ledgers from several machines or sessions
31
+ repairledger re-pair ledger rows with their own benchmark records
32
+ """
33
+
34
+ # Read from the installed package metadata, which pyproject.toml is the only
35
+ # source of. Hard-coding it here made `inferplan --version` print 0.1.0 while
36
+ # the wheel on TestPyPI was 0.1.0a1 - the same version claimed in two places,
37
+ # with nothing comparing them. That is the shape of the dependency-list bug
38
+ # (finding #38) and the requires-python bug: a fact stated twice is a fact
39
+ # that will eventually disagree with itself.
40
+ try:
41
+ from importlib.metadata import PackageNotFoundError, version as _version
42
+ try:
43
+ __version__ = _version("inferplan")
44
+ except PackageNotFoundError:
45
+ # Running from a source checkout that was never installed.
46
+ __version__ = "0.0.0+local"
47
+ except ImportError: # pragma: no cover
48
+ __version__ = "0.0.0+unknown"
49
+
50
+ __all__ = [
51
+ "bench", "runner", "costmodel", "planner", "quality",
52
+ "serve", "gpuwatch", "mergeledger", "repairledger",
53
+ ]
inferplan/bench.py ADDED
@@ -0,0 +1,497 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ InferPlan benchmark engine (v2).
4
+
5
+ Measures one serving configuration against a running vLLM server and writes
6
+ one row per repeat to a CSV, plus a JSON record with full metadata.
7
+
8
+ Fixes over v1:
9
+ 1. Real token counts from vLLM's usage block (not SSE chunk counts).
10
+ 2. Client concurrency and server max-num-seqs recorded separately; queue
11
+ delay reported apart from service time.
12
+ 3. Per-request error handling: failures are counted, never silently folded
13
+ into the latency distribution, and never abort the run.
14
+ 4. --repeat with median + spread (measurement noise is ~7% on this setup).
15
+ 5. True ITL distribution (per inter-token gap), not just averaged TPOT.
16
+ 6. Goodput: share of requests that met the SLO.
17
+
18
+ Usage:
19
+ python bench.py --concurrency 8 --requests 40 --repeat 3 \
20
+ --label fp16_c8 --server-max-num-seqs 8 --slo-ms 2000
21
+ """
22
+ import argparse
23
+ import asyncio
24
+ import json
25
+ import os
26
+ import statistics
27
+ import time
28
+ from datetime import datetime, timezone
29
+
30
+ import aiohttp
31
+
32
+ DEFAULT_URL = "http://localhost:8000"
33
+
34
+ PROMPTS = [
35
+ "Explain GPU memory bandwidth in simple terms.",
36
+ "What is the difference between prefill and decode in LLM inference?",
37
+ "Write a short summary of why quantization reduces memory use.",
38
+ "Describe what a KV cache stores and why it grows.",
39
+ "How does continuous batching improve GPU utilization?",
40
+ "What does p99 latency mean for a web service?",
41
+ "Explain the roofline model in two sentences.",
42
+ "Why is inference usually more expensive than training over time?",
43
+ ]
44
+
45
+ # A long shared preamble, used only when --shared-prefix-tokens is set.
46
+ #
47
+ # Why this exists: the prompts above have no text in common, so a run against
48
+ # them cannot show what prefix caching does - there is no prefix to re-use, and
49
+ # measuring "caching on vs off" on that workload would show no difference for
50
+ # the wrong reason. Production traffic usually DOES repeat a long system prompt
51
+ # on every request, so that case needs its own workload.
52
+ _PREAMBLE_UNIT = (
53
+ "You are a careful technical assistant for a platform engineering team. "
54
+ "Answer precisely, prefer measured numbers over estimates, state your "
55
+ "assumptions, and keep responses short. Never invent benchmark figures. "
56
+ "When a question concerns serving performance, distinguish prefill from "
57
+ "decode, and latency from throughput. "
58
+ )
59
+
60
+
61
+ def shared_prefix(approx_tokens: int) -> str:
62
+ """~4 characters per token is close enough for a load-generator preamble."""
63
+ if approx_tokens <= 0:
64
+ return ""
65
+ target_chars = approx_tokens * 4
66
+ reps = max(1, target_chars // len(_PREAMBLE_UNIT) + 1)
67
+ return (_PREAMBLE_UNIT * reps)[:target_chars]
68
+
69
+
70
+ # ----------------------------------------------------------------------------
71
+ # one request
72
+ # ----------------------------------------------------------------------------
73
+ async def one_request(session, url, model, prompt, max_tokens, req_id):
74
+ """
75
+ Send one streaming request.
76
+
77
+ Returns a dict that ALWAYS has an "ok" key. On failure, ok=False and the
78
+ reason is recorded; the caller counts it instead of treating it as latency.
79
+ """
80
+ payload = {
81
+ "model": model,
82
+ "messages": [{"role": "user", "content": prompt}],
83
+ "max_tokens": max_tokens,
84
+ "stream": True,
85
+ "temperature": 0.0,
86
+ # vLLM returns a final chunk carrying real token counts.
87
+ "stream_options": {"include_usage": True},
88
+ }
89
+
90
+ start = time.perf_counter()
91
+ ttft = None
92
+ last_tok_at = None
93
+ itls = [] # inter-token latencies, one per gap
94
+ chunk_count = 0 # SSE content chunks (NOT tokens)
95
+ usage = None
96
+
97
+ try:
98
+ async with session.post(f"{url}/v1/chat/completions", json=payload) as resp:
99
+ if resp.status != 200:
100
+ body = (await resp.text())[:300]
101
+ return {"ok": False, "req_id": req_id,
102
+ "error": f"HTTP {resp.status}", "detail": body}
103
+
104
+ async for raw in resp.content:
105
+ line = raw.decode("utf-8", errors="replace").strip()
106
+ if not line.startswith("data: "):
107
+ continue
108
+ body = line[6:]
109
+ if body == "[DONE]":
110
+ break
111
+ try:
112
+ chunk = json.loads(body)
113
+ except json.JSONDecodeError:
114
+ continue
115
+
116
+ # With include_usage the final chunk has usage and may carry
117
+ # an empty choices list - handle both shapes.
118
+ if chunk.get("usage"):
119
+ usage = chunk["usage"]
120
+
121
+ choices = chunk.get("choices") or []
122
+ if not choices:
123
+ continue
124
+
125
+ delta = choices[0].get("delta") or {}
126
+ if delta.get("content"):
127
+ now = time.perf_counter()
128
+ if ttft is None:
129
+ ttft = now - start
130
+ else:
131
+ itls.append((now - last_tok_at) * 1000)
132
+ last_tok_at = now
133
+ chunk_count += 1
134
+
135
+ except asyncio.TimeoutError:
136
+ return {"ok": False, "req_id": req_id, "error": "timeout"}
137
+ except aiohttp.ClientError as e:
138
+ return {"ok": False, "req_id": req_id,
139
+ "error": type(e).__name__, "detail": str(e)[:200]}
140
+
141
+ end = time.perf_counter()
142
+
143
+ if ttft is None:
144
+ return {"ok": False, "req_id": req_id, "error": "no_tokens_returned"}
145
+
146
+ # Prefer the server's own token counts; fall back to chunk count and say so.
147
+ if usage:
148
+ out_tokens = usage.get("completion_tokens", 0)
149
+ in_tokens = usage.get("prompt_tokens", 0)
150
+ token_source = "usage"
151
+ else:
152
+ out_tokens = chunk_count
153
+ in_tokens = 0
154
+ token_source = "chunk_count_fallback"
155
+
156
+ decode_s = (end - start) - ttft
157
+ return {
158
+ "ok": True,
159
+ "req_id": req_id,
160
+ "ttft_ms": ttft * 1000,
161
+ "e2e_ms": (end - start) * 1000,
162
+ "decode_ms": decode_s * 1000,
163
+ "out_tokens": out_tokens,
164
+ "in_tokens": in_tokens,
165
+ "chunk_count": chunk_count,
166
+ # TPOT from REAL token count, excluding the first token
167
+ "tpot_ms": decode_s * 1000 / max(out_tokens - 1, 1),
168
+ "itls": itls,
169
+ "token_source": token_source,
170
+ }
171
+
172
+
173
+ # ----------------------------------------------------------------------------
174
+ # one repeat of the whole load
175
+ # ----------------------------------------------------------------------------
176
+ async def one_pass(url, model, concurrency, total, max_tokens, prefix=""):
177
+ sem = asyncio.Semaphore(concurrency)
178
+
179
+ async def guarded(session, i):
180
+ async with sem:
181
+ prompt = prefix + PROMPTS[i % len(PROMPTS)]
182
+ return await one_request(
183
+ session, url, model, prompt, max_tokens, i)
184
+
185
+ timeout = aiohttp.ClientTimeout(total=900, sock_read=300)
186
+ conn = aiohttp.TCPConnector(limit=max(concurrency * 2, 32))
187
+ async with aiohttp.ClientSession(timeout=timeout, connector=conn) as session:
188
+ # Warm-up, not measured. It uses the same prefix so that a cached
189
+ # prefix is already warm when the measured requests start: otherwise
190
+ # the first measured request pays for filling the cache and the
191
+ # comparison between caching on and off is skewed by one request.
192
+ await one_request(session, url, model, prefix + PROMPTS[0], 16, -1)
193
+
194
+ wall_start = time.perf_counter()
195
+ # return_exceptions keeps one bad request from aborting the whole pass
196
+ raw = await asyncio.gather(
197
+ *(guarded(session, i) for i in range(total)),
198
+ return_exceptions=True)
199
+ wall = time.perf_counter() - wall_start
200
+
201
+ results, failures = [], []
202
+ for r in raw:
203
+ if isinstance(r, BaseException):
204
+ failures.append({"error": type(r).__name__, "detail": str(r)[:200]})
205
+ elif r.get("ok"):
206
+ results.append(r)
207
+ else:
208
+ failures.append(r)
209
+ return results, failures, wall
210
+
211
+
212
+ # ----------------------------------------------------------------------------
213
+ # stats
214
+ # ----------------------------------------------------------------------------
215
+ def pct(values, p):
216
+ if not values:
217
+ return float("nan")
218
+ s = sorted(values)
219
+ k = (len(s) - 1) * p / 100
220
+ lo = int(k)
221
+ hi = min(lo + 1, len(s) - 1)
222
+ return s[lo] + (s[hi] - s[lo]) * (k - lo)
223
+
224
+
225
+ def summarize(results, failures, wall, args):
226
+ """Reduce one pass to a flat metric dict."""
227
+ n_ok, n_fail = len(results), len(failures)
228
+ total = n_ok + n_fail
229
+
230
+ ttfts = [r["ttft_ms"] for r in results]
231
+ e2es = [r["e2e_ms"] for r in results]
232
+ tpots = [r["tpot_ms"] for r in results]
233
+ itls = [x for r in results for x in r["itls"]]
234
+ out_tokens = sum(r["out_tokens"] for r in results)
235
+ in_tokens = sum(r["in_tokens"] for r in results)
236
+
237
+ # Queue delay: with client concurrency above the server's max-num-seqs,
238
+ # the excess TTFT is waiting, not prefill. Reported, not inferred away.
239
+ served = min(args.concurrency, args.server_max_num_seqs or args.concurrency)
240
+ queued = max(args.concurrency - served, 0)
241
+
242
+ # Goodput counts a FAILED request as having missed the SLO: a config that
243
+ # drops requests must not score better than one that serves them slowly.
244
+ met = [1 for r in results if r["e2e_ms"] <= args.slo_ms] if args.slo_ms else []
245
+ goodput = (len(met) / total * 100) if (args.slo_ms and total) else float("nan")
246
+
247
+ # A pass with no successful request is not a fast pass, it is a failed one.
248
+ # Rates and cost are left undefined so the surrogate model cannot learn a
249
+ # crashed configuration as a cheap one (SLO-Guard, 2026).
250
+ valid = n_ok > 0
251
+ partial = n_ok > 0 and n_fail > 0
252
+
253
+ if valid:
254
+ # Rates are based on SERVED requests; cost is amortised over them too.
255
+ throughput = out_tokens / wall if wall else 0.0
256
+ rps = n_ok / wall if wall else 0.0
257
+ cost_per_1k = ((wall / 3600) * args.gpu_cost_per_hour / n_ok) * 1000
258
+ else:
259
+ throughput = rps = 0.0
260
+ cost_per_1k = float("nan")
261
+
262
+ return {
263
+ "requests_sent": total,
264
+ "requests_ok": n_ok,
265
+ "requests_failed": n_fail,
266
+ "run_valid": valid,
267
+ "run_partial": partial,
268
+ "wall_s": wall,
269
+ "out_tokens": out_tokens,
270
+ "in_tokens": in_tokens,
271
+ # The mean completion length, which is NOT max_tokens: these prompts
272
+ # stop at EOS around 116 tokens against a 128 limit, and the prefix
273
+ # runs come in between 96 and 111. A cost model that assumes the
274
+ # limit over-predicts every latency by 9-25%, and because the queue
275
+ # term is proportional to the output length it inflates TTFT too.
276
+ # Finding #41. Recorded as a metric so it travels to the ledger.
277
+ "out_tokens_mean": (out_tokens / n_ok) if n_ok else 0.0,
278
+ # The MEDIAN completion length, which is a different number from the
279
+ # mean and is the one a percentile latency needs. Finding #41: using
280
+ # the mean (116) to predict e2e_p50 made it worse, not better,
281
+ # because when most requests run to the max_tokens limit the median
282
+ # request is at the limit while the mean is dragged down by the few
283
+ # that stop early. Cost needs the mean, because cost is total work;
284
+ # a percentile needs the percentile.
285
+ "out_tokens_p50": pct([r["out_tokens"] for r in results], 50),
286
+ "ttft_p50": pct(ttfts, 50), "ttft_p95": pct(ttfts, 95),
287
+ "ttft_p99": pct(ttfts, 99),
288
+ "tpot_p50": pct(tpots, 50), "tpot_p99": pct(tpots, 99),
289
+ "itl_p50": pct(itls, 50), "itl_p99": pct(itls, 99),
290
+ "e2e_p50": pct(e2es, 50), "e2e_p95": pct(e2es, 95),
291
+ "e2e_p99": pct(e2es, 99),
292
+ "e2e_mean": statistics.mean(e2es) if e2es else float("nan"),
293
+ "throughput_tok_s": throughput,
294
+ "rps": rps,
295
+ "goodput_pct": goodput,
296
+ "client_concurrency": args.concurrency,
297
+ "server_max_num_seqs": args.server_max_num_seqs,
298
+ "queued_excess": queued,
299
+ "cost_per_1k": cost_per_1k,
300
+ "token_source": results[0]["token_source"] if results else "none",
301
+ }
302
+
303
+
304
+ def verdict(ok, sent, failed):
305
+ """One word the planner can filter on, before any number is compared."""
306
+ if ok == 0:
307
+ return "FAILED"
308
+ if failed:
309
+ return "PARTIAL"
310
+ return "OK"
311
+
312
+
313
+ def median_of(passes, key):
314
+ vals = [p[key] for p in passes if isinstance(p[key], (int, float))
315
+ and p[key] == p[key]]
316
+ return statistics.median(vals) if vals else float("nan")
317
+
318
+
319
+ def spread_of(passes, key):
320
+ """Relative spread (max-min)/median in percent - the noise estimate."""
321
+ vals = [p[key] for p in passes if isinstance(p[key], (int, float))
322
+ and p[key] == p[key]]
323
+ if len(vals) < 2:
324
+ return 0.0
325
+ med = statistics.median(vals)
326
+ return (max(vals) - min(vals)) / med * 100 if med else 0.0
327
+
328
+
329
+ # ----------------------------------------------------------------------------
330
+ # main
331
+ # ----------------------------------------------------------------------------
332
+ def main():
333
+ ap = argparse.ArgumentParser()
334
+ ap.add_argument("--url", default=DEFAULT_URL)
335
+ ap.add_argument("--model", default="Qwen/Qwen2.5-0.5B-Instruct")
336
+ ap.add_argument("--concurrency", type=int, default=8,
337
+ help="client-side concurrent requests")
338
+ ap.add_argument("--server-max-num-seqs", type=int, default=None,
339
+ help="the server's --max-num-seqs, for queue accounting")
340
+ ap.add_argument("--requests", type=int, default=40)
341
+ ap.add_argument("--max-tokens", type=int, default=128)
342
+ ap.add_argument("--shared-prefix-tokens", type=int, default=0,
343
+ help="prepend this many tokens of identical text to every "
344
+ "prompt; required to measure prefix caching at all")
345
+ ap.add_argument("--repeat", type=int, default=3,
346
+ help="passes per configuration; median is reported")
347
+ ap.add_argument("--slo-ms", type=float, default=0.0,
348
+ help="end-to-end SLO for goodput; 0 disables")
349
+ ap.add_argument("--gpu-cost-per-hour", type=float, default=0.35)
350
+ ap.add_argument("--label", default="baseline")
351
+ ap.add_argument("--csv", default="results.csv")
352
+ ap.add_argument("--json-dir", default="runs")
353
+ args = ap.parse_args()
354
+
355
+ prefix = shared_prefix(args.shared_prefix_tokens)
356
+ print(f"[{args.label}] {args.repeat} pass(es) x {args.requests} requests "
357
+ f"@ client concurrency {args.concurrency}")
358
+ if prefix:
359
+ print(f" shared prefix: ~{args.shared_prefix_tokens} tokens "
360
+ f"({len(prefix)} chars) identical on every request")
361
+
362
+ passes, all_failures = [], []
363
+ for i in range(args.repeat):
364
+ results, failures, wall = asyncio.run(
365
+ one_pass(args.url, args.model, args.concurrency,
366
+ args.requests, args.max_tokens, prefix))
367
+ s = summarize(results, failures, wall, args)
368
+ passes.append(s)
369
+ all_failures.extend(failures)
370
+ print(f" pass {i+1}/{args.repeat}: "
371
+ f"{s['requests_ok']}/{s['requests_sent']} ok, "
372
+ f"{s['throughput_tok_s']:.0f} tok/s, "
373
+ f"e2e p99 {s['e2e_p99']:.0f} ms, "
374
+ f"${s['cost_per_1k']:.4f}/1K")
375
+
376
+ keys = ["ttft_p50", "ttft_p95", "ttft_p99", "tpot_p50", "tpot_p99",
377
+ "itl_p50", "itl_p99", "e2e_p50", "e2e_p95", "e2e_p99", "e2e_mean",
378
+ "throughput_tok_s", "rps", "goodput_pct", "cost_per_1k",
379
+ "out_tokens_mean", "out_tokens_p50"]
380
+ med = {k: median_of(passes, k) for k in keys}
381
+ noise = spread_of(passes, "throughput_tok_s")
382
+
383
+ ok = sum(p["requests_ok"] for p in passes)
384
+ sent = sum(p["requests_sent"] for p in passes)
385
+ failed = sent - ok
386
+ status = verdict(ok, sent, failed)
387
+
388
+ print()
389
+ print("=" * 62)
390
+ print(f" CONFIG: {args.label} [{status}] "
391
+ f"(median of {args.repeat} pass(es))")
392
+ print("=" * 62)
393
+ print(f" requests ok / sent : {ok} / {sent}"
394
+ + (f" FAILED {failed}" if failed else ""))
395
+ if status == "FAILED":
396
+ print(" -> no request succeeded: this configuration is INFEASIBLE.")
397
+ print(" Rates and cost are not reported; the row is kept as a")
398
+ print(" negative observation for the cost model.")
399
+ print(f" client concurrency : {args.concurrency}")
400
+ print(f" server max-num-seqs : {args.server_max_num_seqs or 'unknown'}")
401
+ if args.server_max_num_seqs and args.concurrency > args.server_max_num_seqs:
402
+ print(f" -> {args.concurrency - args.server_max_num_seqs} request(s) "
403
+ f"queue in excess of server capacity: TTFT includes wait time")
404
+ print(f" token source : {passes[0]['token_source']}")
405
+ print("-" * 62)
406
+ print(f" TTFT p50/p95/p99 : {med['ttft_p50']:7.1f} /{med['ttft_p95']:8.1f} /{med['ttft_p99']:8.1f} ms")
407
+ print(f" ITL p50/p99 : {med['itl_p50']:7.1f} /{med['itl_p99']:8.1f} ms")
408
+ print(f" TPOT p50/p99 : {med['tpot_p50']:7.1f} /{med['tpot_p99']:8.1f} ms")
409
+ print(f" E2E p50/p95/p99 : {med['e2e_p50']:7.1f} /{med['e2e_p95']:8.1f} /{med['e2e_p99']:8.1f} ms")
410
+ print("-" * 62)
411
+ print(f" throughput : {med['throughput_tok_s']:8.1f} tokens/s")
412
+ print(f" request rate : {med['rps']:8.2f} req/s")
413
+ if args.slo_ms:
414
+ print(f" goodput (<= {args.slo_ms:.0f} ms) : {med['goodput_pct']:8.1f} %")
415
+ print(f" cost per 1K requests: ${med['cost_per_1k']:.4f}")
416
+ print(f" noise (throughput) : {noise:8.1f} % across passes")
417
+ print("=" * 62)
418
+
419
+ if all_failures:
420
+ print(" failure breakdown:")
421
+ tally = {}
422
+ for f in all_failures:
423
+ tally[f.get("error", "unknown")] = tally.get(f.get("error", "unknown"), 0) + 1
424
+ for err, n in sorted(tally.items(), key=lambda kv: -kv[1]):
425
+ print(f" {n:4d} {err}")
426
+
427
+ # ---- CSV row (one per configuration, median values) --------------------
428
+ cols = ["timestamp", "label", "status", "model", "client_concurrency",
429
+ "server_max_num_seqs", "requests_sent", "requests_ok",
430
+ "requests_failed", "max_tokens", "shared_prefix_tokens",
431
+ "repeat"] + keys + ["noise_pct"]
432
+ row = {
433
+ "timestamp": datetime.now(timezone.utc).isoformat(timespec="seconds"),
434
+ "label": args.label, "status": status, "model": args.model,
435
+ "client_concurrency": args.concurrency,
436
+ "server_max_num_seqs": args.server_max_num_seqs or "",
437
+ "requests_sent": sent, "requests_ok": ok, "requests_failed": failed,
438
+ "max_tokens": args.max_tokens,
439
+ "shared_prefix_tokens": args.shared_prefix_tokens,
440
+ "repeat": args.repeat,
441
+ "noise_pct": round(noise, 2),
442
+ }
443
+ row.update({k: round(med[k], 4) if med[k] == med[k] else "" for k in keys})
444
+
445
+ # The header is only written for a new file, so adding a column to this
446
+ # list silently leaves an old file's header one field short of every
447
+ # later row. Anything reading that CSV by name or index then gets a
448
+ # different metric than it asked for, with no error.
449
+ #
450
+ # Finding #39: that happened when shared_prefix_tokens was added, and it
451
+ # produced two confidently wrong claims about chunked prefill before the
452
+ # mismatch was noticed. So the header is now checked, and a file whose
453
+ # header does not match is set aside rather than appended to.
454
+ header_line = ",".join(cols)
455
+ existing = None
456
+ if os.path.exists(args.csv):
457
+ try:
458
+ with open(args.csv) as f:
459
+ existing = f.readline().strip()
460
+ except OSError:
461
+ existing = None
462
+ if existing and existing != header_line:
463
+ stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
464
+ archived = f"{args.csv}.{stamp}.old"
465
+ try:
466
+ os.rename(args.csv, archived)
467
+ print(f" NOTE: {args.csv} had a header from an older version of")
468
+ print(f" this script, so its columns no longer match the rows")
469
+ print(f" being written. It has been moved to {archived} and a")
470
+ print(f" new file started. The old rows are intact; read them")
471
+ print(f" with the header that is now at the top of that file.")
472
+ existing = None
473
+ except OSError as e:
474
+ print(f" WARNING: {args.csv} has a stale header and could not "
475
+ f"be renamed ({e}).")
476
+ print(f" Columns in that file do NOT match these rows. Pass "
477
+ f"--csv with a new path.")
478
+ write_header = existing is None
479
+ with open(args.csv, "a") as f:
480
+ if write_header:
481
+ f.write(header_line + "\n")
482
+ f.write(",".join(str(row[c]) for c in cols) + "\n")
483
+ print(f" appended to {args.csv}")
484
+
485
+ # ---- full JSON record (per-pass detail, for the surrogate model) -------
486
+ os.makedirs(args.json_dir, exist_ok=True)
487
+ stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
488
+ path = os.path.join(args.json_dir, f"{args.label}_{stamp}.json")
489
+ with open(path, "w") as f:
490
+ json.dump({"args": vars(args), "status": status, "passes": passes,
491
+ "median": med, "noise_pct": noise,
492
+ "failures": all_failures[:50]}, f, indent=2)
493
+ print(f" wrote {path}")
494
+
495
+
496
+ if __name__ == "__main__":
497
+ main()
inferplan/cli.py ADDED
@@ -0,0 +1,76 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ One entry point for the whole library: `inferplan <command> [options]`.
4
+
5
+ Each command forwards its arguments untouched to the module that owns it, so
6
+ `inferplan plan --rate 20` and `python -m inferplan.planner --rate 20` behave
7
+ identically. The dispatcher deliberately does no argument parsing of its own
8
+ beyond picking the command - a wrapper that reinterprets flags is a second
9
+ place for them to drift.
10
+ """
11
+ import sys
12
+
13
+ COMMANDS = {
14
+ "serve": ("serve", "start one vLLM server and wait for it"),
15
+ "bench": ("bench", "measure the server that is running"),
16
+ "sweep": ("runner", "measure many configurations, with the "
17
+ "reference control"),
18
+ "fit": ("costmodel", "learn from the ledger and validate the fit"),
19
+ "plan": ("planner", "recommend a configuration for your limits"),
20
+ "quality": ("quality", "measure what a precision costs in quality"),
21
+ "watch": ("gpuwatch", "sample the GPU during a run"),
22
+ "merge": ("mergeledger", "combine ledgers from several sessions"),
23
+ "repair": ("repairledger", "re-pair ledger rows with their own "
24
+ "benchmark JSON (finding #40)"),
25
+ }
26
+
27
+ ORDER = ["serve", "bench", "sweep", "fit", "plan", "quality", "watch",
28
+ "merge", "repair"]
29
+
30
+
31
+ def usage(stream=sys.stdout) -> None:
32
+ print("inferplan <command> [options]", file=stream)
33
+ print(file=stream)
34
+ print(" a typical first session:", file=stream)
35
+ print(" inferplan sweep --sweep knee --reference-every 4", file=stream)
36
+ print(" inferplan fit", file=stream)
37
+ print(" inferplan plan --rate 20 --p99-ms 2000", file=stream)
38
+ print(file=stream)
39
+ print(" commands:", file=stream)
40
+ for name in ORDER:
41
+ _, blurb = COMMANDS[name]
42
+ print(f" {name:<9} {blurb}", file=stream)
43
+ print(file=stream)
44
+ print(" any command's own --help works: inferplan plan --help",
45
+ file=stream)
46
+
47
+
48
+ def main(argv=None) -> int:
49
+ argv = list(sys.argv[1:] if argv is None else argv)
50
+ if not argv or argv[0] in ("-h", "--help", "help"):
51
+ usage()
52
+ return 0
53
+ if argv[0] in ("-V", "--version", "version"):
54
+ from . import __version__
55
+ print(f"inferplan {__version__}")
56
+ return 0
57
+
58
+ cmd = argv[0]
59
+ if cmd not in COMMANDS:
60
+ print(f"inferplan: unknown command {cmd!r}", file=sys.stderr)
61
+ print(file=sys.stderr)
62
+ usage(sys.stderr)
63
+ return 2
64
+
65
+ module_name, _ = COMMANDS[cmd]
66
+ # argparse inside each module reads sys.argv, so the command word is
67
+ # removed and prog is set to how the user actually invoked it. Without
68
+ # that, every error message and --help would say "cli.py".
69
+ sys.argv = [f"inferplan {cmd}"] + argv[1:]
70
+ mod = __import__(f"inferplan.{module_name}", fromlist=["main"])
71
+ rc = mod.main()
72
+ return 0 if rc is None else rc
73
+
74
+
75
+ if __name__ == "__main__":
76
+ raise SystemExit(main())