Inkling-2-Mini-Optimized / benchmark-v1.2.py
NeuralNovaAI's picture
Fix benchmark compilation classification for vLLM uptime telemetry
3ee4809 verified
Raw History Blame Contribute Delete
26.1 kB
#!/usr/bin/env python3
"""Three-arm controlled benchmark; uses the unchanged v1.0.0 container kernels.
New deterministic token-ID workload, not the historical reference prompt set.
Only standard library imports are needed for --help, --plan and CPU tests.
"""
import argparse
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
import csv
from datetime import datetime, timezone
import hashlib
import importlib.util
import importlib.metadata
import json
import math
import os
from pathlib import Path
import random
import re
import signal
import socket
import subprocess
import sys
import time
import urllib.request
VERSION = "1.2"
MODEL = "thinkingmachines/Inkling-2-Mini"
REVISION = "c9d028302cd0f035fdf8e7e91f089a4ce94d2195"
IMAGE = "registry.neural-nova.io/public/inkling2-mini@sha256:404e3c10d9e2c7ab90356715f403e1299ef8e51a1ffb44e634eaff76abc14c4e"
ARMS = ("native", "native-dspark", "optimized-dspark")
WORKLOADS = ((1024, 1024), (4096, 4096))
CONCURRENCIES = (1, 4)
REQUESTS = 32
REPEATS = 3
SEED = 42
PORT = 8000
MIN_WARMUPS = 2
MAX_WARMUPS = 3
LAUNCHER = Path(__file__).with_name("serve-benchmark-v1.2.py")
JIT_MARKERS = ("during inference:", "Triton autotuning", "[Autotuner]: Autotuning process starts")
SAMPLING = dict(temperature=0, seed=SEED, top_p=1, top_k=0, min_p=0,
repetition_penalty=1, presence_penalty=0, frequency_penalty=0)
def write_json(path, value):
path.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n", encoding="utf-8")
def digest(path):
h = hashlib.sha256()
with path.open("rb") as handle:
for block in iter(lambda: handle.read(1024 * 1024), b""):
h.update(block)
return h.hexdigest()
def launcher_module():
spec = importlib.util.spec_from_file_location("inkling_benchmark_launcher", LAUNCHER)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def plan():
launcher = launcher_module()
return {
"benchmark_version": VERSION, "required_image": IMAGE, "model_revision": REVISION,
"arms": list(ARMS), "concurrencies": list(CONCURRENCIES),
"workloads": list(WORKLOADS), "requests_per_timed_loop": REQUESTS,
"timed_repeats_per_cell": REPEATS, "timed_loops": 36,
"full_warmups_min": MIN_WARMUPS, "full_warmups_max": MAX_WARMUPS,
"sampling": SAMPLING, "speculative_rejection_sampling": "standard",
"workload": "Version 1.1 deterministic ordinary-token pool; frozen across all arms. Different prompts from the historical tables.",
"server_order": "One fresh server per arm, fixed listed order; repeats share a server, not independent server-order repetitions.",
"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.",
"timing": "Whole client loop wall time; no subtraction. Throughput=sum(output tokens)/sum(loop duration). Latencies pool request samples.",
"commands": {arm: {"argv": launcher.command(arm, PORT)[0], "VLLM_PLUGINS": launcher.command(arm, PORT)[1]} for arm in ARMS},
}
def token_pool():
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(MODEL, revision=REVISION)
text = (
"The river runs past the city and into the sea. A train crosses the old "
"bridge every morning while shops open along the street. Engineers test "
"each part before assembling the machine. They measure speed, noise, "
"temperature and power, then write the results in a small notebook. "
"If the numbers disagree, they repeat the experiment with the same "
"inputs and check what changed. The report includes tables, notes, "
"and examples for the people who will use the system next. "
"On weekends the market sells fruit, bread, cheese, tea and flowers. "
"Prices range from 1 to 30, depending on the month and the weather."
)
pool = sorted(set(tokenizer.encode(text, add_special_tokens=False)) - set(tokenizer.all_special_ids))
if len(pool) < 2:
raise ValueError("Tokenizer did not produce an ordinary token pool")
return pool
def workload(pool, input_tokens, output_tokens):
rng = random.Random(SEED + input_tokens)
return [{"id": i, "prompt_token_ids": rng.choices(pool, k=input_tokens),
"output_tokens": output_tokens} for i in range(REQUESTS)]
def completion(base, row, directory, open_response=urllib.request.urlopen):
payload = dict(model=MODEL, prompt=row["prompt_token_ids"], **SAMPLING,
max_tokens=row["output_tokens"], ignore_eos=True,
add_special_tokens=False, return_token_ids=True,
stream=True, stream_options={"include_usage": True})
encoded = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()
record = {"id": row["id"], "request": payload,
"request_sha256": hashlib.sha256(encoded).hexdigest(), "events": [], "success": False}
start = time.perf_counter()
record["start_monotonic"] = start
ids, arrivals = [], []
prompt, usage, finish, done = None, None, None, False
try:
req = urllib.request.Request(base + "/v1/completions", data=encoded,
headers={"Content-Type": "application/json"})
with open_response(req, timeout=900) as response:
for line in response:
if not line.startswith(b"data:"):
continue
raw = line[5:].strip()
if raw == b"[DONE]":
done = True
break
packet = json.loads(raw)
arrival = time.perf_counter() - start
record["events"].append({"seconds": arrival, "data": packet})
if packet.get("error"):
raise ValueError(str(packet["error"]))
usage = packet.get("usage") or usage
choices = packet.get("choices", [])
if any(c.get("index") != 0 for c in choices) or len(choices) > 1:
raise ValueError("Expected exactly one completion choice")
for source in [packet, *choices]:
if source.get("prompt_token_ids") is not None:
prompt = source["prompt_token_ids"]
if prompt != row["prompt_token_ids"]:
raise ValueError("Response prompt IDs differ from frozen input")
for choice in choices:
chunk = choice.get("token_ids") or []
if chunk:
ids.extend(chunk)
arrivals.append((arrival, len(chunk)))
finish = choice.get("finish_reason") or finish
record["end_monotonic"] = time.perf_counter()
if (not done or not usage or not arrivals or prompt != row["prompt_token_ids"]
or usage.get("prompt_tokens") != len(prompt)
or usage.get("completion_tokens") != row["output_tokens"]
or len(ids) != row["output_tokens"] or finish != "length"):
raise ValueError("Incomplete fixed-length workload or missing SSE/usage evidence")
record.update(success=True, token_ids=ids, prompt_token_ids=prompt,
usage=usage, finish_reason=finish, arrivals=arrivals,
ttft_s=arrivals[0][0], e2e_s=record["end_monotonic"] - start,
tpot_s=(arrivals[-1][0] - arrivals[0][0]) / (len(ids) - 1),
chunk_interval_s=(arrivals[-1][0] - arrivals[0][0]) / (len(arrivals) - 1) if len(arrivals) > 1 else None)
return record
except BaseException as exc:
record.update(error_type=type(exc).__name__, error=str(exc))
raise
finally:
# Keep partial streams even when protocol validation fails.
write_json(directory / f"request-{row['id']:04d}.json", record)
def run_workload(base, rows, concurrency, directory):
directory.mkdir()
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=concurrency) as executor:
futures = [executor.submit(completion, base, row, directory) for row in rows]
records, failures = [], []
for row, future in zip(rows, futures):
try:
records.append(future.result())
except Exception as exc:
failures.append({"id": row["id"], "error": str(exc)})
duration = time.perf_counter() - start
if failures:
write_json(directory / "failures.json", failures)
raise RuntimeError("Request failures; raw evidence preserved, stopping benchmark")
return records, duration
def peak_concurrency(records):
points = [(r["start_monotonic"], 1) for r in records] + [(r["end_monotonic"], -1) for r in records]
active = peak = 0
for _, delta in sorted(points):
active += delta
peak = max(peak, active)
if active != 0:
raise ValueError("Unbalanced request intervals")
return peak
def metric_series(text, name, source=None):
pattern = re.compile(r"^" + re.escape(name) + r"(\{[^\n]*\})?\s+([^\s]+)(?:\s+[^\s]+)?$")
out = {}
for line in text.splitlines():
match = pattern.fullmatch(line)
if not match:
continue
labels = match.group(1) or ""
if source is not None and not re.search(r'(?:\{|,)\s*source="' + re.escape(source) + r'"(?:,|\})', labels):
continue
value = float(match.group(2))
if not math.isfinite(value) or value < 0 or labels in out:
raise ValueError("Invalid/duplicate metric: " + name)
out[labels] = value
return out
def metric_delta(before, after, name, source=None, optional=False):
a, b = metric_series(before, name, source), metric_series(after, name, source)
if not b:
if optional and not a:
return 0
raise ValueError("Required metric missing: " + name)
if a.keys() - b.keys() or any(v < a.get(k, 0) for k, v in b.items()):
raise ValueError("Counter reset/disappeared: " + name)
return sum(v - a.get(k, 0) for k, v in b.items())
def work_counters(before, after, rows, arm):
expected_prompt = sum(len(r["prompt_token_ids"]) for r in rows)
expected_output = sum(r["output_tokens"] for r in rows)
definitions = {
"prompt": ("vllm:prompt_tokens_total", None, expected_prompt),
"computed_prefill": ("vllm:prompt_tokens_by_source_total", "local_compute", expected_prompt),
"generated": ("vllm:generation_tokens_total", None, expected_output),
"cached": ("vllm:prompt_tokens_cached_total", None, 0),
"preemptions": ("vllm:num_preemptions_total", None, 0),
}
result = {}
for key, (name, source, expected) in definitions.items():
result[key] = metric_delta(before, after, name, source)
if result[key] != expected:
raise ValueError(f"Unequal work: {key}={result[key]}, expected {expected}")
drafted = metric_delta(before, after, "vllm:spec_decode_num_draft_tokens_total", optional=arm == "native")
accepted = metric_delta(before, after, "vllm:spec_decode_num_accepted_tokens_total", optional=arm == "native")
if (arm == "native" and (drafted or accepted)) or (arm != "native" and not (drafted > 0 and 0 <= accepted <= drafted)):
raise ValueError("Speculation counters do not match arm")
result.update(drafted=drafted, accepted=accepted, acceptance_percent=100 * accepted / drafted if drafted else None)
return result
def cache_snapshot(root):
out = {}
for path in sorted(root.rglob("*")):
if path.is_file():
stat = path.stat()
out[str(path.relative_to(root))] = {"bytes": stat.st_size, "mtime_ns": stat.st_mtime_ns, "sha256": digest(path)}
return out
def compilation_review(before, after, text):
changed = sorted(k for k in before.keys() | after.keys() if before.get(k) != after.get(k))
# The pinned image's vllm/usage/usage_lib.py appends uptime telemetry
# here every600s. It is not a compiler artifact. Keep all fingerprints
# and report this exact file separately; no cache directory is excluded.
telemetry = [k for k in changed if k.replace(chr(92), "/") == "home/.config/vllm/usage_stats.json"]
compiler = [k for k in changed if k not in telemetry]
events = [line for line in text.splitlines() if any(marker in line for marker in JIT_MARKERS)]
return {"clean": not compiler and not events, "cache_changes": compiler,
"all_files_changed": changed, "telemetry_file_changes": telemetry, "jit_events": events,
"scope": "Verbose JIT/autotune events and full cache fingerprints; only the exact vLLM uptime telemetry JSON is classified as non-compilation. Not a profiler."}
def percentile(values, q):
values = sorted(values)
if not values:
return None
index = (len(values) - 1) * q
lo, hi = math.floor(index), math.ceil(index)
return values[lo] + (values[hi] - values[lo]) * (index - lo)
def summarize_samples(samples, duration):
if duration <= 0 or not math.isfinite(duration):
raise ValueError("Invalid measured duration")
outputs = sum(s["output_tokens"] for s in samples)
out = {"requests": len(samples), "output_tokens": outputs, "duration_seconds": duration,
"output_tokens_per_second": outputs / duration, "requests_per_second": len(samples) / duration}
for key in ("ttft_s", "tpot_s", "e2e_s", "chunk_interval_s"):
values = [s[key] * 1000 for s in samples if s[key] is not None]
for p in (50, 95, 99):
out[key.removesuffix("_s") + f"_p{p}_ms"] = percentile(values, p / 100)
return out
def metrics(base, path):
with urllib.request.urlopen(base + "/metrics", timeout=30) as response:
value = response.read().decode("utf-8")
path.write_text(value, encoding="utf-8")
return value
def run_phase(base, rows, concurrency, directory, cache, server_log, arm, timed):
directory.mkdir()
before_metrics = metrics(base, directory / "metrics-before.txt")
before_cache = cache_snapshot(cache)
write_json(directory / "cache-before.json", before_cache)
offset = server_log.stat().st_size
records, seconds = run_workload(base, rows, concurrency, directory / "requests")
# Metrics export can lag the last SSE packet. This wait is outside timing.
deadline = time.monotonic() + 10
while True:
after_metrics = metrics(base, directory / "metrics-after.txt")
try:
counters = work_counters(before_metrics, after_metrics, rows, arm)
break
except ValueError:
if time.monotonic() >= deadline:
raise
time.sleep(0.25)
after_cache = cache_snapshot(cache)
write_json(directory / "cache-after.json", after_cache)
with server_log.open("rb") as handle:
handle.seek(offset)
text = handle.read().decode("utf-8", errors="replace")
(directory / "server-phase.log").write_text(text, encoding="utf-8")
review = compilation_review(before_cache, after_cache, text)
write_json(directory / "compilation-review.json", review)
peak = peak_concurrency(records)
if peak != concurrency:
raise ValueError(f"Actual streaming concurrency {peak} != {concurrency}")
samples = [{"output_tokens": len(r["token_ids"]), **{key: r[key] for key in
("ttft_s", "tpot_s", "e2e_s", "chunk_interval_s")}} for r in records]
summary = {**summarize_samples(samples, seconds), "samples": samples,
"actual_peak_concurrency": peak, "work": counters,
"compilation": review, "timed": timed, "valid": not timed or review["clean"]}
write_json(directory / "summary.json", summary)
if timed and not review["clean"]:
raise RuntimeError("Compilation detected during timing; preserve this loop and stop")
return summary
def warmup(phase):
for number in range(1, MAX_WARMUPS + 1):
result = phase(number)
if number >= MIN_WARMUPS and result["compilation"]["clean"]:
return number
raise RuntimeError("Full-workload warmup did not converge; no timed loop launched")
def server_environment(cache):
home = cache / "home"
home.mkdir(parents=True)
env = dict(os.environ)
# Resolve the model cache before HOME is isolated, so model downloads persist.
env["HF_HOME"] = os.environ.get("HF_HOME", str(Path.home() / ".cache/huggingface"))
env.update(HOME=str(home), XDG_CACHE_HOME=str(home / ".cache"),
TRITON_CACHE_DIR=str(home / ".triton/cache"),
HUMMING_CACHE_DIR=str(home / ".humming/cache"),
VLLM_CACHE_ROOT=str(home / ".cache/vllm"),
DG_JIT_CACHE_DIR=str(home / ".deep_gemm"),
TORCHINDUCTOR_CACHE_DIR=str(home / ".cache/torchinductor"),
PYTHONDONTWRITEBYTECODE="1", PYTHONUNBUFFERED="1")
return env
def stop_server(process):
try:
os.killpg(process.pid, signal.SIGTERM)
except ProcessLookupError:
pass
try:
process.wait(timeout=30)
except subprocess.TimeoutExpired:
pass
# Kill remaining workers even if their parent exited first.
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass
process.wait(timeout=15)
@contextmanager
def running_server(arm, directory):
cache = directory / "compiler-cache"
env = server_environment(cache)
argv, plugins = launcher_module().command(arm, PORT)
env["VLLM_PLUGINS"] = plugins
write_json(directory / "launch.json", {"argv": argv, "VLLM_PLUGINS": plugins,
"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")}})
base = f"http://127.0.0.1:{PORT}"
with socket.socket() as probe:
if probe.connect_ex(("127.0.0.1", PORT)) == 0:
raise RuntimeError("Port 8000 already occupied; refusing to use another server")
log_path = directory / "server.log"
with log_path.open("w", encoding="utf-8") as log:
process = subprocess.Popen([sys.executable, "-u", str(LAUNCHER), "--arm", arm, "--port", str(PORT)],
stdout=log, stderr=subprocess.STDOUT, env=env, start_new_session=True)
write_json(directory / "process.json", {"pid": process.pid})
try:
deadline = time.monotonic() + 1800
while time.monotonic() < deadline and process.poll() is None:
try:
with urllib.request.urlopen(base + "/health", timeout=2):
pass
with urllib.request.urlopen(base + "/v1/models", timeout=5) as response:
models = json.load(response)
if MODEL not in [m["id"] for m in models["data"]]:
raise ValueError("Unexpected served model")
write_json(directory / "models.json", models)
break
except OSError:
time.sleep(1)
else:
raise RuntimeError("Server failed readiness; see server.log")
text = log_path.read_text(encoding="utf-8", errors="replace")
attested = "INKLING_AOT_WORKER_READY" in text
if attested != (arm == "optimized-dspark"):
raise RuntimeError("Worker plugin attestation does not match arm")
yield base, cache, log_path
finally:
stop_server(process)
write_json(directory / "cleanup.json", {"parent_returncode": process.returncode, "process_group_termination_requested": True})
def pooled(runs):
groups = []
for inputs, outputs in WORKLOADS:
for c in CONCURRENCIES:
for arm in ARMS:
cell = [r for r in runs if (r["input_tokens"], r["output_tokens_each"], r["concurrency"], r["arm"]) == (inputs, outputs, c, arm)]
row = {"input_tokens": inputs, "output_tokens_each": outputs, "concurrency": c, "arm": arm,
"completed_loops": len(cell), "complete": len(cell) == REPEATS and all(r["valid"] for r in cell)}
if row["complete"]:
row.update(summarize_samples([s for r in cell for s in r["samples"]], sum(r["duration_seconds"] for r in cell)))
drafted = sum(r["work"]["drafted"] for r in cell)
accepted = sum(r["work"]["accepted"] for r in cell)
row.update(acceptance_percent=100 * accepted / drafted if drafted else None)
groups.append(row)
return groups
def gpu_preflight(root):
gpu = subprocess.check_output(["nvidia-smi", "--query-gpu=name,uuid,driver_version,memory.total", "--format=csv,noheader,nounits"], text=True)
(root / "gpu.txt").write_text(gpu, encoding="utf-8")
rows = list(csv.reader(gpu.strip().splitlines()))
if len(rows) != 1 or "H100" not in rows[0][0] or float(rows[0][3]) < 79000:
raise RuntimeError("This benchmark requires exactly one visible H100 80GB")
apps = subprocess.check_output(["nvidia-smi", "--query-compute-apps=pid", "--format=csv,noheader,nounits"], text=True).strip()
(root / "gpu-compute-processes-before.txt").write_text(apps, encoding="utf-8")
if apps:
raise RuntimeError("GPU compute processes already present; stop other serving jobs first")
versions = {name: importlib.metadata.version(name) for name in ("vllm", "torch", "transformers")}
write_json(root / "runtime-versions.json", {"python": sys.version, "packages": versions})
def execute(root):
frozen = plan()
frozen["source_sha256"] = {p.name: digest(p) for p in (Path(__file__), LAUNCHER)}
write_json(root / "plan.json", frozen)
runs, status, error = [], "failed", None
try:
gpu_preflight(root)
pool = token_pool()
write_json(root / "token-pool.json", pool)
rows_by_shape = {str(i): workload(pool, i, o) for i, o in WORKLOADS}
for label, rows in rows_by_shape.items():
write_json(root / f"prompts-{label}.json", rows)
write_json(root / "workload-hashes.json", {p.name: digest(p) for p in sorted(root.glob("prompts-*.json"))})
for arm in ARMS:
directory = root / arm
directory.mkdir()
with running_server(arm, directory) as (base, cache, log):
for inputs, outputs in WORKLOADS:
rows = rows_by_shape[str(inputs)]
for c in CONCURRENCIES:
cell = directory / f"{inputs}x{outputs}-c{c}"
cell.mkdir()
def run(label, timed):
print(json.dumps({"arm": arm, "shape": [inputs, outputs], "c": c, "phase": label}), flush=True)
return run_phase(base, rows, c, cell / label, cache, log, arm, timed)
warmup(lambda n: run(f"warmup-{n}", False))
for repeat in range(1, REPEATS + 1):
result = run(f"measure-{repeat}", True)
runs.append(dict(result, input_tokens=inputs, output_tokens_each=outputs,
concurrency=c, arm=arm, repeat=repeat))
write_json(root / "completed-loops.json", runs)
status = "complete"
except BaseException as exc:
error = {"type": type(exc).__name__, "message": str(exc)}
raise
finally:
summary = pooled(runs)
write_json(root / "summary.json", {"status": status, "error": error, "benchmark_version": VERSION,
"cells": summary, "runs": runs, "accuracy_evaluated": False,
"limitations": [frozen["workload"], frozen["server_order"], "Chunk intervals are not per-token ITL. Fixed random-token output is not an accuracy test."]})
fields = ["input_tokens", "output_tokens_each", "concurrency", "arm", "complete", "completed_loops",
"requests", "output_tokens", "duration_seconds", "output_tokens_per_second", "requests_per_second",
"ttft_p50_ms", "tpot_p50_ms", "e2e_p50_ms", "acceptance_percent"]
with (root / "summary.csv").open("w", encoding="utf-8", newline="") as handle:
writer = csv.DictWriter(handle, fields, extrasaction="ignore")
writer.writeheader()
writer.writerows(summary)
print(json.dumps({"status": status, "evidence": str(root), "error": error}), flush=True)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output", type=Path, default=Path("/results"))
parser.add_argument("--plan", action="store_true", help="Print frozen settings without downloading weights or using a GPU")
args = parser.parse_args()
if args.plan:
print(json.dumps(plan(), indent=2))
return
if sys.platform != "linux":
parser.error("Run inside the published Linux NVIDIA container")
import fcntl
args.output.mkdir(parents=True, exist_ok=True)
# The host-mounted result directory coordinates cooperating invocations.
with (args.output / ".benchmark.lock").open("a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
root = (args.output / datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ")).resolve()
root.mkdir()
def interrupt(signum, frame):
raise KeyboardInterrupt(signal.Signals(signum).name)
signal.signal(signal.SIGTERM, interrupt)
execute(root)
if __name__ == "__main__":
main()