NeuralNovaAI commited on
Commit
3ee4809
·
verified ·
1 Parent(s): 845483f

Fix benchmark compilation classification for vLLM uptime telemetry

Browse files
Files changed (2) hide show
  1. benchmark-v1.2.py +532 -0
  2. serve-benchmark-v1.2.py +56 -0
benchmark-v1.2.py ADDED
@@ -0,0 +1,532 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Three-arm controlled benchmark; uses the unchanged v1.0.0 container kernels.
3
+
4
+ New deterministic token-ID workload, not the historical reference prompt set.
5
+ Only standard library imports are needed for --help, --plan and CPU tests.
6
+ """
7
+ import argparse
8
+ from concurrent.futures import ThreadPoolExecutor
9
+ from contextlib import contextmanager
10
+ import csv
11
+ from datetime import datetime, timezone
12
+ import hashlib
13
+ import importlib.util
14
+ import importlib.metadata
15
+ import json
16
+ import math
17
+ import os
18
+ from pathlib import Path
19
+ import random
20
+ import re
21
+ import signal
22
+ import socket
23
+ import subprocess
24
+ import sys
25
+ import time
26
+ import urllib.request
27
+
28
+ VERSION = "1.2"
29
+ MODEL = "thinkingmachines/Inkling-2-Mini"
30
+ REVISION = "c9d028302cd0f035fdf8e7e91f089a4ce94d2195"
31
+ IMAGE = "registry.neural-nova.io/public/inkling2-mini@sha256:404e3c10d9e2c7ab90356715f403e1299ef8e51a1ffb44e634eaff76abc14c4e"
32
+ ARMS = ("native", "native-dspark", "optimized-dspark")
33
+ WORKLOADS = ((1024, 1024), (4096, 4096))
34
+ CONCURRENCIES = (1, 4)
35
+ REQUESTS = 32
36
+ REPEATS = 3
37
+ SEED = 42
38
+ PORT = 8000
39
+ MIN_WARMUPS = 2
40
+ MAX_WARMUPS = 3
41
+ LAUNCHER = Path(__file__).with_name("serve-benchmark-v1.2.py")
42
+ JIT_MARKERS = ("during inference:", "Triton autotuning", "[Autotuner]: Autotuning process starts")
43
+ SAMPLING = dict(temperature=0, seed=SEED, top_p=1, top_k=0, min_p=0,
44
+ repetition_penalty=1, presence_penalty=0, frequency_penalty=0)
45
+
46
+
47
+ def write_json(path, value):
48
+ path.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n", encoding="utf-8")
49
+
50
+
51
+ def digest(path):
52
+ h = hashlib.sha256()
53
+ with path.open("rb") as handle:
54
+ for block in iter(lambda: handle.read(1024 * 1024), b""):
55
+ h.update(block)
56
+ return h.hexdigest()
57
+
58
+
59
+ def launcher_module():
60
+ spec = importlib.util.spec_from_file_location("inkling_benchmark_launcher", LAUNCHER)
61
+ module = importlib.util.module_from_spec(spec)
62
+ spec.loader.exec_module(module)
63
+ return module
64
+
65
+
66
+ def plan():
67
+ launcher = launcher_module()
68
+ return {
69
+ "benchmark_version": VERSION, "required_image": IMAGE, "model_revision": REVISION,
70
+ "arms": list(ARMS), "concurrencies": list(CONCURRENCIES),
71
+ "workloads": list(WORKLOADS), "requests_per_timed_loop": REQUESTS,
72
+ "timed_repeats_per_cell": REPEATS, "timed_loops": 36,
73
+ "full_warmups_min": MIN_WARMUPS, "full_warmups_max": MAX_WARMUPS,
74
+ "sampling": SAMPLING, "speculative_rejection_sampling": "standard",
75
+ "workload": "Version 1.1 deterministic ordinary-token pool; frozen across all arms. Different prompts from the historical tables.",
76
+ "server_order": "One fresh server per arm, fixed listed order; repeats share a server, not independent server-order repetitions.",
77
+ "compilation_gate": "Zero observed verbose JIT/autotune log events and zero compiler-cache changes in final full warmup and every timed loop. Only the exact vLLM telemetry file home/.config/vllm/usage_stats.json is classified separately; its fingerprints remain recorded.",
78
+ "timing": "Whole client loop wall time; no subtraction. Throughput=sum(output tokens)/sum(loop duration). Latencies pool request samples.",
79
+ "commands": {arm: {"argv": launcher.command(arm, PORT)[0], "VLLM_PLUGINS": launcher.command(arm, PORT)[1]} for arm in ARMS},
80
+ }
81
+
82
+
83
+ def token_pool():
84
+ from transformers import AutoTokenizer
85
+ tokenizer = AutoTokenizer.from_pretrained(MODEL, revision=REVISION)
86
+ text = (
87
+ "The river runs past the city and into the sea. A train crosses the old "
88
+ "bridge every morning while shops open along the street. Engineers test "
89
+ "each part before assembling the machine. They measure speed, noise, "
90
+ "temperature and power, then write the results in a small notebook. "
91
+ "If the numbers disagree, they repeat the experiment with the same "
92
+ "inputs and check what changed. The report includes tables, notes, "
93
+ "and examples for the people who will use the system next. "
94
+ "On weekends the market sells fruit, bread, cheese, tea and flowers. "
95
+ "Prices range from 1 to 30, depending on the month and the weather."
96
+ )
97
+ pool = sorted(set(tokenizer.encode(text, add_special_tokens=False)) - set(tokenizer.all_special_ids))
98
+ if len(pool) < 2:
99
+ raise ValueError("Tokenizer did not produce an ordinary token pool")
100
+ return pool
101
+
102
+
103
+ def workload(pool, input_tokens, output_tokens):
104
+ rng = random.Random(SEED + input_tokens)
105
+ return [{"id": i, "prompt_token_ids": rng.choices(pool, k=input_tokens),
106
+ "output_tokens": output_tokens} for i in range(REQUESTS)]
107
+
108
+
109
+ def completion(base, row, directory, open_response=urllib.request.urlopen):
110
+ payload = dict(model=MODEL, prompt=row["prompt_token_ids"], **SAMPLING,
111
+ max_tokens=row["output_tokens"], ignore_eos=True,
112
+ add_special_tokens=False, return_token_ids=True,
113
+ stream=True, stream_options={"include_usage": True})
114
+ encoded = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()
115
+ record = {"id": row["id"], "request": payload,
116
+ "request_sha256": hashlib.sha256(encoded).hexdigest(), "events": [], "success": False}
117
+ start = time.perf_counter()
118
+ record["start_monotonic"] = start
119
+ ids, arrivals = [], []
120
+ prompt, usage, finish, done = None, None, None, False
121
+ try:
122
+ req = urllib.request.Request(base + "/v1/completions", data=encoded,
123
+ headers={"Content-Type": "application/json"})
124
+ with open_response(req, timeout=900) as response:
125
+ for line in response:
126
+ if not line.startswith(b"data:"):
127
+ continue
128
+ raw = line[5:].strip()
129
+ if raw == b"[DONE]":
130
+ done = True
131
+ break
132
+ packet = json.loads(raw)
133
+ arrival = time.perf_counter() - start
134
+ record["events"].append({"seconds": arrival, "data": packet})
135
+ if packet.get("error"):
136
+ raise ValueError(str(packet["error"]))
137
+ usage = packet.get("usage") or usage
138
+ choices = packet.get("choices", [])
139
+ if any(c.get("index") != 0 for c in choices) or len(choices) > 1:
140
+ raise ValueError("Expected exactly one completion choice")
141
+ for source in [packet, *choices]:
142
+ if source.get("prompt_token_ids") is not None:
143
+ prompt = source["prompt_token_ids"]
144
+ if prompt != row["prompt_token_ids"]:
145
+ raise ValueError("Response prompt IDs differ from frozen input")
146
+ for choice in choices:
147
+ chunk = choice.get("token_ids") or []
148
+ if chunk:
149
+ ids.extend(chunk)
150
+ arrivals.append((arrival, len(chunk)))
151
+ finish = choice.get("finish_reason") or finish
152
+ record["end_monotonic"] = time.perf_counter()
153
+ if (not done or not usage or not arrivals or prompt != row["prompt_token_ids"]
154
+ or usage.get("prompt_tokens") != len(prompt)
155
+ or usage.get("completion_tokens") != row["output_tokens"]
156
+ or len(ids) != row["output_tokens"] or finish != "length"):
157
+ raise ValueError("Incomplete fixed-length workload or missing SSE/usage evidence")
158
+ record.update(success=True, token_ids=ids, prompt_token_ids=prompt,
159
+ usage=usage, finish_reason=finish, arrivals=arrivals,
160
+ ttft_s=arrivals[0][0], e2e_s=record["end_monotonic"] - start,
161
+ tpot_s=(arrivals[-1][0] - arrivals[0][0]) / (len(ids) - 1),
162
+ chunk_interval_s=(arrivals[-1][0] - arrivals[0][0]) / (len(arrivals) - 1) if len(arrivals) > 1 else None)
163
+ return record
164
+ except BaseException as exc:
165
+ record.update(error_type=type(exc).__name__, error=str(exc))
166
+ raise
167
+ finally:
168
+ # Keep partial streams even when protocol validation fails.
169
+ write_json(directory / f"request-{row['id']:04d}.json", record)
170
+
171
+
172
+ def run_workload(base, rows, concurrency, directory):
173
+ directory.mkdir()
174
+ start = time.perf_counter()
175
+ with ThreadPoolExecutor(max_workers=concurrency) as executor:
176
+ futures = [executor.submit(completion, base, row, directory) for row in rows]
177
+ records, failures = [], []
178
+ for row, future in zip(rows, futures):
179
+ try:
180
+ records.append(future.result())
181
+ except Exception as exc:
182
+ failures.append({"id": row["id"], "error": str(exc)})
183
+ duration = time.perf_counter() - start
184
+ if failures:
185
+ write_json(directory / "failures.json", failures)
186
+ raise RuntimeError("Request failures; raw evidence preserved, stopping benchmark")
187
+ return records, duration
188
+
189
+
190
+ def peak_concurrency(records):
191
+ points = [(r["start_monotonic"], 1) for r in records] + [(r["end_monotonic"], -1) for r in records]
192
+ active = peak = 0
193
+ for _, delta in sorted(points):
194
+ active += delta
195
+ peak = max(peak, active)
196
+ if active != 0:
197
+ raise ValueError("Unbalanced request intervals")
198
+ return peak
199
+
200
+
201
+ def metric_series(text, name, source=None):
202
+ pattern = re.compile(r"^" + re.escape(name) + r"(\{[^\n]*\})?\s+([^\s]+)(?:\s+[^\s]+)?$")
203
+ out = {}
204
+ for line in text.splitlines():
205
+ match = pattern.fullmatch(line)
206
+ if not match:
207
+ continue
208
+ labels = match.group(1) or ""
209
+ if source is not None and not re.search(r'(?:\{|,)\s*source="' + re.escape(source) + r'"(?:,|\})', labels):
210
+ continue
211
+ value = float(match.group(2))
212
+ if not math.isfinite(value) or value < 0 or labels in out:
213
+ raise ValueError("Invalid/duplicate metric: " + name)
214
+ out[labels] = value
215
+ return out
216
+
217
+
218
+ def metric_delta(before, after, name, source=None, optional=False):
219
+ a, b = metric_series(before, name, source), metric_series(after, name, source)
220
+ if not b:
221
+ if optional and not a:
222
+ return 0
223
+ raise ValueError("Required metric missing: " + name)
224
+ if a.keys() - b.keys() or any(v < a.get(k, 0) for k, v in b.items()):
225
+ raise ValueError("Counter reset/disappeared: " + name)
226
+ return sum(v - a.get(k, 0) for k, v in b.items())
227
+
228
+
229
+ def work_counters(before, after, rows, arm):
230
+ expected_prompt = sum(len(r["prompt_token_ids"]) for r in rows)
231
+ expected_output = sum(r["output_tokens"] for r in rows)
232
+ definitions = {
233
+ "prompt": ("vllm:prompt_tokens_total", None, expected_prompt),
234
+ "computed_prefill": ("vllm:prompt_tokens_by_source_total", "local_compute", expected_prompt),
235
+ "generated": ("vllm:generation_tokens_total", None, expected_output),
236
+ "cached": ("vllm:prompt_tokens_cached_total", None, 0),
237
+ "preemptions": ("vllm:num_preemptions_total", None, 0),
238
+ }
239
+ result = {}
240
+ for key, (name, source, expected) in definitions.items():
241
+ result[key] = metric_delta(before, after, name, source)
242
+ if result[key] != expected:
243
+ raise ValueError(f"Unequal work: {key}={result[key]}, expected {expected}")
244
+ drafted = metric_delta(before, after, "vllm:spec_decode_num_draft_tokens_total", optional=arm == "native")
245
+ accepted = metric_delta(before, after, "vllm:spec_decode_num_accepted_tokens_total", optional=arm == "native")
246
+ if (arm == "native" and (drafted or accepted)) or (arm != "native" and not (drafted > 0 and 0 <= accepted <= drafted)):
247
+ raise ValueError("Speculation counters do not match arm")
248
+ result.update(drafted=drafted, accepted=accepted, acceptance_percent=100 * accepted / drafted if drafted else None)
249
+ return result
250
+
251
+
252
+ def cache_snapshot(root):
253
+ out = {}
254
+ for path in sorted(root.rglob("*")):
255
+ if path.is_file():
256
+ stat = path.stat()
257
+ out[str(path.relative_to(root))] = {"bytes": stat.st_size, "mtime_ns": stat.st_mtime_ns, "sha256": digest(path)}
258
+ return out
259
+
260
+
261
+ def compilation_review(before, after, text):
262
+ changed = sorted(k for k in before.keys() | after.keys() if before.get(k) != after.get(k))
263
+ # The pinned image's vllm/usage/usage_lib.py appends uptime telemetry
264
+ # here every600s. It is not a compiler artifact. Keep all fingerprints
265
+ # and report this exact file separately; no cache directory is excluded.
266
+ telemetry = [k for k in changed if k.replace(chr(92), "/") == "home/.config/vllm/usage_stats.json"]
267
+ compiler = [k for k in changed if k not in telemetry]
268
+ events = [line for line in text.splitlines() if any(marker in line for marker in JIT_MARKERS)]
269
+ return {"clean": not compiler and not events, "cache_changes": compiler,
270
+ "all_files_changed": changed, "telemetry_file_changes": telemetry, "jit_events": events,
271
+ "scope": "Verbose JIT/autotune events and full cache fingerprints; only the exact vLLM uptime telemetry JSON is classified as non-compilation. Not a profiler."}
272
+
273
+
274
+ def percentile(values, q):
275
+ values = sorted(values)
276
+ if not values:
277
+ return None
278
+ index = (len(values) - 1) * q
279
+ lo, hi = math.floor(index), math.ceil(index)
280
+ return values[lo] + (values[hi] - values[lo]) * (index - lo)
281
+
282
+
283
+ def summarize_samples(samples, duration):
284
+ if duration <= 0 or not math.isfinite(duration):
285
+ raise ValueError("Invalid measured duration")
286
+ outputs = sum(s["output_tokens"] for s in samples)
287
+ out = {"requests": len(samples), "output_tokens": outputs, "duration_seconds": duration,
288
+ "output_tokens_per_second": outputs / duration, "requests_per_second": len(samples) / duration}
289
+ for key in ("ttft_s", "tpot_s", "e2e_s", "chunk_interval_s"):
290
+ values = [s[key] * 1000 for s in samples if s[key] is not None]
291
+ for p in (50, 95, 99):
292
+ out[key.removesuffix("_s") + f"_p{p}_ms"] = percentile(values, p / 100)
293
+ return out
294
+
295
+
296
+ def metrics(base, path):
297
+ with urllib.request.urlopen(base + "/metrics", timeout=30) as response:
298
+ value = response.read().decode("utf-8")
299
+ path.write_text(value, encoding="utf-8")
300
+ return value
301
+
302
+
303
+ def run_phase(base, rows, concurrency, directory, cache, server_log, arm, timed):
304
+ directory.mkdir()
305
+ before_metrics = metrics(base, directory / "metrics-before.txt")
306
+ before_cache = cache_snapshot(cache)
307
+ write_json(directory / "cache-before.json", before_cache)
308
+ offset = server_log.stat().st_size
309
+ records, seconds = run_workload(base, rows, concurrency, directory / "requests")
310
+ # Metrics export can lag the last SSE packet. This wait is outside timing.
311
+ deadline = time.monotonic() + 10
312
+ while True:
313
+ after_metrics = metrics(base, directory / "metrics-after.txt")
314
+ try:
315
+ counters = work_counters(before_metrics, after_metrics, rows, arm)
316
+ break
317
+ except ValueError:
318
+ if time.monotonic() >= deadline:
319
+ raise
320
+ time.sleep(0.25)
321
+ after_cache = cache_snapshot(cache)
322
+ write_json(directory / "cache-after.json", after_cache)
323
+ with server_log.open("rb") as handle:
324
+ handle.seek(offset)
325
+ text = handle.read().decode("utf-8", errors="replace")
326
+ (directory / "server-phase.log").write_text(text, encoding="utf-8")
327
+ review = compilation_review(before_cache, after_cache, text)
328
+ write_json(directory / "compilation-review.json", review)
329
+ peak = peak_concurrency(records)
330
+ if peak != concurrency:
331
+ raise ValueError(f"Actual streaming concurrency {peak} != {concurrency}")
332
+ samples = [{"output_tokens": len(r["token_ids"]), **{key: r[key] for key in
333
+ ("ttft_s", "tpot_s", "e2e_s", "chunk_interval_s")}} for r in records]
334
+ summary = {**summarize_samples(samples, seconds), "samples": samples,
335
+ "actual_peak_concurrency": peak, "work": counters,
336
+ "compilation": review, "timed": timed, "valid": not timed or review["clean"]}
337
+ write_json(directory / "summary.json", summary)
338
+ if timed and not review["clean"]:
339
+ raise RuntimeError("Compilation detected during timing; preserve this loop and stop")
340
+ return summary
341
+
342
+
343
+ def warmup(phase):
344
+ for number in range(1, MAX_WARMUPS + 1):
345
+ result = phase(number)
346
+ if number >= MIN_WARMUPS and result["compilation"]["clean"]:
347
+ return number
348
+ raise RuntimeError("Full-workload warmup did not converge; no timed loop launched")
349
+
350
+
351
+ def server_environment(cache):
352
+ home = cache / "home"
353
+ home.mkdir(parents=True)
354
+ env = dict(os.environ)
355
+ # Resolve the model cache before HOME is isolated, so model downloads persist.
356
+ env["HF_HOME"] = os.environ.get("HF_HOME", str(Path.home() / ".cache/huggingface"))
357
+ env.update(HOME=str(home), XDG_CACHE_HOME=str(home / ".cache"),
358
+ TRITON_CACHE_DIR=str(home / ".triton/cache"),
359
+ HUMMING_CACHE_DIR=str(home / ".humming/cache"),
360
+ VLLM_CACHE_ROOT=str(home / ".cache/vllm"),
361
+ DG_JIT_CACHE_DIR=str(home / ".deep_gemm"),
362
+ TORCHINDUCTOR_CACHE_DIR=str(home / ".cache/torchinductor"),
363
+ PYTHONDONTWRITEBYTECODE="1", PYTHONUNBUFFERED="1")
364
+ return env
365
+
366
+
367
+ def stop_server(process):
368
+ try:
369
+ os.killpg(process.pid, signal.SIGTERM)
370
+ except ProcessLookupError:
371
+ pass
372
+ try:
373
+ process.wait(timeout=30)
374
+ except subprocess.TimeoutExpired:
375
+ pass
376
+ # Kill remaining workers even if their parent exited first.
377
+ try:
378
+ os.killpg(process.pid, signal.SIGKILL)
379
+ except ProcessLookupError:
380
+ pass
381
+ process.wait(timeout=15)
382
+
383
+
384
+ @contextmanager
385
+ def running_server(arm, directory):
386
+ cache = directory / "compiler-cache"
387
+ env = server_environment(cache)
388
+ argv, plugins = launcher_module().command(arm, PORT)
389
+ env["VLLM_PLUGINS"] = plugins
390
+ write_json(directory / "launch.json", {"argv": argv, "VLLM_PLUGINS": plugins,
391
+ "cache_environment": {key: env[key] for key in ("HOME", "HF_HOME", "XDG_CACHE_HOME", "TRITON_CACHE_DIR", "HUMMING_CACHE_DIR", "VLLM_CACHE_ROOT", "DG_JIT_CACHE_DIR", "TORCHINDUCTOR_CACHE_DIR")}})
392
+ base = f"http://127.0.0.1:{PORT}"
393
+ with socket.socket() as probe:
394
+ if probe.connect_ex(("127.0.0.1", PORT)) == 0:
395
+ raise RuntimeError("Port 8000 already occupied; refusing to use another server")
396
+ log_path = directory / "server.log"
397
+ with log_path.open("w", encoding="utf-8") as log:
398
+ process = subprocess.Popen([sys.executable, "-u", str(LAUNCHER), "--arm", arm, "--port", str(PORT)],
399
+ stdout=log, stderr=subprocess.STDOUT, env=env, start_new_session=True)
400
+ write_json(directory / "process.json", {"pid": process.pid})
401
+ try:
402
+ deadline = time.monotonic() + 1800
403
+ while time.monotonic() < deadline and process.poll() is None:
404
+ try:
405
+ with urllib.request.urlopen(base + "/health", timeout=2):
406
+ pass
407
+ with urllib.request.urlopen(base + "/v1/models", timeout=5) as response:
408
+ models = json.load(response)
409
+ if MODEL not in [m["id"] for m in models["data"]]:
410
+ raise ValueError("Unexpected served model")
411
+ write_json(directory / "models.json", models)
412
+ break
413
+ except OSError:
414
+ time.sleep(1)
415
+ else:
416
+ raise RuntimeError("Server failed readiness; see server.log")
417
+ text = log_path.read_text(encoding="utf-8", errors="replace")
418
+ attested = "INKLING_AOT_WORKER_READY" in text
419
+ if attested != (arm == "optimized-dspark"):
420
+ raise RuntimeError("Worker plugin attestation does not match arm")
421
+ yield base, cache, log_path
422
+ finally:
423
+ stop_server(process)
424
+ write_json(directory / "cleanup.json", {"parent_returncode": process.returncode, "process_group_termination_requested": True})
425
+
426
+
427
+ def pooled(runs):
428
+ groups = []
429
+ for inputs, outputs in WORKLOADS:
430
+ for c in CONCURRENCIES:
431
+ for arm in ARMS:
432
+ cell = [r for r in runs if (r["input_tokens"], r["output_tokens_each"], r["concurrency"], r["arm"]) == (inputs, outputs, c, arm)]
433
+ row = {"input_tokens": inputs, "output_tokens_each": outputs, "concurrency": c, "arm": arm,
434
+ "completed_loops": len(cell), "complete": len(cell) == REPEATS and all(r["valid"] for r in cell)}
435
+ if row["complete"]:
436
+ row.update(summarize_samples([s for r in cell for s in r["samples"]], sum(r["duration_seconds"] for r in cell)))
437
+ drafted = sum(r["work"]["drafted"] for r in cell)
438
+ accepted = sum(r["work"]["accepted"] for r in cell)
439
+ row.update(acceptance_percent=100 * accepted / drafted if drafted else None)
440
+ groups.append(row)
441
+ return groups
442
+
443
+
444
+ def gpu_preflight(root):
445
+ gpu = subprocess.check_output(["nvidia-smi", "--query-gpu=name,uuid,driver_version,memory.total", "--format=csv,noheader,nounits"], text=True)
446
+ (root / "gpu.txt").write_text(gpu, encoding="utf-8")
447
+ rows = list(csv.reader(gpu.strip().splitlines()))
448
+ if len(rows) != 1 or "H100" not in rows[0][0] or float(rows[0][3]) < 79000:
449
+ raise RuntimeError("This benchmark requires exactly one visible H100 80GB")
450
+ apps = subprocess.check_output(["nvidia-smi", "--query-compute-apps=pid", "--format=csv,noheader,nounits"], text=True).strip()
451
+ (root / "gpu-compute-processes-before.txt").write_text(apps, encoding="utf-8")
452
+ if apps:
453
+ raise RuntimeError("GPU compute processes already present; stop other serving jobs first")
454
+ versions = {name: importlib.metadata.version(name) for name in ("vllm", "torch", "transformers")}
455
+ write_json(root / "runtime-versions.json", {"python": sys.version, "packages": versions})
456
+
457
+
458
+ def execute(root):
459
+ frozen = plan()
460
+ frozen["source_sha256"] = {p.name: digest(p) for p in (Path(__file__), LAUNCHER)}
461
+ write_json(root / "plan.json", frozen)
462
+ runs, status, error = [], "failed", None
463
+ try:
464
+ gpu_preflight(root)
465
+ pool = token_pool()
466
+ write_json(root / "token-pool.json", pool)
467
+ rows_by_shape = {str(i): workload(pool, i, o) for i, o in WORKLOADS}
468
+ for label, rows in rows_by_shape.items():
469
+ write_json(root / f"prompts-{label}.json", rows)
470
+ write_json(root / "workload-hashes.json", {p.name: digest(p) for p in sorted(root.glob("prompts-*.json"))})
471
+ for arm in ARMS:
472
+ directory = root / arm
473
+ directory.mkdir()
474
+ with running_server(arm, directory) as (base, cache, log):
475
+ for inputs, outputs in WORKLOADS:
476
+ rows = rows_by_shape[str(inputs)]
477
+ for c in CONCURRENCIES:
478
+ cell = directory / f"{inputs}x{outputs}-c{c}"
479
+ cell.mkdir()
480
+ def run(label, timed):
481
+ print(json.dumps({"arm": arm, "shape": [inputs, outputs], "c": c, "phase": label}), flush=True)
482
+ return run_phase(base, rows, c, cell / label, cache, log, arm, timed)
483
+ warmup(lambda n: run(f"warmup-{n}", False))
484
+ for repeat in range(1, REPEATS + 1):
485
+ result = run(f"measure-{repeat}", True)
486
+ runs.append(dict(result, input_tokens=inputs, output_tokens_each=outputs,
487
+ concurrency=c, arm=arm, repeat=repeat))
488
+ write_json(root / "completed-loops.json", runs)
489
+ status = "complete"
490
+ except BaseException as exc:
491
+ error = {"type": type(exc).__name__, "message": str(exc)}
492
+ raise
493
+ finally:
494
+ summary = pooled(runs)
495
+ write_json(root / "summary.json", {"status": status, "error": error, "benchmark_version": VERSION,
496
+ "cells": summary, "runs": runs, "accuracy_evaluated": False,
497
+ "limitations": [frozen["workload"], frozen["server_order"], "Chunk intervals are not per-token ITL. Fixed random-token output is not an accuracy test."]})
498
+ fields = ["input_tokens", "output_tokens_each", "concurrency", "arm", "complete", "completed_loops",
499
+ "requests", "output_tokens", "duration_seconds", "output_tokens_per_second", "requests_per_second",
500
+ "ttft_p50_ms", "tpot_p50_ms", "e2e_p50_ms", "acceptance_percent"]
501
+ with (root / "summary.csv").open("w", encoding="utf-8", newline="") as handle:
502
+ writer = csv.DictWriter(handle, fields, extrasaction="ignore")
503
+ writer.writeheader()
504
+ writer.writerows(summary)
505
+ print(json.dumps({"status": status, "evidence": str(root), "error": error}), flush=True)
506
+
507
+
508
+ def main():
509
+ parser = argparse.ArgumentParser(description=__doc__)
510
+ parser.add_argument("--output", type=Path, default=Path("/results"))
511
+ parser.add_argument("--plan", action="store_true", help="Print frozen settings without downloading weights or using a GPU")
512
+ args = parser.parse_args()
513
+ if args.plan:
514
+ print(json.dumps(plan(), indent=2))
515
+ return
516
+ if sys.platform != "linux":
517
+ parser.error("Run inside the published Linux NVIDIA container")
518
+ import fcntl
519
+ args.output.mkdir(parents=True, exist_ok=True)
520
+ # The host-mounted result directory coordinates cooperating invocations.
521
+ with (args.output / ".benchmark.lock").open("a") as lock:
522
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
523
+ root = (args.output / datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ")).resolve()
524
+ root.mkdir()
525
+ def interrupt(signum, frame):
526
+ raise KeyboardInterrupt(signal.Signals(signum).name)
527
+ signal.signal(signal.SIGTERM, interrupt)
528
+ execute(root)
529
+
530
+
531
+ if __name__ == "__main__":
532
+ main()
serve-benchmark-v1.2.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Matched benchmark launcher for the existing Inkling v1.0.0 container."""
3
+ import argparse
4
+ import json
5
+ import os
6
+
7
+ MODEL = "thinkingmachines/Inkling-2-Mini"
8
+ REVISION = "c9d028302cd0f035fdf8e7e91f089a4ce94d2195"
9
+ ARMS = ("native", "native-dspark", "optimized-dspark")
10
+ PLUGIN = "inkling2_mini_aot"
11
+
12
+
13
+ def command(arm, port=8000):
14
+ if arm not in ARMS:
15
+ raise ValueError("Unknown benchmark arm")
16
+ argv = [
17
+ "vllm", "serve", MODEL, "--revision", REVISION,
18
+ "--tokenizer-revision", REVISION, "--served-model-name", MODEL,
19
+ "--host", "127.0.0.1", "--port", str(port),
20
+ "--tensor-parallel-size", "1", "--dtype", "bfloat16",
21
+ "--max-model-len", "131072", "--max-num-seqs", "64",
22
+ "--max-num-batched-tokens", "8192", "--gpu-memory-utilization", "0.75",
23
+ "--reasoning-parser", "inkling", "--tool-call-parser", "inkling",
24
+ "--enable-auto-tool-choice", "--no-enable-prefix-caching",
25
+ "--jit-monitor-verbose",
26
+ ]
27
+ if arm != "native":
28
+ argv += ["--speculative-config", json.dumps({
29
+ "method": "dspark", "num_speculative_tokens": 7,
30
+ "draft_sample_method": "probabilistic",
31
+ "rejection_sample_method": "standard",
32
+ }, sort_keys=True)]
33
+ return argv, PLUGIN if arm == "optimized-dspark" else ""
34
+
35
+
36
+ def main():
37
+ parser = argparse.ArgumentParser(description=__doc__)
38
+ parser.add_argument("--arm", choices=ARMS, required=True)
39
+ parser.add_argument("--port", type=int, default=8000)
40
+ parser.add_argument("--print-command", action="store_true")
41
+ args = parser.parse_args()
42
+ argv, plugins = command(args.arm, args.port)
43
+ if args.print_command:
44
+ print(json.dumps({"argv": argv, "VLLM_PLUGINS": plugins}, indent=2))
45
+ return
46
+ os.environ["VLLM_PLUGINS"] = plugins
47
+ if plugins:
48
+ from inkling2_mini_kernels import _native, plugin
49
+ if "manifest.json" not in _native.names():
50
+ parser.error("Optimized wheel has no embedded bundle")
51
+ plugin.pins.check()
52
+ os.execvp(argv[0], argv)
53
+
54
+
55
+ if __name__ == "__main__":
56
+ main()