From f249abab8bd15b85cf6f7187bbaf2dba7fad46bc Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Sun, 22 Nov 2026 21:01:23 +1100 Subject: [PATCH 01/50] fix(ci): start the reference server at the verbosity that logs GPU offload A comparison failed at the reference arm's first server with "server log has no positive GPU-layer offload evidence". At the pinned llama.cpp, llama-server's default log verbosity is 3 (info) and the library's own INFO lines are filed under 4 (trace), so `load_tensors: offloaded N/M layers to GPU`, the line the startup check reads, was never written. Both Skippy arms had passed the same check earlier in that run. The reference now starts with `-lv 4`, and each of its samples records `log_verbosity` in what was applied. At that level the server adds lines per request and none in its per-token path; the effect on the reference's figures has not been measured. --- ci/INFERENCE_PERFORMANCE.md | 4 +++- scripts/lib/performance_arms.py | 8 ++++++-- scripts/tests/inference_performance_contracts.py | 6 ++++++ 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index 9c64226b..d1e53b29 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -62,7 +62,9 @@ the pool existed, runs without it. Each sample records what was applied and what the arm did not support. All arms are probed before model measurements begin. An arm missing required endpoint/model/context/GPU or startup options fails explicitly as unsupported before any measured round; required options are never silently omitted. `llama-server` gets the same lanes and the same -total context (`-np`, `-c`, `-kvu`). +total context (`-np`, `-c`, `-kvu`). It also starts with `-lv 4`: at the pinned +llama.cpp that is the lowest log verbosity that prints the GPU-offload line the +startup check reads, and the sample records it as `log_verbosity`. ## Traces diff --git a/scripts/lib/performance_arms.py b/scripts/lib/performance_arms.py index 6c1118cb..0c1b622c 100644 --- a/scripts/lib/performance_arms.py +++ b/scripts/lib/performance_arms.py @@ -10,6 +10,9 @@ REQUIRED = ("--startup-timeout-secs", "--bind-addr", "--model-id", "--ctx-size", "--n-gpu-layers", "--model-path") METAL = {"LLAMA_STAGE_BACKEND": "metal", "LLAMA_STAGE_LINK_MODE": "static"} +# llama.cpp files its library's INFO lines under trace, and the offload line the +# startup check reads is one of them. +REFERENCE_VERBOSITY = 4 def checkout(arm): @@ -67,8 +70,9 @@ def server_args(built, help_text, model, coordinate, context, server): if built["kind"] == "llama-server": total = pool if pool is not None else context * lanes args = [built["binary"], "-m", str(model), "--host", "127.0.0.1", "--port", str(PORT), - "-ngl", "999", "-np", str(lanes), "-c", str(total), "-kvu", "--alias", coordinate] - return args, {"lanes": lanes, "total_context": total}, [] + "-ngl", "999", "-np", str(lanes), "-c", str(total), "-kvu", + "-lv", str(REFERENCE_VERBOSITY), "--alias", coordinate] + return args, {"lanes": lanes, "total_context": total, "log_verbosity": REFERENCE_VERBOSITY}, [] args = [built["binary"], "serve", "--startup-timeout-secs", "300", "--ctx-size", str(context), "--n-gpu-layers", "999", "--bind-addr", f"127.0.0.1:{PORT}", "--model-path", str(model), "--model-id", coordinate] diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index 0f8d7e19..65d8827b 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -175,6 +175,12 @@ def test_llama_server_gets_the_same_cells(self): _, applied, _ = server_args(built, "", "/m.gguf", "org/m@rev", 8192, unpooled) self.assertEqual(applied["total_context"], 4 * 8192) + def test_llama_server_starts_at_trace_verbosity_and_records_it(self): + built = {"label": "reference", "kind": "llama-server", "binary": "/b/llama-server"} + args, applied, _ = server_args(built, "", "/m.gguf", "org/m@rev", 8192, self.server) + self.assertEqual(args[args.index("-lv") + 1], "4") + self.assertEqual(applied["log_verbosity"], 4) + class ReportTests(unittest.TestCase): record = {"started_at": "2026-11-21T10:00:00Z", "arms": [{"label": "candidate", "sha": "a" * 40}]} From c9cc99fd87e04bd773aff8fbb15ad67bb859eaec Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Sun, 22 Nov 2026 21:59:39 +1100 Subject: [PATCH 02/50] feat(ci): keep what the reference rejects under KV pressure as a result A failed request fails the job. Two points ask for more KV than their server's pool holds once every request is in flight: sixteen lanes at depth 4,096 in the 32K pool, and four lanes at that depth in the 16K pool. By its source at the pin, `llama-server` frees KV from idle slots only, and once that is not enough it fails every request it is processing with "Context size has been exceeded". With the reference on, that would end a comparison at the reference's first such point. At those points, and for `llama-server` alone, failed requests are now its result. The sample keeps null metrics and `rejected`: the measured requests, how many failed, how many were cut short, and AIPerf's error details with their counts. The summary table shows `rejected (n=N)` for that arm, and the stored row carries `rejected` as JSON text. The server must still be running afterwards. A failed request on a Skippy arm, or from `llama-server` inside its pool, fails the job as before. The rejection is read from AIPerf's per-request export, because its summary cannot carry it. With every measured request failed, AIPerf 0.13.0 exits 1 and writes no summary. And it counts a stream that ends on an error event as served, which is how `llama-server` fails a request that has started answering; such a request has no output length in the per-request export, and is counted as cut short. None of this has run on hardware. What `llama-server` does is read from its source, and AIPerf's exit code and exports were checked against a stand-in server. --- ci/INFERENCE_PERFORMANCE.md | 19 ++- scripts/inference-performance.py | 12 +- scripts/lib/performance_arms.py | 12 ++ scripts/lib/performance_load.py | 45 +++++- scripts/lib/performance_report.py | 33 +++-- .../tests/inference_performance_contracts.py | 134 +++++++++++++++++- 6 files changed, 231 insertions(+), 24 deletions(-) diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index d1e53b29..36cca866 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -66,6 +66,15 @@ total context (`-np`, `-c`, `-kvu`). It also starts with `-lv 4`: at the pinned llama.cpp that is the lowest log verbosity that prints the GPU-offload line the startup check reads, and the sample records it as `log_verbosity`. +A failed request fails the job: a point counts only when AIPerf reports every +request served. `llama-server` has one exception. It frees KV from idle slots +only, so at a point whose requests, all in flight, need more than its pool holds +it fails them: sixteen lanes at depth 4,096 in the 32K pool, and four lanes at +that depth in the 16K pool. There the failures are its result. The sample keeps +them as `rejected`, with null metrics, and the summary table shows `rejected` for +that arm. The server must still be running afterwards, or the job fails. A Skippy +arm is held to every point. + ## Traces With `trace` on, each job runs the candidate once more per model and server after @@ -85,8 +94,13 @@ The job writes `performance.json` with the harness commit, scenario digest, host chip, macOS version and Metal working-set limit, every arm's commit and binary SHA-256, the model shards, and one sample per model, round, arm and point. Each sample holds output tokens per second, requests per second, time to first token (p50 and p95), -inter-token latency (p50), request latency (p50) and mean output tokens. Server -logs, build logs and the AIPerf exports (as `aiperf.tar.gz`) sit beside it. +inter-token latency (p50), request latency (p50) and mean output tokens. A sample +from a point its server rejected has those as null and a `rejected` entry: the +measured requests, how many AIPerf recorded as failed, how many were cut short, +and its error details with their counts. Cut short means a stream that ended on +an error event: AIPerf counts it as served and leaves it without an output +length. Server logs, build logs and the AIPerf exports (as `aiperf.tar.gz`) sit +beside it. The controller checks that evidence against the admitted plan and writes a table of medians, round ranges and the candidate's change against the baseline to the @@ -105,6 +119,7 @@ For graphs over time it also writes `LABEL-rows.jsonl` beside each job's with the job, when the run started, the host, the arm's commit and when it was committed, the model revision, the server's lanes and pool, the point's concurrency, depth and token counts, the round, and each metric as its own column. +A rejected point keeps its row, with null metrics and the `rejected` entry as JSON text. An arm taken from a pull request has `on_main` false and its number in `pull_request`; llama.cpp's server has `on_main` null. Rows from every run can share one table. With DuckDB, over a folder per run, main's history alone: diff --git a/scripts/inference-performance.py b/scripts/inference-performance.py index 8b2107b4..77c52ea8 100644 --- a/scripts/inference-performance.py +++ b/scripts/inference-performance.py @@ -24,7 +24,7 @@ from lib.inference_inputs import admit as admit_model from lib.inference_inputs import fixture from lib.jy_qualification import ORIGIN, Pilot -from lib.performance_arms import build, capabilities, server_args, supports +from lib.performance_arms import build, capabilities, may_reject, server_args, supports from lib.performance_load import run_point, tokenizer from lib.performance_plan import (SCENARIO, arms, job_spec, models, nodes, pull_request_head, pull_request_number, round_order, scenario) @@ -281,12 +281,16 @@ def measure(built, help_text, model, inputs, key, index, server, shape, output, ready(process, 900) offload(log) for point in server["points"]: - metrics = run_point(ENDPOINT, point, coordinate, inputs["tokenizer_path"], - shape["warmup_requests"], WORK / "aiperf" / name / point["id"]) + metrics, rejected = run_point(ENDPOINT, point, coordinate, inputs["tokenizer_path"], + shape["warmup_requests"], WORK / "aiperf" / name / point["id"], + may_reject=may_reject(built, server, point)) + # A rejection is the answer of a server that is still serving; one that died is a fault. + if rejected is not None and process.poll() is not None: + raise RuntimeError("server exited while it was rejecting requests; inspect its log") samples.append({"model": key, "round": None if index is None else index + 1, "arm": built["label"], "server": server["id"], "point": point["id"], "applied": applied, - "unsupported": missing, "metrics": metrics}) + "unsupported": missing, "metrics": metrics, "rejected": rejected}) finally: stop(process) return samples diff --git a/scripts/lib/performance_arms.py b/scripts/lib/performance_arms.py index 0c1b622c..fa208c53 100644 --- a/scripts/lib/performance_arms.py +++ b/scripts/lib/performance_arms.py @@ -90,3 +90,15 @@ def server_args(built, help_text, model, coordinate, context, server): args += [flag] if value is None else [flag, str(value)] applied[flag.removeprefix("--").replace("-", "_")] = True if value is None else value return args, applied, missing + + +def may_reject(built, server, point): + """Whether failed requests at this point are a result rather than a fault. + + `llama-server` frees KV from idle slots only, so when the requests in flight need more + than its pool holds it fails them. Only there is a failure its answer: a Skippy arm is + held to every point, and so is `llama-server` inside its pool. + """ + pool = server["pool_tokens"] + in_flight = point["concurrency"] * (point["depth"] + point["input_tokens"] + point["output_tokens"]) + return built["kind"] == "llama-server" and pool is not None and in_flight > pool diff --git a/scripts/lib/performance_load.py b/scripts/lib/performance_load.py index fdeae2be..359dcac0 100644 --- a/scripts/lib/performance_load.py +++ b/scripts/lib/performance_load.py @@ -1,5 +1,8 @@ """Drive one load point with the pinned AIPerf and read back what it measured.""" +import json +import subprocess +from collections import Counter from pathlib import Path from .ci_artifacts import read_json @@ -64,9 +67,45 @@ def measurements(export): for name, (metric, statistic) in METRICS.items()} -def run_point(endpoint, point, coordinate, tokenizer_path, warmup, directory: Path): - command(profile_args(endpoint, point, coordinate, tokenizer_path, warmup, directory), timeout=5400) +def rejection(directory, requests): + """What the server failed among the measured requests, from AIPerf's per-request export. + + AIPerf records an error for a request the server answers with one. A stream that ends on + an error event it counts as served and leaves without an output length: that request is + cut short here. None when nothing failed, and None unless the export accounts for every + measured request, so a load run that broke off is never taken for the server's answer. + """ + exports = list(directory.rglob("profile_export.jsonl")) + if len(exports) != 1: + return None + # One record a line. A server's own error text sits inside a record, so split on newlines alone. + records = [json.loads(line) for line in exports[0].read_text(encoding="utf-8").split("\n") if line.strip()] + measured = [record for record in records + if (record.get("metadata") or {}).get("benchmark_phase") == "profiling"] + failed = Counter(json.dumps(record["error"], sort_keys=True) for record in measured if record.get("error")) + cut_short = sum(1 for record in measured if not record.get("error") + and "output_sequence_length" not in (record.get("metrics") or {})) + if len(measured) != requests or not (failed or cut_short): + return None + return {"requests": requests, "failed": sum(failed.values()), "cut_short": cut_short, + "errors": [{"error_details": json.loads(error), "count": count} + for error, count in sorted(failed.items())]} + + +def run_point(endpoint, point, coordinate, tokenizer_path, warmup, directory: Path, *, may_reject): + """One point's metrics, or null metrics and what the server rejected where it may reject.""" + failure = None + try: + command(profile_args(endpoint, point, coordinate, tokenizer_path, warmup, directory), timeout=5400) + except subprocess.CalledProcessError as error: + # AIPerf exits non-zero, with no summary export, when every measured request failed. + failure = error + rejected = rejection(directory, point["requests"]) if may_reject else None + if rejected is not None: + return dict.fromkeys(METRICS), rejected + if failure is not None: + raise failure exports = list(directory.rglob("profile_export_aiperf.json")) if len(exports) != 1: raise ValueError(f'{point["id"]}: expected one AIPerf export, found {len(exports)}') - return measurements(read_json(exports[0])) + return measurements(read_json(exports[0])), None diff --git a/scripts/lib/performance_report.py b/scripts/lib/performance_report.py index 2b4f3d73..293fac95 100644 --- a/scripts/lib/performance_report.py +++ b/scripts/lib/performance_report.py @@ -14,9 +14,15 @@ def summarize(samples): - """Group by (model, server, point, metric), then by arm: median, min, max and n over rounds.""" - groups = {} + """Group by (model, server, point, metric), then by arm: median, min, max and n over rounds. + + `rejected` counts, by arm, the rounds in which the arm's server rejected the point. + """ + groups, rejected = {}, {} for sample in samples: + if sample["rejected"] is not None: + rounds = rejected.setdefault((sample["model"], sample["server"], sample["point"]), {}) + rounds[sample["arm"]] = rounds.get(sample["arm"], 0) + 1 for metric, value in sample["metrics"].items(): if value is None: continue @@ -27,6 +33,7 @@ def summarize(samples): arms = {arm: {"median": statistics.median(values), "min": min(values), "max": max(values), "n": len(values)} for arm, values in sorted(by_arm.items())} rows.append({"model": model, "server": server, "point": point, "metric": metric, "arms": arms, + "rejected": rejected.get((model, server, point), {}), "candidate_vs_baseline": change(arms.get("candidate"), arms.get("baseline"))}) return rows @@ -39,10 +46,12 @@ def change(candidate, baseline): "ranges_overlap": overlap} -def cell(stats): +def cell(stats, rejected): + """An arm's rounds at one point: what they measured, and how many of them its server rejected.""" if not stats: - return "—" - return f'{stats["median"]:.1f} ({stats["min"]:.1f}–{stats["max"]:.1f}, n={stats["n"]})' + return f"rejected (n={rejected})" if rejected else "—" + measured = f'{stats["median"]:.1f} ({stats["min"]:.1f}–{stats["max"]:.1f}, n={stats["n"]})' + return f"{measured}; rejected n={rejected}" if rejected else measured def verdict(row): @@ -87,13 +96,16 @@ def markdown(title, host, rows, record): lines = ["# " + plain(title), "", "Host: " + plain(host), "", *health_sections(view, health_charts(view), chart_format="mermaid"), "", "## Round ranges", "", "Median (min–max, n). Reference is the optional llama.cpp arm. " - "Its measurements are shown separately from the candidate/baseline verdict.", ""] + "Its measurements are shown separately from the candidate/baseline verdict. " + "Rejected is the number of rounds in which its server failed requests at a point " + "that needs more KV than its pool holds.", ""] detail = [] for row in rows: if row["metric"] in HEADLINE: arms = row["arms"] detail.append([plain(row[field]) for field in ("model", "server", "point", "metric")] + - [cell(arms.get(arm)) for arm in ("baseline", "candidate", "reference")] + [verdict(row)]) + [cell(arms.get(arm), row["rejected"].get(arm, 0)) + for arm in ("baseline", "candidate", "reference")] + [verdict(row)]) lines.extend(table(["Model", "Server", "Point", "Metric", "Baseline", "Candidate", "Reference", "Change"], detail)) return "\n".join(lines) + "\n" @@ -106,7 +118,8 @@ def rows(record, shape, committed_at, job, pull_requests): `started_at` orders runs by when they ran. An arm that `pull_requests` maps to a pull request has `on_main` false, so a graph of main's history can leave it out; llama.cpp's server has it null. What an arm applied or lacked differs by arm, so it is kept as JSON - text and every row has the same columns. + text and every row has the same columns. A point the server rejected keeps its row: its + metrics are null and `rejected` holds what was rejected, as JSON text. """ arms = {arm["label"]: arm for arm in record["arms"]} points = {(server["id"], point["id"]): (server, point) @@ -131,5 +144,7 @@ def rows(record, shape, committed_at, job, pull_requests): "input_tokens": point["input_tokens"], "output_tokens": point["output_tokens"], "requests": point["requests"], "round": sample["round"], "applied": json.dumps(sample["applied"], sort_keys=True), - "unsupported": json.dumps(sample["unsupported"]), **sample["metrics"], + "unsupported": json.dumps(sample["unsupported"]), + "rejected": None if sample["rejected"] is None else json.dumps(sample["rejected"], sort_keys=True), + **sample["metrics"], } diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index 65d8827b..ca81cf4b 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -7,8 +7,8 @@ from unittest.mock import Mock, patch from lib import performance_plan -from lib.performance_arms import REQUIRED, capabilities, server_args -from lib.performance_load import measurements +from lib.performance_arms import REQUIRED, capabilities, may_reject, server_args +from lib.performance_load import measurements, rejection, run_point from lib import performance_report from lib.performance_report import markdown, summarize @@ -181,6 +181,105 @@ def test_llama_server_starts_at_trace_verbosity_and_records_it(self): self.assertEqual(args[args.index("-lv") + 1], "4") self.assertEqual(applied["log_verbosity"], 4) + def test_only_llama_server_may_reject_a_point_and_only_past_its_pool(self): + reference = {"label": "reference", "kind": "llama-server", "binary": "/b/llama-server"} + cells = [(server, point) for server in performance_plan.scenario()["servers"] + for point in server["points"]] + self.assertEqual([point["id"] for server, point in cells if may_reject(reference, server, point)], + ["c16-depth4096", "c4-depth4096-pool16k"]) + self.assertFalse(any(may_reject(self.skippy, server, point) for server, point in cells)) + + +class RejectionTests(unittest.TestCase): + point = {"id": "c4-depth4096-pool16k", "concurrency": 4, "depth": 4096, "input_tokens": 512, + "output_tokens": 128, "requests": 4} + refused = {"code": 500, "type": "Internal Server Error", "message": "Context size has been exceeded."} + summary = {"request_count": {"avg": 4}, "request_error_rate": {"avg": 0}, "error_summary": [], + "is_complete": True, "output_token_throughput": {"avg": 120.5}} + + def write(self, directory, failed=(), served=0, cut_short=0): + """AIPerf's per-request export: two warmup requests, then the measured ones.""" + def request(phase, error, metrics): + return {"metadata": {"benchmark_phase": phase}, "error": error, "metrics": metrics} + + whole = {"output_sequence_length": {"value": 128, "unit": "tokens"}} + records = ([request("warmup", None, whole)] * 2 + + [request("profiling", error, {}) for error in failed] + + [request("profiling", None, whole)] * served + + [request("profiling", None, {"request_latency": {"value": 9.5, "unit": "ms"}})] * cut_short) + (Path(directory) / "profile_export.jsonl").write_text( + "".join(json.dumps(record) + "\n" for record in records), encoding="utf-8") + + def drive(self, directory, may_reject): + return run_point("http://127.0.0.1:9337", self.point, "org/m@rev", "/t", 2, Path(directory), + may_reject=may_reject) + + def test_rejection_counts_failed_and_cut_short_requests_among_the_measured_ones(self): + from tempfile import TemporaryDirectory + other = dict(self.refused, code=503) + with TemporaryDirectory() as directory: + self.write(directory, failed=[self.refused, other, self.refused], cut_short=1) + self.assertEqual(rejection(Path(directory), 4), { + "requests": 4, "failed": 3, "cut_short": 1, + "errors": [{"error_details": self.refused, "count": 2}, {"error_details": other, "count": 1}]}) + # A load run that broke off before every request is not the server's answer. + self.assertIsNone(rejection(Path(directory), 5)) + with TemporaryDirectory() as directory: + self.assertIsNone(rejection(Path(directory), 4)) + self.write(directory, served=4) + self.assertIsNone(rejection(Path(directory), 4)) + + def test_a_point_the_server_may_reject_keeps_what_it_rejected_in_place_of_metrics(self): + from subprocess import CalledProcessError + from tempfile import TemporaryDirectory + with TemporaryDirectory() as directory: + self.write(directory, failed=[self.refused] * 4) + # AIPerf exits non-zero, with no summary export, when every measured request failed. + with patch("lib.performance_load.command", side_effect=CalledProcessError(1, ["aiperf"])): + metrics, rejected = self.drive(directory, may_reject=True) + self.assertEqual((metrics["output_tok_s"], set(metrics.values())), (None, {None})) + self.assertEqual((rejected["failed"], rejected["cut_short"]), (4, 0)) + with self.assertRaises(CalledProcessError): + self.drive(directory, may_reject=False) + with TemporaryDirectory() as directory: + self.write(directory, failed=[self.refused], served=2, cut_short=1) + (Path(directory) / "profile_export_aiperf.json").write_text(json.dumps(self.summary)) + with patch("lib.performance_load.command"): + self.assertEqual(self.drive(directory, may_reject=True)[1]["cut_short"], 1) + + def test_a_point_the_server_served_is_measured_and_a_broken_load_run_still_fails(self): + from subprocess import CalledProcessError + from tempfile import TemporaryDirectory + with TemporaryDirectory() as directory: + self.write(directory, served=4) + (Path(directory) / "profile_export_aiperf.json").write_text(json.dumps(self.summary)) + with patch("lib.performance_load.command"): + metrics, rejected = self.drive(directory, may_reject=True) + self.assertEqual((metrics["output_tok_s"], rejected), (120.5, None)) + with patch("lib.performance_load.command", side_effect=CalledProcessError(1, ["aiperf"])): + with self.assertRaises(CalledProcessError): + self.drive(directory, may_reject=True) + + def test_a_rejected_point_is_a_sample_only_while_its_server_stays_up(self): + from tempfile import TemporaryDirectory + measure = run_path(str(Path(__file__).resolve().parents[1] / "inference-performance.py"))["measure"] + built = {"label": "reference", "kind": "llama-server", "binary": "/b/llama-server"} + server = {"id": "lanes4-pool16k", "lanes": 4, "pool_tokens": 16384, "points": [self.point]} + inputs = {"repo": "org/m", "revision": "rev", "tokenizer_path": "/t"} + shape = {"context_per_lane": 8192, "warmup_requests": 2} + rejected = {"requests": 4, "failed": 4, "cut_short": 0, "errors": []} + process, load = Mock(), Mock(return_value=({"output_tok_s": None}, rejected)) + with TemporaryDirectory() as directory, patch.dict( + measure.__globals__, start=Mock(return_value=process), ready=Mock(), offload=Mock(), + stop=Mock(), run_point=load): + process.poll.return_value = None + sample, = measure(built, "", "/m.gguf", inputs, "m", 0, server, shape, Path(directory)) + self.assertEqual((sample["rejected"], sample["metrics"]), (rejected, {"output_tok_s": None})) + self.assertTrue(load.call_args.kwargs["may_reject"]) + process.poll.return_value = 1 + with self.assertRaisesRegex(RuntimeError, "exited while it was rejecting"): + measure(built, "", "/m.gguf", inputs, "m", 0, server, shape, Path(directory)) + class ReportTests(unittest.TestCase): record = {"started_at": "2026-11-21T10:00:00Z", "arms": [{"label": "candidate", "sha": "a" * 40}]} @@ -201,7 +300,8 @@ def test_measurements_reject_failed_requests_and_keep_missing_metrics_null(self) def test_medians_spreads_and_verdicts(self): def sample(arm, value): - return {"model": "m", "server": "s", "point": "p", "arm": arm, "metrics": {"output_tok_s": value}} + return {"model": "m", "server": "s", "point": "p", "arm": arm, "metrics": {"output_tok_s": value}, + "rejected": None} rows = summarize([sample("baseline", v) for v in (100, 102, 98)] + [sample("candidate", v) for v in (120, 118, 121)]) @@ -215,7 +315,7 @@ def sample(arm, value): def test_one_percent_rule_keeps_range_uncertainty_and_actual_p50_labels(self): def row(metric, candidate): return summarize([{"model": "m", "server": "s", "point": "p", "arm": arm, - "metrics": {metric: value}} + "metrics": {metric: value}, "rejected": None} for arm, values in (("baseline", (90, 100, 110)), ("candidate", (candidate - 10, candidate, candidate + 10))) for value in values])[0] @@ -238,7 +338,24 @@ def row(metric, candidate): self.assertIn('bar [100.00000000, 102.00000000, 70.00000000]', report) with self.assertRaises(ValueError): summarize([{"model": "m", "server": "s", "point": "p", "arm": "candidate", - "metrics": {"output_tok_s": float("nan")}}]) + "metrics": {"output_tok_s": float("nan")}, "rejected": None}]) + + def test_rejected_rounds_are_counted_beside_the_arms_that_measured_the_point(self): + rejected = {"requests": 16, "failed": 14, "cut_short": 2, "errors": []} + + def sample(arm, value, rejected=None): + return {"model": "m", "server": "s", "point": "p", "arm": arm, "metrics": {"output_tok_s": value}, + "rejected": rejected} + + rows = summarize([sample("baseline", v) for v in (100, 102, 98)] + + [sample("candidate", v) for v in (120, 118, 121)] + + [sample("reference", None, rejected)] * 3) + self.assertEqual((rows[0]["rejected"], sorted(rows[0]["arms"])), + ({"reference": 3}, ["baseline", "candidate"])) + self.assertIn("| rejected (n=3) |", markdown("t", "h", rows, self.record)) + self.assertEqual(performance_report.cell({"median": 70, "min": 68, "max": 72, "n": 2}, 1), + "70.0 (68.0–72.0, n=2); rejected n=1") + self.assertEqual(performance_report.cell(None, 0), "—") def test_stored_rows_carry_their_arm_point_and_host_but_not_the_trace_pass(self): shape = performance_plan.scenario() @@ -246,7 +363,7 @@ def test_stored_rows_carry_their_arm_point_and_host_but_not_the_trace_pass(self) point = server["points"][0] measured = {"model": "qwen35-4b", "round": 2, "arm": "baseline", "server": server["id"], "point": point["id"], "applied": {}, "unsupported": [], - "metrics": {"output_tok_s": 99.5, "ttft_ms_p50": None}} + "metrics": {"output_tok_s": 99.5, "ttft_ms_p50": None}, "rejected": None} record = {"harness": "d" * 40, "scenario_sha256": "e" * 64, "started_at": "2026-11-21T10:00:00+00:00", "host": {"chip": "Apple M1 Ultra", "node": "n1"}, "arms": [{"label": "baseline", "kind": "skippy", "sha": "b" * 40, "binary_sha256": "f" * 64}, @@ -261,7 +378,12 @@ def test_stored_rows_carry_their_arm_point_and_host_but_not_the_trace_pass(self) self.assertEqual((row["lanes"], row["concurrency"], row["depth"]), (server["lanes"], point["concurrency"], point["depth"])) self.assertEqual((row["output_tok_s"], row["ttft_ms_p50"], row["chip"]), (99.5, None, "Apple M1 Ultra")) + self.assertIsNone(row["rejected"]) json.dumps(row) + rejected = {"requests": 8, "failed": 8, "cut_short": 0, "errors": []} + record["samples"] = [{**measured, "metrics": {"output_tok_s": None}, "rejected": rejected}] + stored, = performance_report.rows(record, shape, {}, "job_1", {}) + self.assertEqual((stored["output_tok_s"], json.loads(stored["rejected"])), (None, rejected)) if __name__ == "__main__": From ccaea2f333c2f311314a803e424435f6e77881f1 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Wed, 25 Nov 2026 15:48:22 +1100 Subject: [PATCH 03/50] feat(ci): accept a branch of this repository as a performance arm --- .github/workflows/inference-performance.yml | 4 +-- ci/INFERENCE_PERFORMANCE.md | 11 +++--- scripts/inference-performance.py | 36 ++++++++++++------- scripts/lib/performance_plan.py | 7 ++++ scripts/lib/performance_report.py | 15 ++++---- .../tests/inference_performance_contracts.py | 20 +++++++++-- 6 files changed, 65 insertions(+), 28 deletions(-) diff --git a/.github/workflows/inference-performance.yml b/.github/workflows/inference-performance.yml index 3259058d..e14c21e5 100644 --- a/.github/workflows/inference-performance.yml +++ b/.github/workflows/inference-performance.yml @@ -3,11 +3,11 @@ on: workflow_dispatch: inputs: candidate: - description: Ref or SHA on main to measure, or pr:N for the head of an open pull request from this repository. + description: Ref or SHA on main to measure, pr:N for the head of an open pull request from this repository, or branch:NAME for a branch's head. type: string default: main baseline: - description: Ref or SHA on main, or pr:N, to compare against. The candidate again gives an A/A noise run. + description: Ref or SHA on main, pr:N or branch:NAME, to compare against. The candidate again gives an A/A noise run. type: string required: true reference: diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index 36cca866..efd575f2 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -18,8 +18,8 @@ gh workflow run inference-performance.yml -f candidate=main \ | input | meaning | |---|---| -| `candidate` | ref or SHA on main to measure, or `pr:N` for the head of open pull request N; default `main` | -| `baseline` | ref, SHA or `pr:N` to compare against; passing the candidate again gives an A/A noise run | +| `candidate` | ref or SHA on main to measure, `pr:N` for the head of open pull request N, or `branch:NAME` for a branch's head; default `main` | +| `baseline` | ref, SHA, `pr:N` or `branch:NAME` to compare against; passing the candidate again gives an A/A noise run | | `reference` | add llama.cpp's `llama-server` at the candidate's `llama_cpp/upstream.txt` pin; default on | | `models` | `ci/inference-ladder.json` ids; shards are the hash-pinned files in `ci/inference-artifacts.json` | | `nodes` | Metal nodes, one job each; empty runs one job on any Metal Mac with room for the largest model plus 16 GiB | @@ -28,7 +28,9 @@ gh workflow run inference-performance.yml -f candidate=main \ Both commits must be on protected main, unless an arm is `pr:N`: the head of an open pull request from this repository, never a fork's, authored by a collaborator with write access, so only code that could -already run on trusted CI reaches the lab. Such an arm is reported, and stored, +already run on trusted CI reaches the lab. An arm can also be `branch:NAME`, the head of a +branch of this repository, for a line of work that tracks main without a pull request: only +collaborators with write access can push one, the bar `pr:N` sets for its author. Such an arm is reported, and stored, as not on main; with `pr:N` as the baseline, a change stacked on another pull request is measured against that one alone. The controller and the harness always come from main, so every arm is driven by the same scripts and scenario, @@ -121,7 +123,8 @@ committed, the model revision, the server's lanes and pool, the point's concurrency, depth and token counts, the round, and each metric as its own column. A rejected point keeps its row, with null metrics and the `rejected` entry as JSON text. An arm taken from a pull request has `on_main` false and its number in -`pull_request`; llama.cpp's server has `on_main` null. Rows from every run can +`pull_request`; one taken from a branch has `on_main` false and its name in `branch`; +llama.cpp's server has `on_main` null. Rows from every run can share one table. With DuckDB, over a folder per run, main's history alone: ```sql diff --git a/scripts/inference-performance.py b/scripts/inference-performance.py index 77c52ea8..7389abd8 100644 --- a/scripts/inference-performance.py +++ b/scripts/inference-performance.py @@ -26,7 +26,7 @@ from lib.jy_qualification import ORIGIN, Pilot from lib.performance_arms import build, capabilities, may_reject, server_args, supports from lib.performance_load import run_point, tokenizer -from lib.performance_plan import (SCENARIO, arms, job_spec, models, nodes, pull_request_head, +from lib.performance_plan import (SCENARIO, arms, branch_name, job_spec, models, nodes, pull_request_head, pull_request_number, round_order, scenario) from lib.performance_report import markdown, rows, summarize @@ -56,23 +56,30 @@ def resolve_main(ref): def resolve(ref): - """A commit on main, or with `pr:N` an open pull request's head, as (commit, N or None).""" + """A commit on main, with `pr:N` an open pull request's head, or with `branch:NAME` a branch's head, as + (commit, N or None, NAME or None). Only collaborators with write access can push a branch here, which is + the same bar `pr:N` sets for its author.""" + branch = branch_name(ref) + if branch is not None: + return github(f"repos/{REPO}/branches/{quote(branch, safe='')}")["commit"]["sha"], None, branch number = pull_request_number(ref) if number is None: - return resolve_main(ref), None + return resolve_main(ref), None, None pull = github(f"repos/{REPO}/pulls/{number}") sha = pull_request_head(pull, REPO) login = pull["user"]["login"] permission = github(f"repos/{REPO}/collaborators/{quote(login, safe='')}/permission")["permission"] if permission not in {"admin", "maintain", "write"}: raise ValueError("native performance PR author must be a repository collaborator with write access") - return sha, number + return sha, number, None -def off_main(pull_requests): - """A line for each arm taken from a pull request, so no report reads as main's.""" - return "".join(f"The {label} is the head of #{number}, not a commit on main.\n\n" - for label, number in pull_requests.items() if number is not None) +def off_main(pull_requests, branches=None): + """A line for each arm taken from a pull request or a branch, so no report reads as main's.""" + return "".join([*(f"The {label} is the head of #{number}, not a commit on main.\n\n" + for label, number in pull_requests.items() if number is not None), + *(f"The {label} is the head of branch {name}, not a commit on main.\n\n" + for label, name in (branches or {}).items() if name is not None)]) def reference_pin(sha): @@ -88,9 +95,10 @@ def committed_at(arm_list): def admit(evidence): harness = capture(["git", "rev-parse", "HEAD"]).strip() - candidate, candidate_pull = resolve(os.environ["CANDIDATE"]) - baseline, baseline_pull = resolve(os.environ["BASELINE"]) + candidate, candidate_pull, candidate_branch = resolve(os.environ["CANDIDATE"]) + baseline, baseline_pull, baseline_branch = resolve(os.environ["BASELINE"]) pull_requests = {"candidate": candidate_pull, "baseline": baseline_pull} + branches = {"candidate": candidate_branch, "baseline": baseline_branch} with_reference = os.environ.get("REFERENCE", "true") == "true" trace = os.environ.get("TRACE", "false") == "true" arm_list = arms(candidate, baseline, reference_pin(candidate) if with_reference else None) @@ -103,10 +111,11 @@ def admit(evidence): evidence.mkdir(parents=True, exist_ok=True) write_json(evidence / "plan.json", {"harness": harness, "arms": arm_list, "models": keys, "rounds": rounds, "trace": trace, "pull_requests": pull_requests, + "branches": branches, "committed_at": committed_at(arm_list), "jobs": jobs}) for arm in arm_list: print(f'{arm["label"]}: {arm["kind"]} {arm["sha"]}') - print(off_main(pull_requests), end="") + print(off_main(pull_requests, branches), end="") print(f"{len(jobs)} job(s), {len(keys)} model(s), {rounds} round(s); nothing has run yet") @@ -169,7 +178,8 @@ def collect(pilot, job, plan, label, evidence): write_json(evidence / f"{label}-performance.json", result) (evidence / f"{label}-rows.jsonl").write_text( "".join(json.dumps(row, sort_keys=True) + "\n" - for row in rows(result, scenario(), plan["committed_at"], job["id"], plan["pull_requests"])), + for row in rows(result, scenario(), plan["committed_at"], job["id"], plan["pull_requests"], + plan.get("branches"))), encoding="utf-8") if plan["trace"]: download(pilot, run_id, "traces.tar.gz", evidence / f"{label}-traces.tar.gz") @@ -203,7 +213,7 @@ def dispatch(evidence): failures.append(f'{spec["label"]}: {job["status"]}') continue reports.append(collect(pilot, job, plan, spec["label"], evidence)) - report = off_main(plan["pull_requests"]) + "\n".join(reports) + report = off_main(plan["pull_requests"], plan.get("branches")) + "\n".join(reports) (evidence / "summary.md").write_text(report, encoding="utf-8") if os.environ.get("GITHUB_STEP_SUMMARY"): with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as stream: diff --git a/scripts/lib/performance_plan.py b/scripts/lib/performance_plan.py index d1e784d0..7f5fc043 100644 --- a/scripts/lib/performance_plan.py +++ b/scripts/lib/performance_plan.py @@ -15,6 +15,7 @@ LLAMA = "https://github.com/ggml-org/llama.cpp.git" SHA = re.compile(r"[0-9a-f]{40}") PULL_REQUEST = re.compile(r"pr:([1-9][0-9]{0,6})") +BRANCH = re.compile(r"branch:([A-Za-z0-9._/-]{1,200})") NODE = re.compile(r"[A-Za-z0-9._-]{1,64}") RESERVE_GIB = 16 MAX_ROUNDS = 9 @@ -64,6 +65,12 @@ def pull_request_number(ref): return int(match[1]) if match else None +def branch_name(ref): + """`branch:NAME` names the head of a branch of this repository, measured as off main.""" + match = BRANCH.fullmatch(ref) + return match[1] if match else None + + def pull_request_head(pull, repository): """The head of an open pull request from this repository: a fork's code never runs on the lab.""" if pull.get("state") != "open" or (pull.get("head", {}).get("repo") or {}).get("full_name") != repository: diff --git a/scripts/lib/performance_report.py b/scripts/lib/performance_report.py index 293fac95..37c597e7 100644 --- a/scripts/lib/performance_report.py +++ b/scripts/lib/performance_report.py @@ -110,16 +110,16 @@ def markdown(title, host, rows, record): return "\n".join(lines) + "\n" -def rows(record, shape, committed_at, job, pull_requests): +def rows(record, shape, committed_at, job, pull_requests, branches=None): """One flat row per measured sample, for a table that graphs runs over time. The diagnostic pass is left out. Every row carries what it was measured on and with, so rows from many runs can share one table: `committed_at` orders arms by commit, `started_at` orders runs by when they ran. An arm that `pull_requests` maps to a pull - request has `on_main` false, so a graph of main's history can leave it out; llama.cpp's - server has it null. What an arm applied or lacked differs by arm, so it is kept as JSON - text and every row has the same columns. A point the server rejected keeps its row: its - metrics are null and `rejected` holds what was rejected, as JSON text. + request, or `branches` to a branch, has `on_main` false, so a graph of main's history can + leave it out; llama.cpp's server has it null. What an arm applied or lacked differs by arm, + so it is kept as JSON text and every row has the same columns. A point the server rejected + keeps its row: its metrics are null and `rejected` holds what was rejected, as JSON text. """ arms = {arm["label"]: arm for arm in record["arms"]} points = {(server["id"], point["id"]): (server, point) @@ -128,6 +128,7 @@ def rows(record, shape, committed_at, job, pull_requests): for sample in record["samples"]: arm = arms[sample["arm"]] pull_request = pull_requests.get(sample["arm"]) + branch = (branches or {}).get(sample["arm"]) server, point = points[(sample["server"], sample["point"])] yield { "schema_version": 1, "job": job, "started_at": record.get("started_at"), @@ -136,8 +137,8 @@ def rows(record, shape, committed_at, job, pull_requests): "metal_working_set_bytes": host.get("metal_working_set_bytes"), "arm": sample["arm"], "kind": arm["kind"], "sha": arm["sha"], "committed_at": committed_at.get(arm["sha"]), "binary_sha256": arm["binary_sha256"], - "on_main": None if arm["kind"] != "skippy" else pull_request is None, - "pull_request": pull_request, + "on_main": None if arm["kind"] != "skippy" else pull_request is None and branch is None, + "pull_request": pull_request, "branch": branch, "model": sample["model"], "model_revision": record["models"][sample["model"]]["revision"], "server": sample["server"], "lanes": server["lanes"], "pool_tokens": server["pool_tokens"], "point": sample["point"], "concurrency": point["concurrency"], "depth": point["depth"], diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index ca81cf4b..e0bfcdff 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -69,12 +69,24 @@ def github(path): return pull if path.endswith("/pulls/130") else {"permission": permission} with patch.dict(resolve.__globals__, github=github): if permission in {"write", "maintain", "admin"}: - self.assertEqual(resolve("pr:130"), (self.candidate, 130)) + self.assertEqual(resolve("pr:130"), (self.candidate, 130, None)) else: with self.assertRaisesRegex(ValueError, "collaborator"): resolve("pr:130") self.assertEqual(calls[-1], "repos/Mesh-LLM/skippy/collaborators/author/permission") + def test_an_arm_can_be_a_branch_of_this_repository(self): + resolve = run_path(str(Path(__file__).resolve().parents[1] / "inference-performance.py"))["resolve"] + calls = [] + def github(path): + calls.append(path) + return {"commit": {"sha": self.candidate}} + with patch.dict(resolve.__globals__, github=github): + self.assertEqual(resolve("branch:team/gen-ai"), (self.candidate, None, "team/gen-ai")) + self.assertEqual(calls, ["repos/Mesh-LLM/skippy/branches/team%2Fgen-ai"]) + for ref in ("branch:", "branch:a b", "branches:x", "pr:130"): + self.assertIsNone(performance_plan.branch_name(ref)) + def test_every_arm_leads_one_round(self): arm_list = performance_plan.arms(self.candidate, self.baseline, self.pin) firsts = [performance_plan.round_order(arm_list, index)[0]["label"] for index in range(3)] @@ -372,8 +384,12 @@ def test_stored_rows_carry_their_arm_point_and_host_but_not_the_trace_pass(self) "diagnostic": {"samples": [{**measured, "round": None}]}} row, pulled = performance_report.rows(record, shape, {"b" * 40: "2026-11-20T10:16:30Z"}, "job_1", {"candidate": 130, "baseline": None}) + branched, _ = performance_report.rows(record, shape, {}, "job_1", {"candidate": None, "baseline": None}, + {"baseline": "team/gen-ai", "candidate": None}) + self.assertEqual((branched["on_main"], branched["branch"], branched["pull_request"]), + (False, "team/gen-ai", None)) self.assertEqual((row["sha"], row["committed_at"], row["round"]), ("b" * 40, "2026-11-20T10:16:30Z", 2)) - self.assertEqual((row["on_main"], row["pull_request"]), (True, None)) + self.assertEqual((row["on_main"], row["pull_request"], row["branch"]), (True, None, None)) self.assertEqual((pulled["sha"], pulled["on_main"], pulled["pull_request"]), ("a" * 40, False, 130)) self.assertEqual((row["lanes"], row["concurrency"], row["depth"]), (server["lanes"], point["concurrency"], point["depth"])) From fda19f366bab5d4f85631e50d24d1dcdc8a2982a Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Wed, 25 Nov 2026 15:48:22 +1100 Subject: [PATCH 04/50] feat(ci): add a backend table and a GB10 CUDA entry to performance runs --- Justfile | 2 +- ci/INFERENCE_PERFORMANCE.md | 35 +++++-- scripts/inference-performance.py | 62 +++++++----- scripts/lib/inference_checks.py | 9 +- scripts/lib/performance_arms.py | 33 +++++-- scripts/lib/performance_backends.py | 99 +++++++++++++++++++ scripts/lib/performance_plan.py | 30 +++--- scripts/lib/performance_report.py | 10 +- .../tests/inference_performance_contracts.py | 62 +++++++++++- 9 files changed, 283 insertions(+), 59 deletions(-) create mode 100644 scripts/lib/performance_backends.py diff --git a/Justfile b/Justfile index f8e95024..01be0c90 100644 --- a/Justfile +++ b/Justfile @@ -240,7 +240,7 @@ inference-performance-cancel ledger="target/ci-evidence/inference-performance/jo @"{{ automation_python }}" scripts/inference-performance.py cancel "$@" inference-performance-build: - @command -v hf uv cmake ninja cargo && xcrun --find swift + @command -v hf uv cmake ninja cargo && {{ automation_python }} scripts/inference-performance.py toolcheck @"{{ automation_python }}" scripts/inference-performance.py build inference-performance-execute: diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index efd575f2..a3a6ef4d 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -26,6 +26,24 @@ gh workflow run inference-performance.yml -f candidate=main \ | `rounds` | rounds per arm, at most 9; default 3 | | `trace` | after the rounds, one diagnostic pass of the candidate with debug telemetry; default off | +## Backends + +`admit` reads `BACKEND` (default `metal`) and refuses any value that has no entry in the +backend table, `scripts/lib/performance_backends.py`. The plan records the backend; build +and execute read it from the plan and never infer it from the host, so a job always +measures the machine it was planned for. Each entry holds the selector fragment of the JY +target, the Skippy build overrides, the reference build's accelerator CMake flags, the +tool check that runs before any build, the script that resolves a native toolkit for the +reference build when it needs one, the device prefixes that count as GPU offload evidence, +and the functions that prove the host and measure its free memory. A backend without a +complete entry fails at plan time, not partway through a job. + +The table holds `metal` (any Apple M-series Mac whose Metal device is its own GPU) and +`cuda` (a DGX Spark: Linux aarch64, an NVIDIA GB10, unified memory, CUDA architecture +121). The Spark's reference arm builds with `-DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=121`, +configuring with the same toolkit environment `scripts/lib/cuda-toolkit.sh` resolves for +Skippy's build. The GitHub workflow still dispatches Metal only. + Both commits must be on protected main, unless an arm is `pr:N`: the head of an open pull request from this repository, never a fork's, authored by a collaborator with write access, so only code that could already run on trusted CI reaches the lab. An arm can also be `branch:NAME`, the head of a @@ -39,16 +57,17 @@ and an older commit is never asked to run code it does not have. ## What one job does 1. Builds each arm from its own checkout with release settings: `just - llama-build` with Metal static linking, then `cargo build --release -p + llama-build` with the backend's build overrides, then `cargo build --release -p skippy-cli`; the reference builds `llama-server` with CMake. Qualification uses debug builds; a comparison measures what ships. 2. Admits each model through the same hash-verified cache as qualification and - checks the weights plus 16 GiB against the lesser of free and inactive - memory and Metal's working-set limit, as qualification does. + checks the weights plus the backend's reserve against the backend's free memory: + the lesser of free and inactive memory and Metal's working-set limit on `metal`, + `MemAvailable` on `cuda`. -Any Apple M-series Mac whose Metal device is its own GPU can run a job, not -only the M3 Ultra that qualification requires: arms are compared on one host, -never across hosts. The job refuses to run as root. +Any Apple M-series Mac whose Metal device is its own GPU, or a DGX Spark, can +run a job, not only the hardware qualification requires: arms are compared on +one host, never across hosts. The job refuses to run as root. 3. For each model and round, runs every arm in rotated order (each arm leads one round in three), and for each arm starts one server per entry in `ci/inference-performance.json`, then drives each of its points with the @@ -93,7 +112,9 @@ writes nothing. ## Evidence The job writes `performance.json` with the harness commit, scenario digest, -host chip, macOS version and Metal working-set limit, every arm's commit and binary SHA-256, the model +the host facts the backend records (chip, macOS version and Metal working-set limit on +`metal`; GPU, driver, CUDA version, OS release and kernel on `cuda`), every arm's commit +and binary SHA-256, the model shards, and one sample per model, round, arm and point. Each sample holds output tokens per second, requests per second, time to first token (p50 and p95), inter-token latency (p50), request latency (p50) and mean output tokens. A sample diff --git a/scripts/inference-performance.py b/scripts/inference-performance.py index 7389abd8..e02b5315 100644 --- a/scripts/inference-performance.py +++ b/scripts/inference-performance.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Compare Skippy commits, and llama.cpp's own server, on one Metal host at a time.""" +"""Compare Skippy commits, and llama.cpp's own server, on one host of any backend in the table.""" import argparse import base64 @@ -19,12 +19,12 @@ from lib.ci_artifacts import digest, read_json, write_json from lib.ci_process import cancel_on_signal, capture, command, start, stop from lib.ci_smoke import curl -from lib import inference_metal from lib.inference_checks import ENDPOINT, offload from lib.inference_inputs import admit as admit_model from lib.inference_inputs import fixture from lib.jy_qualification import ORIGIN, Pilot from lib.performance_arms import build, capabilities, may_reject, server_args, supports +from lib.performance_backends import BACKENDS from lib.performance_load import run_point, tokenizer from lib.performance_plan import (SCENARIO, arms, branch_name, job_spec, models, nodes, pull_request_head, pull_request_number, round_order, scenario) @@ -37,7 +37,6 @@ # Outside the artifact directory: artifact names are flat, so the traces travel as one archive. TRACES = WORK / "traces" TERMINAL = {"succeeded", "failed", "cancelled", "expired"} -RESERVE = 16 * 1024**3 def github(path): @@ -101,22 +100,25 @@ def admit(evidence): branches = {"candidate": candidate_branch, "baseline": baseline_branch} with_reference = os.environ.get("REFERENCE", "true") == "true" trace = os.environ.get("TRACE", "false") == "true" + backend = os.environ.get("BACKEND") or "metal" arm_list = arms(candidate, baseline, reference_pin(candidate) if with_reference else None) keys = models([key.strip() for key in os.environ["MODELS"].split(",") if key.strip()]) pins = nodes([node.strip() for node in os.environ.get("NODES", "").split(",") if node.strip()]) rounds = int(os.environ.get("ROUNDS") or 3) jobs = [{"label": node or "any", - "spec": job_spec(harness, arm_list, keys, rounds, node, node or "any", trace=trace)} + "spec": job_spec(harness, arm_list, keys, rounds, node, node or "any", + trace=trace, backend=backend)} for node in (pins or [None])] evidence.mkdir(parents=True, exist_ok=True) - write_json(evidence / "plan.json", {"harness": harness, "arms": arm_list, "models": keys, + write_json(evidence / "plan.json", {"harness": harness, "backend": backend, "arms": arm_list, + "models": keys, "rounds": rounds, "trace": trace, "pull_requests": pull_requests, "branches": branches, "committed_at": committed_at(arm_list), "jobs": jobs}) for arm in arm_list: print(f'{arm["label"]}: {arm["kind"]} {arm["sha"]}') print(off_main(pull_requests, branches), end="") - print(f"{len(jobs)} job(s), {len(keys)} model(s), {rounds} round(s); nothing has run yet") + print(f"backend {backend}: {len(jobs)} job(s), {len(keys)} model(s), {rounds} round(s); nothing has run yet") def resource_id(identifier): @@ -183,7 +185,8 @@ def collect(pilot, job, plan, label, evidence): encoding="utf-8") if plan["trace"]: download(pilot, run_id, "traces.tar.gz", evidence / f"{label}-traces.tar.gz") - host = f'{result["host"]["chip"]} ({result["host"].get("node") or "unknown node"})' + host = f'{result["host"].get("gpu") or result["host"].get("chip") or "unknown device"}' \ + f' ({result["host"].get("node") or "unknown node"})' return markdown(f"Inference performance: {label}", host, summarize(result["samples"]), result) @@ -229,18 +232,25 @@ def native_plan(): raise ValueError("harness checkout differs from the admitted harness commit") labels = {arm["label"]: arm["sha"] for arm in plan["arms"]} expected = arms(labels["candidate"], labels["baseline"], labels.get("reference")) + if plan.get("backend") not in BACKENDS: + raise ValueError(f'performance plan backend {plan.get("backend")!r} has no entry in the table') if (plan["arms"] != expected or plan["models"] != models(plan["models"]) or type(plan.get("trace")) is not bool): raise ValueError("performance plan arms, models or trace flag are malformed") return plan +def toolcheck(): + """The backend's tool check, before any build spends an hour on a host without its tools.""" + command(BACKENDS[native_plan()["backend"]]["tool_check"], timeout=120, capture_stdout=True) + + def build_arms(): plan = native_plan() - inference_metal.chip() WORK.mkdir(parents=True, exist_ok=True) try: - write_json(BUILT, [build(arm, WORK / f'build-{arm["label"]}.log') for arm in plan["arms"]]) + write_json(BUILT, [build(arm, WORK / f'build-{arm["label"]}.log', plan["backend"]) + for arm in plan["arms"]]) finally: # execute() is the only other place build logs reach the artifact # directory, and it never runs after a build failure. @@ -275,7 +285,8 @@ def traced(built, help_text, args, applied, missing, trace): "SKIPPY_TELEMETRY_OTLP_METRICS_FILE": str(trace.parent / f"{trace.name}.metrics.jsonl")} -def measure(built, help_text, model, inputs, key, index, server, shape, output, trace=None): +def measure(built, help_text, model, inputs, key, index, server, shape, output, trace=None, + prefixes=("MTL",)): """`index` is the round, or None for a diagnostic pass that writes `trace`.""" coordinate = f'{inputs["repo"]}@{inputs["revision"]}' args, applied, missing = server_args(built, help_text, model, coordinate, @@ -289,7 +300,7 @@ def measure(built, help_text, model, inputs, key, index, server, shape, output, process = start(args, overrides, stdin=subprocess.DEVNULL, stdout=stream, stderr=stream) try: ready(process, 900) - offload(log) + offload(log, prefixes) for point in server["points"]: metrics, rejected = run_point(ENDPOINT, point, coordinate, inputs["tokenizer_path"], shape["warmup_requests"], WORK / "aiperf" / name / point["id"], @@ -309,8 +320,8 @@ def measure(built, help_text, model, inputs, key, index, server, shape, output, def execute(): if os.geteuid() == 0: raise ValueError("native inference must not execute as root") - plan, chip = native_plan(), inference_metal.chip() - working_set = inference_metal.working_set(chip) + plan = native_plan() + entry = BACKENDS[plan["backend"]] built = read_json(BUILT) if [(entry["label"], entry["sha"]) for entry in built] != [(arm["label"], arm["sha"]) for arm in plan["arms"]]: raise ValueError("built arms differ from the admitted plan") @@ -324,8 +335,8 @@ def execute(): shape, helps = scenario(), {entry["label"]: capabilities(entry) for entry in built} record = {"schema_version": 1, "harness": plan["harness"], "scenario_sha256": digest(SCENARIO), "started_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), - "host": {"chip": chip, "macos": capture(["sw_vers", "-productVersion"]).strip(), - "metal_working_set_bytes": working_set, "node": os.environ.get("JIANYANG_NODE")}, + "host": {"node": os.environ.get("JIANYANG_NODE"), "backend": plan["backend"], + **entry["facts"]()}, "arms": built, "rounds": plan["rounds"], "models": {}, "samples": []} if plan["trace"]: # Tracing slows the arm it runs on, so its samples never join the comparison. @@ -334,25 +345,27 @@ def execute(): try: for key in plan["models"]: inputs = fixture(key) - available = inference_metal.available_memory(capture(["vm_stat"]), working_set) - if available < sum(file["size"] for file in inputs["files"]) + RESERVE: - raise ValueError(f"{key}: insufficient Metal working set or free memory for weights and reserve") + available = entry["free_memory"](record["host"]) + reserve = entry["reserve_gib"] * 1024**3 + if available < sum(file["size"] for file in inputs["files"]) + reserve: + raise ValueError(f"{key}: insufficient {plan['backend']} free memory for weights and reserve") model = admit_model(key, inputs) inputs = {**inputs, "tokenizer_path": tokenizer(inputs)} record["models"][key] = {"repo": inputs["repo"], "revision": inputs["revision"], "files": inputs["files"]} for index in range(plan["rounds"]): - for entry in round_order(built, index): + for arm in round_order(built, index): for server in shape["servers"]: - record["samples"] += measure(entry, helps[entry["label"]], model, inputs, key, - index, server, shape, output) + record["samples"] += measure(arm, helps[arm["label"]], model, inputs, key, + index, server, shape, output, + prefixes=entry["device_prefixes"]) write_json(output / "performance.json", record) if plan["trace"]: - candidate = next(entry for entry in built if entry["label"] == "candidate") + candidate = next(arm for arm in built if arm["label"] == "candidate") for server in shape["servers"]: record["diagnostic"]["samples"] += measure( candidate, helps["candidate"], model, inputs, key, None, server, shape, output, - trace=TRACES / f'{key}-{server["id"]}') + trace=TRACES / f'{key}-{server["id"]}', prefixes=entry["device_prefixes"]) write_json(output / "performance.json", record) finally: write_json(output / "performance.json", record) @@ -370,6 +383,7 @@ def main(): for name in ("admit", "dispatch"): actions.add_parser(name).add_argument("evidence", type=Path) actions.add_parser("cancel").add_argument("ledger", type=Path) + actions.add_parser("toolcheck") actions.add_parser("build") actions.add_parser("execute") args = parser.parse_args() @@ -379,6 +393,8 @@ def main(): dispatch(args.evidence) elif args.action == "cancel": cancel(Pilot(), args.ledger) + elif args.action == "toolcheck": + toolcheck() elif args.action == "build": build_arms() else: diff --git a/scripts/lib/inference_checks.py b/scripts/lib/inference_checks.py index 711fa1f9..15ef45c8 100644 --- a/scripts/lib/inference_checks.py +++ b/scripts/lib/inference_checks.py @@ -32,16 +32,17 @@ def numerical(model, coordinate, fixture, output): command(args, timeout=1800, overrides={"CUDA_VISIBLE_DEVICES": ""}) -def offload(log): +def offload(log, prefixes=("MTL",)): + devices = "|".join(prefixes) with log.open(encoding="utf-8") as stream: for line in stream: match = re.search(r"offloaded ([0-9]+)/[^\n]*GPU", line) if match and int(match[1]) > 0: return # Skippy's structured status log does not forward llama.cpp's - # offload line; a Metal backend device selection is its GPU - # evidence, with the harness having applied --n-gpu-layers. - if '"type":"backend_device_selected"' in line and re.search(r'"detail":"MTL', line): + # offload line; a backend device selection is its GPU evidence, + # with the harness having applied --n-gpu-layers. + if '"type":"backend_device_selected"' in line and re.search(rf'"detail":"(?:{devices})', line): return raise ValueError("server log has no positive GPU-layer offload evidence") diff --git a/scripts/lib/performance_arms.py b/scripts/lib/performance_arms.py index fa208c53..6d1cb7c7 100644 --- a/scripts/lib/performance_arms.py +++ b/scripts/lib/performance_arms.py @@ -5,14 +5,17 @@ from .ci_artifacts import digest from .ci_process import capture, command +from .performance_backends import BACKENDS +from .performance_plan import ROOT PORT = 9337 REQUIRED = ("--startup-timeout-secs", "--bind-addr", "--model-id", "--ctx-size", "--n-gpu-layers", "--model-path") -METAL = {"LLAMA_STAGE_BACKEND": "metal", "LLAMA_STAGE_LINK_MODE": "static"} # llama.cpp files its library's INFO lines under trace, and the offload line the # startup check reads is one of them. REFERENCE_VERBOSITY = 4 +TOOLKIT_ENV = ("PATH", "CUDACXX", "NVCC", "CUDAToolkit_ROOT", "CUDA_HOME", "CUDA_PATH", + "CUDA_LIBRARY_PATH", "LIBRARY_PATH", "LD_LIBRARY_PATH") def checkout(arm): @@ -23,24 +26,40 @@ def checkout(arm): return path.resolve() -def build(arm, log): +def toolkit_overrides(script): + """The toolkit environment Skippy's own build exports, so the reference arm configures + the same native toolkit rather than whatever an unpackaged CMake happens to find.""" + text = capture(["bash", "-c", f'source "{script}" && configure_cuda_toolkit_env && env -0']) + found = {key: value for item in text.split("\0") if "=" in item + for key, value in (item.split("=", 1),) if key in TOOLKIT_ENV} + if not found: + raise ValueError("the native toolkit environment did not resolve; the reference build cannot find it") + return found + + +def build(arm, log, backend="metal"): """Every arm is a release build: the comparison measures what ships, not a debug harness.""" + entry = BACKENDS[backend] path = checkout(arm) with log.open("wb") as stream: if arm["kind"] == "skippy": - command(["just", "llama-build"], timeout=7200, overrides=METAL, cwd=path, + command(["just", "llama-build"], timeout=7200, overrides=entry["skippy_env"], cwd=path, stdout=stream, stderr=stream) command(["cargo", "build", "--locked", "--release", "-p", "skippy-cli"], timeout=7200, - overrides=METAL, cwd=path, stdout=stream, stderr=stream) + overrides=entry["skippy_env"], cwd=path, stdout=stream, stderr=stream) binary = path / "target/release/skippy" else: + overrides = None + if entry["toolkit_script"]: + overrides = toolkit_overrides(ROOT / entry["toolkit_script"]) build_dir = path / "build" command(["cmake", "-S", str(path), "-B", str(build_dir), "-G", "Ninja", - "-DCMAKE_BUILD_TYPE=Release", "-DGGML_METAL=ON", "-DLLAMA_BUILD_TESTS=OFF", + "-DCMAKE_BUILD_TYPE=Release", *entry["reference_cmake"], + "-DLLAMA_BUILD_TESTS=OFF", "-DLLAMA_BUILD_EXAMPLES=OFF", "-DLLAMA_BUILD_SERVER=ON"], timeout=1800, - cwd=path, stdout=stream, stderr=stream) + cwd=path, overrides=overrides, stdout=stream, stderr=stream) command(["cmake", "--build", str(build_dir), "--target", "llama-server", "--parallel"], - timeout=7200, cwd=path, stdout=stream, stderr=stream) + timeout=7200, cwd=path, overrides=overrides, stdout=stream, stderr=stream) binary = build_dir / "bin/llama-server" return {"label": arm["label"], "kind": arm["kind"], "sha": arm["sha"], "binary": str(binary), "binary_sha256": digest(binary)} diff --git a/scripts/lib/performance_backends.py b/scripts/lib/performance_backends.py new file mode 100644 index 00000000..9e617aeb --- /dev/null +++ b/scripts/lib/performance_backends.py @@ -0,0 +1,99 @@ +"""One closed table of the backends a performance comparison can run on. + +An entry holds everything backend-specific: the selector fragment of the JY target, the +Skippy build overrides, the reference build's accelerator CMake flags, the tool check that +runs before any build, the script that resolves a native toolkit when the reference build +needs one, the device prefixes that count as GPU offload evidence, and the functions that +prove the host and measure its free memory. `admit` refuses a `BACKEND` with no entry and +records the one it accepts in the plan; build and execute read the backend from the plan +and never infer it from the host, so a job always measures the machine it was planned for. +A backend without a complete entry therefore fails at plan time, not partway through a job. +""" + +import platform +from pathlib import Path + +from . import inference_metal +from .ci_process import capture + + +def linux_release(): + for line in Path("/etc/os-release").read_text(encoding="utf-8").splitlines(): + if line.startswith("PRETTY_NAME="): + return line.split("=", 1)[1].strip('"') + return "" + + +def metal_facts(): + chip = inference_metal.chip() + return {"chip": chip, "macos": capture(["sw_vers", "-productVersion"]).strip(), + "metal_working_set_bytes": inference_metal.working_set(chip)} + + +def metal_free(host): + return inference_metal.available_memory(capture(["vm_stat"]), host["metal_working_set_bytes"]) + + +def cuda_facts(): + """A Linux aarch64 host with an NVIDIA GB10, proved the way qualification's authority proves it.""" + if platform.system() != "Linux" or platform.machine() != "aarch64": + raise ValueError("the cuda backend requires Linux aarch64 (a DGX Spark)") + gpu = capture(["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"]).strip() + if "GB10" not in gpu: + raise ValueError(f"the cuda backend requires an NVIDIA GB10, not {gpu!r}") + driver = capture(["nvidia-smi", "--query-gpu=driver_version", "--format=csv,noheader"]).strip() + cuda = "" + for line in capture(["nvidia-smi", "--version"]).splitlines(): + if "CUDA Version" in line: + cuda = line.split(":", 1)[1].strip() + break + return {"gpu": gpu, "driver_version": driver, "toolkit_version": cuda or None, + "os": "linux", "os_version": linux_release(), "kernel": capture(["uname", "-r"]).strip()} + + +def cuda_free(host): + """Unified memory: everything the kernel will hand out is what a model competes for.""" + for line in Path("/proc/meminfo").read_text(encoding="utf-8").splitlines(): + if line.startswith("MemAvailable:"): + return int(line.split()[1]) * 1024 + raise ValueError("MemAvailable missing") + + +# The unified reserve, shared system memory for everything beside the weights. +RESERVE_GIB = 16 + +BACKENDS = { + "metal": { + "description": "Same-host Metal comparison", + "selector": {"os": {"family": "macos"}, "accelerator": {"backend": "metal"}}, + "memory_key": "system_gib", + "reserve_gib": RESERVE_GIB, + "pin_required": False, + "skippy_env": {"LLAMA_STAGE_BACKEND": "metal", "LLAMA_STAGE_LINK_MODE": "static"}, + "reference_cmake": ["-DGGML_METAL=ON"], + "tool_check": ["xcrun", "--find", "swift"], + "toolkit_script": None, + "device_prefixes": ("MTL",), + "facts": metal_facts, + "free_memory": metal_free, + "env": {}, + }, + "cuda": { + "description": "Same-host CUDA comparison", + "selector": {"os": {"family": "linux"}, "arch": {"in": ["aarch64"]}, + "accelerator": {"backend": "cuda", "model": {"in": ["NVIDIA GB10"]}}, + "memory": {"unified": True}}, + "memory_key": "system_gib", + "reserve_gib": RESERVE_GIB, + "pin_required": False, + "skippy_env": {"LLAMA_STAGE_BACKEND": "cuda", "LLAMA_STAGE_LINK_MODE": "static", + "LLAMA_STAGE_CUDA_ARCHITECTURES": "121"}, + "reference_cmake": ["-DGGML_CUDA=ON", "-DCMAKE_CUDA_ARCHITECTURES=121"], + "tool_check": ["nvidia-smi"], + "toolkit_script": "scripts/lib/cuda-toolkit.sh", + "device_prefixes": ("CUDA",), + "facts": cuda_facts, + "free_memory": cuda_free, + "env": {}, + }, +} diff --git a/scripts/lib/performance_plan.py b/scripts/lib/performance_plan.py index 7f5fc043..00903ee5 100644 --- a/scripts/lib/performance_plan.py +++ b/scripts/lib/performance_plan.py @@ -8,6 +8,7 @@ from .ci_artifacts import digest, read_json from .inference_inputs import fixture from .inference_ladder import ladder_models +from .performance_backends import BACKENDS ROOT = Path(__file__).resolve().parents[2] SCENARIO = ROOT / "ci/inference-performance.json" @@ -17,7 +18,6 @@ PULL_REQUEST = re.compile(r"pr:([1-9][0-9]{0,6})") BRANCH = re.compile(r"branch:([A-Za-z0-9._/-]{1,200})") NODE = re.compile(r"[A-Za-z0-9._-]{1,64}") -RESERVE_GIB = 16 MAX_ROUNDS = 9 POINT_FIELDS = {"id", "concurrency", "depth", "input_tokens", "output_tokens", "requests"} @@ -104,18 +104,13 @@ def models(keys): return keys -def memory_floor(keys): - largest = max(sum(file["size"] for file in fixture(key)["files"]) for key in keys) - return math.ceil(largest / 1024**3) + RESERVE_GIB - - def nodes(values): if len(set(values)) != len(values) or not all(NODE.fullmatch(value) for value in values): raise ValueError("nodes must be distinct JY node names") return values -def job_spec(harness, arm_list, keys, rounds, node, label, *, trace=False): +def job_spec(harness, arm_list, keys, rounds, node, label, *, trace=False, backend="metal"): """`trace` adds one diagnostic pass of the candidate with debug telemetry, kept out of the measurements: tracing costs time, so a traced arm is not a comparable one.""" count(rounds, "rounds") @@ -123,20 +118,28 @@ def job_spec(harness, arm_list, keys, rounds, node, label, *, trace=False): raise ValueError("trace must be true or false") if rounds > MAX_ROUNDS: raise ValueError(f"at most {MAX_ROUNDS} rounds fit the job's time budget") + if backend not in BACKENDS: + raise ValueError(f"unknown backend {backend!r}; the table holds {', '.join(sorted(BACKENDS))}") shape = scenario() - target = {"executor": "lab", "num_nodes": 1, "selector": { - "os": {"family": "macos"}, "accelerator": {"backend": "metal"}, - "memory": {"system_gib": {"min": memory_floor(keys)}}}} + entry = BACKENDS[backend] + if entry["pin_required"] and node is None: + raise ValueError(f"a {backend} plan must name exactly one node: its GPUs differ between hosts") + largest = max(sum(file["size"] for file in fixture(key)["files"]) for key in keys) + selector = {key: value for key, value in entry["selector"].items() if key != "memory"} + selector["memory"] = {entry["memory_key"]: {"min": math.ceil(largest / 1024**3) + entry["reserve_gib"]}, + **entry["selector"].get("memory", {})} + target = {"executor": "lab", "num_nodes": 1, "selector": selector} if node is not None: target["nodes"] = [node] repos = [{"url": SKIPPY, "rev": harness, "path": "harness"}] + [ {"url": SKIPPY if arm["kind"] == "skippy" else LLAMA, "rev": arm["sha"], "path": arm["path"]} for arm in arm_list] - plan = {"harness": harness, "arms": arm_list, "models": keys, "rounds": rounds, "trace": trace} + plan = {"harness": harness, "backend": backend, "arms": arm_list, "models": keys, + "rounds": rounds, "trace": trace} points = [point for server in shape["servers"] for point in server["points"]] return { "name": f"skippy-inference-performance-{label}", - "description": "Same-host Metal comparison of " + ", ".join( + "description": entry["description"] + " of " + ", ".join( f'{arm["label"]} {arm["sha"][:12]}' for arm in arm_list) + f" on {', '.join(keys)}.", "priority": 50, "target": target, @@ -145,7 +148,8 @@ def job_spec(harness, arm_list, keys, rounds, node, label, *, trace=False): "sha256": fixture(keys[0])["files"][0]["sha256"], "egress": "lab_only"}, "workspace": {"repos": repos, "build": "cd harness && just inference-performance-build", "retain": "on_failure"}, - "env": {"SKIPPY_PERFORMANCE_PLAN": json.dumps(plan, separators=(",", ":"))}, + "env": {"SKIPPY_PERFORMANCE_PLAN": json.dumps(plan, separators=(",", ":")), + **entry["env"]}, "command": "cd harness && just inference-performance-execute", }, "harness": { diff --git a/scripts/lib/performance_report.py b/scripts/lib/performance_report.py index 37c597e7..99408362 100644 --- a/scripts/lib/performance_report.py +++ b/scripts/lib/performance_report.py @@ -74,7 +74,8 @@ def report_view(host, rows, record): key = row["model"], row["server"], row["point"] configuration = configurations.setdefault(key, { "id": "/".join(key), "label": " · ".join(key), "group": host, - "workload": f'Controlled Metal · {host} · {row["server"]} · {row["point"]}', + "workload": f'Controlled {((record.get("host") or {}).get("backend") or "metal")} · {host}' + f' · {row["server"]} · {row["point"]}', "outcome": "passed", "metrics": [], }) arms = row["arms"] @@ -131,9 +132,12 @@ def rows(record, shape, committed_at, job, pull_requests, branches=None): branch = (branches or {}).get(sample["arm"]) server, point = points[(sample["server"], sample["point"])] yield { - "schema_version": 1, "job": job, "started_at": record.get("started_at"), + "schema_version": 2, "job": job, "started_at": record.get("started_at"), "harness": record["harness"], "scenario_sha256": record["scenario_sha256"], - "chip": host["chip"], "macos": host.get("macos"), "node": host.get("node"), + "backend": host.get("backend"), "gpu": host.get("gpu"), "chip": host.get("chip"), + "macos": host.get("macos"), "os": host.get("os"), "os_version": host.get("os_version"), + "kernel": host.get("kernel"), "driver_version": host.get("driver_version"), + "toolkit_version": host.get("toolkit_version"), "node": host.get("node"), "metal_working_set_bytes": host.get("metal_working_set_bytes"), "arm": sample["arm"], "kind": arm["kind"], "sha": arm["sha"], "committed_at": committed_at.get(arm["sha"]), "binary_sha256": arm["binary_sha256"], diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index e0bfcdff..a3bf55a7 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -4,9 +4,10 @@ import unittest from pathlib import Path from runpy import run_path +from tempfile import TemporaryDirectory from unittest.mock import Mock, patch -from lib import performance_plan +from lib import performance_arms, performance_plan from lib.performance_arms import REQUIRED, capabilities, may_reject, server_args from lib.performance_load import measurements, rejection, run_point from lib import performance_report @@ -114,6 +115,26 @@ def test_job_runs_every_arm_from_its_own_checkout_on_a_metal_host(self): with self.assertRaises(ValueError): performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], performance_plan.MAX_ROUNDS + 1, None, "x") + def test_a_cuda_plan_targets_a_dgx_spark(self): + arm_list = performance_plan.arms(self.candidate, self.baseline, self.pin) + spec = performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 3, "spark-000137", "sp", + backend="cuda") + selector = spec["target"]["selector"] + self.assertEqual(selector["os"], {"family": "linux"}) + self.assertEqual(selector["arch"], {"in": ["aarch64"]}) + self.assertEqual(selector["accelerator"], {"backend": "cuda", "model": {"in": ["NVIDIA GB10"]}}) + self.assertIs(selector["memory"]["unified"], True) + self.assertGreaterEqual(selector["memory"]["system_gib"]["min"], 18) + self.assertEqual(spec["target"]["nodes"], ["spark-000137"]) + self.assertIn("Same-host CUDA comparison", spec["description"]) + self.assertEqual(json.loads(spec["runtime"]["env"]["SKIPPY_PERFORMANCE_PLAN"])["backend"], "cuda") + + def test_an_unknown_backend_is_refused_at_plan_time(self): + arm_list = performance_plan.arms(self.candidate, self.baseline, self.pin) + with self.assertRaisesRegex(ValueError, "unknown backend"): + performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 3, None, "any", + backend="space-heater") + def test_models_must_be_ladder_ids(self): with self.assertRaises(ValueError): performance_plan.models(["qwen35-4b", "qwen35-4b"]) @@ -202,6 +223,45 @@ def test_only_llama_server_may_reject_a_point_and_only_past_its_pool(self): self.assertFalse(any(may_reject(self.skippy, server, point) for server, point in cells)) +class BackendTests(unittest.TestCase): + """The backend table drives every arm's build; one entry changes no other entry's commands.""" + skippy = {"label": "candidate", "kind": "skippy", "sha": "a" * 40, "path": "candidate"} + reference = {"label": "reference", "kind": "llama-server", "sha": "c" * 40, "path": "reference"} + + def build(self, arm, backend): + calls = [] + with TemporaryDirectory() as directory: + with patch("lib.performance_arms.checkout", return_value=Path(directory)), \ + patch("lib.performance_arms.command", + side_effect=lambda args, **kwargs: calls.append((args, kwargs)) or None), \ + patch("lib.performance_arms.toolkit_overrides", return_value={"CUDACXX": "/c/bin/nvcc"}), \ + patch("lib.performance_arms.digest", return_value="0" * 64): + built = performance_arms.build(arm, Path(directory) / "build.log", backend) + return calls, built + + def test_the_cuda_entry_builds_both_arms_for_a_gb10(self): + calls, _ = self.build(self.skippy, "cuda") + just, cargo = calls[0], calls[1] + self.assertEqual(just[0][:2], ["just", "llama-build"]) + self.assertEqual((just[1]["overrides"]["LLAMA_STAGE_BACKEND"], just[1]["overrides"]["LLAMA_STAGE_LINK_MODE"], + just[1]["overrides"]["LLAMA_STAGE_CUDA_ARCHITECTURES"]), ("cuda", "static", "121")) + self.assertEqual(cargo[0][:3], ["cargo", "build", "--locked"]) + self.assertEqual(cargo[1]["overrides"], just[1]["overrides"]) + calls, _ = self.build(self.reference, "cuda") + configure, make = calls[0], calls[1] + self.assertIn("-DGGML_CUDA=ON", configure[0]) + self.assertIn("-DCMAKE_CUDA_ARCHITECTURES=121", configure[0]) + self.assertNotIn("-DGGML_METAL=ON", configure[0]) + self.assertEqual(configure[1]["overrides"], {"CUDACXX": "/c/bin/nvcc"}) + self.assertEqual(make[1]["overrides"], {"CUDACXX": "/c/bin/nvcc"}) + + def test_the_metal_entry_builds_the_reference_without_a_toolkit_environment(self): + calls, _ = self.build(self.reference, "metal") + self.assertIn("-DGGML_METAL=ON", calls[0][0]) + self.assertNotIn("-DGGML_CUDA=ON", calls[0][0]) + self.assertIsNone(calls[0][1]["overrides"]) + + class RejectionTests(unittest.TestCase): point = {"id": "c4-depth4096-pool16k", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 4} From 15ba179e1482fbff89f0eb9f9129323f7f2f29d2 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Wed, 25 Nov 2026 15:48:22 +1100 Subject: [PATCH 05/50] feat(ci): add a cuda-x86 performance backend for discrete GPUs --- ci/INFERENCE_PERFORMANCE.md | 26 ++++++- scripts/lib/performance_arms.py | 21 ++++-- scripts/lib/performance_backends.py | 75 +++++++++++++++++++ .../tests/inference_performance_contracts.py | 44 ++++++++++- 4 files changed, 156 insertions(+), 10 deletions(-) diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index a3a6ef4d..f5700e4b 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -38,11 +38,29 @@ reference build when it needs one, the device prefixes that count as GPU offload and the functions that prove the host and measure its free memory. A backend without a complete entry fails at plan time, not partway through a job. -The table holds `metal` (any Apple M-series Mac whose Metal device is its own GPU) and +The table holds `metal` (any Apple M-series Mac whose Metal device is its own GPU), `cuda` (a DGX Spark: Linux aarch64, an NVIDIA GB10, unified memory, CUDA architecture -121). The Spark's reference arm builds with `-DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=121`, -configuring with the same toolkit environment `scripts/lib/cuda-toolkit.sh` resolves for -Skippy's build. The GitHub workflow still dispatches Metal only. +121) and `cuda-x86` (a discrete NVIDIA GPU on Linux x86_64). The Spark's reference arm +builds with `-DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=121`, configuring with the same +toolkit environment `scripts/lib/cuda-toolkit.sh` resolves for Skippy's build. The +GitHub workflow still dispatches Metal only. + +`cuda-x86` differs from the Spark in four ways, all in its table entry: + +- **Pinned to one node.** x86 hosts carry different cards, so an unpinned `cuda-x86` + plan is refused at plan time; a result is only comparable on the card it was measured on. +- **One GPU.** The job environment sets `CUDA_VISIBLE_DEVICES=0`, so both arms see the + same single GPU; the host record says how many GPUs the host has and that GPU 0 was used. +- **The host's own architecture.** Both arms read GPU 0's compute capability at build time + (`nvidia-smi --query-gpu=compute_cap`, 8.9 meaning 89) and build for it, not the release + lists from `ci/targets.json`. The architecture is recorded in the evidence. +- **Discrete memory.** Admission checks the weights plus a 6 GiB discrete reserve against + GPU 0's free VRAM and against system `MemAvailable`, since Skippy can hold KV in host + RAM. The reserve is not the unified 16 GiB: a discrete GPU runs no operating system + beside the model, so the reserve covers only the KV pools and recurrent state of the + deepest cells (3.0 GiB and 0.94 GiB for the largest full-attention and hybrid models at + a 32K pool and 16 lanes) plus both arms' compute buffers. The host record also lists any + other compute process already on GPU 0. Both commits must be on protected main, unless an arm is `pr:N`: the head of an open pull request from this repository, never a fork's, authored by a collaborator with write access, so only code that could diff --git a/scripts/lib/performance_arms.py b/scripts/lib/performance_arms.py index 6d1cb7c7..ba6ac314 100644 --- a/scripts/lib/performance_arms.py +++ b/scripts/lib/performance_arms.py @@ -37,16 +37,23 @@ def toolkit_overrides(script): return found +def resolve_setting(entry, key): + """A table value, or a callable the host resolves at build time, such as a GPU architecture.""" + value = entry[key] + return value() if callable(value) else value + + def build(arm, log, backend="metal"): """Every arm is a release build: the comparison measures what ships, not a debug harness.""" entry = BACKENDS[backend] + skippy_env = resolve_setting(entry, "skippy_env") path = checkout(arm) with log.open("wb") as stream: if arm["kind"] == "skippy": - command(["just", "llama-build"], timeout=7200, overrides=entry["skippy_env"], cwd=path, + command(["just", "llama-build"], timeout=7200, overrides=skippy_env, cwd=path, stdout=stream, stderr=stream) command(["cargo", "build", "--locked", "--release", "-p", "skippy-cli"], timeout=7200, - overrides=entry["skippy_env"], cwd=path, stdout=stream, stderr=stream) + overrides=skippy_env, cwd=path, stdout=stream, stderr=stream) binary = path / "target/release/skippy" else: overrides = None @@ -54,15 +61,19 @@ def build(arm, log, backend="metal"): overrides = toolkit_overrides(ROOT / entry["toolkit_script"]) build_dir = path / "build" command(["cmake", "-S", str(path), "-B", str(build_dir), "-G", "Ninja", - "-DCMAKE_BUILD_TYPE=Release", *entry["reference_cmake"], + "-DCMAKE_BUILD_TYPE=Release", *resolve_setting(entry, "reference_cmake"), "-DLLAMA_BUILD_TESTS=OFF", "-DLLAMA_BUILD_EXAMPLES=OFF", "-DLLAMA_BUILD_SERVER=ON"], timeout=1800, cwd=path, overrides=overrides, stdout=stream, stderr=stream) command(["cmake", "--build", str(build_dir), "--target", "llama-server", "--parallel"], timeout=7200, cwd=path, overrides=overrides, stdout=stream, stderr=stream) binary = build_dir / "bin/llama-server" - return {"label": arm["label"], "kind": arm["kind"], "sha": arm["sha"], "binary": str(binary), - "binary_sha256": digest(binary)} + built = {"label": arm["label"], "kind": arm["kind"], "sha": arm["sha"], "binary": str(binary), + "binary_sha256": digest(binary)} + architecture = skippy_env.get("LLAMA_STAGE_CUDA_ARCHITECTURES") + if architecture: + built["gpu_architecture"] = architecture + return built def capabilities(built): diff --git a/scripts/lib/performance_backends.py b/scripts/lib/performance_backends.py index 9e617aeb..f3575b32 100644 --- a/scripts/lib/performance_backends.py +++ b/scripts/lib/performance_backends.py @@ -11,6 +11,7 @@ """ import platform +import re from pathlib import Path from . import inference_metal @@ -59,6 +60,61 @@ def cuda_free(host): raise ValueError("MemAvailable missing") +# A discrete GPU runs no operating system beside the model, so its reserve covers only the +# KV pools and recurrent state of the deepest cells and both arms' compute buffers, not +# the unified 16 GiB. Sized in the cuda-x86 platform's step 3; see INFERENCE_PERFORMANCE.md. +DISCRETE_RESERVE_GIB = 6 + + +def cuda_x86_architecture(): + """The host GPU's compute capability, read at build time: 8.9 means architecture 89.""" + capability = capture(["nvidia-smi", "--query-gpu=compute_cap", "--format=csv,noheader", + "-i", "0"]).strip() + if not re.fullmatch(r"[0-9]+\.[0-9]", capability): + raise ValueError(f"GPU 0 reported no compute capability: {capability!r}") + return capability.replace(".", "") + + +def cuda_x86_skippy_env(): + return {"LLAMA_STAGE_BACKEND": "cuda", "LLAMA_STAGE_LINK_MODE": "static", + "LLAMA_STAGE_CUDA_ARCHITECTURES": cuda_x86_architecture()} + + +def cuda_x86_reference_cmake(): + return ["-DGGML_CUDA=ON", f"-DCMAKE_CUDA_ARCHITECTURES={cuda_x86_architecture()}"] + + +def cuda_x86_facts(): + """A discrete-NVIDIA Linux x86_64 host, described by GPU 0: the one the job pins.""" + if platform.system() != "Linux" or platform.machine() != "x86_64": + raise ValueError("the cuda-x86 backend requires Linux x86_64") + row = capture(["nvidia-smi", "--query-gpu=name,driver_version,compute_cap,memory.total," + "memory.free,count", "--format=csv,noheader,nounits", "-i", "0"]).strip() + fields = [item.strip() for item in row.split(",")] + if len(fields) != 6: + raise ValueError(f"nvidia-smi did not describe GPU 0: {row!r}") + name, driver, capability, total_mib, free_mib, count = fields + cuda = "" + for line in capture(["nvidia-smi", "--version"]).splitlines(): + if "CUDA Version" in line: + cuda = line.split(":", 1)[1].strip() + break + processes = capture(["nvidia-smi", "--query-compute-apps=pid,process_name,used_memory", + "--format=csv", "-i", "0"]).strip() + return {"gpu": name, "gpu_count": int(count), "gpu_used": 0, + "gpu_compute_capability": capability, + "gpu_memory_total_bytes": int(total_mib) * 1024**2, + "gpu_memory_free_bytes": int(free_mib) * 1024**2, + "driver_version": driver, "toolkit_version": cuda or None, + "os": "linux", "os_version": linux_release(), "kernel": capture(["uname", "-r"]).strip(), + "gpu_processes": processes or None} + + +def cuda_x86_free(host): + """The weights must fit GPU 0's own free VRAM, and Skippy may also hold KV in host RAM.""" + return min(host["gpu_memory_free_bytes"], cuda_free(host)) + + # The unified reserve, shared system memory for everything beside the weights. RESERVE_GIB = 16 @@ -96,4 +152,23 @@ def cuda_free(host): "free_memory": cuda_free, "env": {}, }, + # A discrete NVIDIA GPU on Linux x86_64. x86 hosts carry different cards, so a plan + # must name one node, both arms build for that card's own architecture, and the job + # pins GPU 0 with CUDA_VISIBLE_DEVICES. Admission is against GPU 0's free VRAM. + "cuda-x86": { + "description": "Same-host CUDA comparison", + "selector": {"os": {"family": "linux"}, "arch": {"in": ["x86_64"]}, + "accelerator": {"backend": "cuda"}, "memory": {"unified": False}}, + "memory_key": "dedicated_vram_gib", + "reserve_gib": DISCRETE_RESERVE_GIB, + "pin_required": True, + "skippy_env": cuda_x86_skippy_env, + "reference_cmake": cuda_x86_reference_cmake, + "tool_check": ["nvidia-smi"], + "toolkit_script": "scripts/lib/cuda-toolkit.sh", + "device_prefixes": ("CUDA",), + "facts": cuda_x86_facts, + "free_memory": cuda_x86_free, + "env": {"CUDA_VISIBLE_DEVICES": "0"}, + }, } diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index a3bf55a7..edb48360 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -7,7 +7,7 @@ from tempfile import TemporaryDirectory from unittest.mock import Mock, patch -from lib import performance_arms, performance_plan +from lib import performance_arms, performance_backends, performance_plan from lib.performance_arms import REQUIRED, capabilities, may_reject, server_args from lib.performance_load import measurements, rejection, run_point from lib import performance_report @@ -135,6 +135,22 @@ def test_an_unknown_backend_is_refused_at_plan_time(self): performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 3, None, "any", backend="space-heater") + def test_a_cuda_x86_plan_targets_one_pinned_discrete_gpu(self): + arm_list = performance_plan.arms(self.candidate, self.baseline, self.pin) + with self.assertRaisesRegex(ValueError, "must name exactly one node"): + performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 3, None, "any", + backend="cuda-x86") + spec = performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 3, "lab-a33338", "x", + backend="cuda-x86") + selector = spec["target"]["selector"] + self.assertEqual(selector["os"], {"family": "linux"}) + self.assertEqual(selector["arch"], {"in": ["x86_64"]}) + self.assertEqual(selector["accelerator"], {"backend": "cuda"}) + self.assertIs(selector["memory"]["unified"], False) + self.assertGreaterEqual(selector["memory"]["dedicated_vram_gib"]["min"], 9) + self.assertEqual(spec["target"]["nodes"], ["lab-a33338"]) + self.assertEqual(spec["runtime"]["env"].get("CUDA_VISIBLE_DEVICES"), "0") + def test_models_must_be_ladder_ids(self): with self.assertRaises(ValueError): performance_plan.models(["qwen35-4b", "qwen35-4b"]) @@ -261,6 +277,32 @@ def test_the_metal_entry_builds_the_reference_without_a_toolkit_environment(self self.assertNotIn("-DGGML_CUDA=ON", calls[0][0]) self.assertIsNone(calls[0][1]["overrides"]) + def test_the_cuda_x86_entry_builds_for_the_hosts_own_architecture(self): + calls = [] + with patch("lib.performance_backends.cuda_x86_architecture", return_value="89"): + with TemporaryDirectory() as directory: + with patch("lib.performance_arms.checkout", return_value=Path(directory)), \ + patch("lib.performance_arms.command", + side_effect=lambda args, **kwargs: calls.append((args, kwargs)) or None), \ + patch("lib.performance_arms.toolkit_overrides", + return_value={"CUDACXX": "/c/bin/nvcc"}), \ + patch("lib.performance_arms.digest", return_value="0" * 64): + built = performance_arms.build(self.skippy, Path(directory) / "b.log", "cuda-x86") + self.assertEqual(calls[0][1]["overrides"]["LLAMA_STAGE_CUDA_ARCHITECTURES"], "89") + self.assertEqual(built["gpu_architecture"], "89") + del calls[:] + built = performance_arms.build(self.reference, Path(directory) / "r.log", "cuda-x86") + self.assertIn("-DCMAKE_CUDA_ARCHITECTURES=89", calls[0][0]) + self.assertEqual(built["gpu_architecture"], "89") + + def test_cuda_x86_admission_takes_the_lesser_of_gpu0_free_vram_and_host_memory(self): + meminfo = "MemAvailable: 2097152 kB\n" + for free_vram, expected in ((10 * 1024**3, 2 * 1024**3), (1 * 1024**3, 1 * 1024**3)): + with patch("lib.performance_backends.Path") as path: + path.return_value.read_text.return_value = meminfo + self.assertEqual(performance_backends.cuda_x86_free( + {"gpu_memory_free_bytes": free_vram}), expected) + class RejectionTests(unittest.TestCase): point = {"id": "c4-depth4096-pool16k", "concurrency": 4, "depth": 4096, "input_tokens": 512, From ef17221a598fca2299477b4eef41945c40672d2e Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Wed, 25 Nov 2026 15:48:22 +1100 Subject: [PATCH 06/50] feat(ci): add a rocm performance backend --- ci/INFERENCE_PERFORMANCE.md | 16 +++ scripts/inference-performance.py | 6 +- scripts/lib/performance_arms.py | 3 +- scripts/lib/performance_backends.py | 110 ++++++++++++++++++ .../tests/inference_performance_contracts.py | 45 +++++++ 5 files changed, 178 insertions(+), 2 deletions(-) diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index f5700e4b..0ac6bb9a 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -62,6 +62,22 @@ GitHub workflow still dispatches Metal only. a 32K pool and 16 lanes) plus both arms' compute buffers. The host record also lists any other compute process already on GPU 0. +`rocm` is AMD ROCm on Linux x86_64, written for the lab's Strix-Halo-class hosts with +unified memory. A plan must name exactly one node, and the job pins GPU 0 with +`HIP_VISIBLE_DEVICES=0`; no `HSA_OVERRIDE_GFX_VERSION` or other override is set. Both +arms read the first GPU agent's `gfx` target from `rocminfo` at build time: Skippy as +`LLAMA_STAGE_AMDGPU_TARGETS`, the reference as `-DGGML_HIP=ON -DAMDGPU_TARGETS=`, +the variable the pinned llama.cpp's `ggml-hip/CMakeLists.txt` forwards to +`CMAKE_HIP_ARCHITECTURES`. No optional HIP feature is enabled in either build. The tool +check runs `rocminfo` and requires `rocm-smi` or `amd-smi`; the host facts record the +GPU's name and `gfx` target, the ROCm version from `/opt/rocm/.info/version`, the amdgpu +driver version, VRAM and GTT total and used, the OS release and kernel. Admission is the +unified rule: the weights plus 16 GiB must fit in the smaller of `MemAvailable` and free +VRAM plus free GTT, since the GPU allocates from its carve-out plus GTT and the kernel +caps GTT; a smoke job records the figures beside the device memory `llama-server` prints +at load. No CI exercises Skippy's Linux ROCm build, so a performance smoke job is its +first run. + Both commits must be on protected main, unless an arm is `pr:N`: the head of an open pull request from this repository, never a fork's, authored by a collaborator with write access, so only code that could already run on trusted CI reaches the lab. An arm can also be `branch:NAME`, the head of a diff --git a/scripts/inference-performance.py b/scripts/inference-performance.py index e02b5315..dad6fec2 100644 --- a/scripts/inference-performance.py +++ b/scripts/inference-performance.py @@ -242,7 +242,11 @@ def native_plan(): def toolcheck(): """The backend's tool check, before any build spends an hour on a host without its tools.""" - command(BACKENDS[native_plan()["backend"]]["tool_check"], timeout=120, capture_stdout=True) + check = BACKENDS[native_plan()["backend"]]["tool_check"] + if callable(check): + check() + else: + command(check, timeout=120, capture_stdout=True) def build_arms(): diff --git a/scripts/lib/performance_arms.py b/scripts/lib/performance_arms.py index ba6ac314..f157ee7e 100644 --- a/scripts/lib/performance_arms.py +++ b/scripts/lib/performance_arms.py @@ -70,7 +70,8 @@ def build(arm, log, backend="metal"): binary = build_dir / "bin/llama-server" built = {"label": arm["label"], "kind": arm["kind"], "sha": arm["sha"], "binary": str(binary), "binary_sha256": digest(binary)} - architecture = skippy_env.get("LLAMA_STAGE_CUDA_ARCHITECTURES") + architecture = (skippy_env.get("LLAMA_STAGE_CUDA_ARCHITECTURES") + or skippy_env.get("LLAMA_STAGE_AMDGPU_TARGETS")) if architecture: built["gpu_architecture"] = architecture return built diff --git a/scripts/lib/performance_backends.py b/scripts/lib/performance_backends.py index f3575b32..d53c7972 100644 --- a/scripts/lib/performance_backends.py +++ b/scripts/lib/performance_backends.py @@ -12,6 +12,8 @@ import platform import re +import shutil +import subprocess from pathlib import Path from . import inference_metal @@ -115,6 +117,94 @@ def cuda_x86_free(host): return min(host["gpu_memory_free_bytes"], cuda_free(host)) +def rocm_agent(): + """The first GPU agent rocminfo lists: its gfx target and marketing name.""" + gfx, name = None, None + for line in capture(["rocminfo"]).splitlines(): + key, _, value = line.partition(":") + key, value = key.strip(), value.strip() + if key == "Name" and re.fullmatch(r"gfx[0-9a-z]+", value or "") and gfx is None: + gfx = value + elif key == "Marketing Name" and value and gfx is not None and name is None: + name = value + if gfx is None: + raise ValueError("rocminfo lists no GPU agent; the rocm backend needs one") + return gfx, name or gfx + + +def rocm_gfx(): + return rocm_agent()[0] + + +def rocm_skippy_env(): + return {"LLAMA_STAGE_BACKEND": "rocm", "LLAMA_STAGE_LINK_MODE": "static", + "LLAMA_STAGE_AMDGPU_TARGETS": rocm_gfx()} + + +def rocm_reference_cmake(): + # The pinned llama.cpp's ggml-hip/CMakeLists.txt forwards AMDGPU_TARGETS to + # CMAKE_HIP_ARCHITECTURES, so this is the variable Skippy's build also sets. + return ["-DGGML_HIP=ON", f"-DAMDGPU_TARGETS={rocm_gfx()}"] + + +def rocm_tool_check(): + capture(["rocminfo"]) + if not shutil.which("rocm-smi") and not shutil.which("amd-smi"): + raise ValueError("the rocm backend requires rocm-smi or amd-smi for its memory figures") + + +def _try_capture(args): + try: + return capture(args) + except subprocess.CalledProcessError: + return "" + + +def rocm_memory(): + """VRAM and GTT, total and used, from the first row rocm-smi reports, plus the GPU count.""" + text = capture(["rocm-smi", "--showmeminfo", "vram", "gtt", "--csv"]) + lines = [line for line in text.strip().splitlines() if line.strip()] + if len(lines) < 2: + raise ValueError(f"rocm-smi did not report vram and gtt: {text!r}") + header = [item.strip().lower() for item in lines[0].split(",")] + + def field(*words): + for index, column in enumerate(header): + if all(word in column for word in words) and index < len(lines[1].split(",")): + return int(lines[1].split(",")[index].strip()) + raise ValueError(f"rocm-smi columns for {words} not found in {header}") + + return (*field("vram", "total"), *field("vram", "used"), *field("gtt", "total"), + *field("gtt", "used"), len(lines) - 1) + + +def rocm_facts(): + """A Linux x86_64 host with an AMD GPU through ROCm/HIP, described by its first GPU.""" + if platform.system() != "Linux" or platform.machine() != "x86_64": + raise ValueError("the rocm backend requires Linux x86_64") + gfx, name = rocm_agent() + vram_total, vram_used, gtt_total, gtt_used, gpu_count = rocm_memory() + try: + rocm = Path("/opt/rocm/.info/version").read_text(encoding="utf-8").strip() + except OSError: + rocm = None + driver_text = _try_capture(["rocm-smi", "--showdriverversion", "--csv"]).strip() + last = driver_text.splitlines()[-1] if driver_text else "" + driver = last.split(",")[-1].strip() if last else "" + return {"gpu": name, "gpu_count": gpu_count, "gpu_used": 0, "gfx_target": gfx, + "vram_total_bytes": vram_total, "vram_used_bytes": vram_used, + "gtt_total_bytes": gtt_total, "gtt_used_bytes": gtt_used, + "driver_version": driver or None, "toolkit_version": rocm, + "os": "linux", "os_version": linux_release(), "kernel": capture(["uname", "-r"]).strip()} + + +def rocm_free(host): + """Unified AMD memory: the GPU allocates from its carve-out (VRAM) plus GTT, and the + kernel caps GTT, so both pools and MemAvailable bound what a model gets.""" + return min(cuda_free(host), (host["vram_total_bytes"] - host["vram_used_bytes"]) + + (host["gtt_total_bytes"] - host["gtt_used_bytes"])) + + # The unified reserve, shared system memory for everything beside the weights. RESERVE_GIB = 16 @@ -171,4 +261,24 @@ def cuda_x86_free(host): "free_memory": cuda_x86_free, "env": {"CUDA_VISIBLE_DEVICES": "0"}, }, + # AMD ROCm on Linux x86_64. The lab's hosts are Strix-Halo class — unified memory, + # the GPU allocating from its VRAM carve-out plus GTT — so admission takes the smaller + # of MemAvailable and free VRAM plus GTT, and the reserve is the unified 16 GiB. No CI + # exercises Skippy's Linux ROCm build; a performance smoke job is its first run. + "rocm": { + "description": "Same-host ROCm comparison", + "selector": {"os": {"family": "linux"}, "arch": {"in": ["x86_64"]}, + "accelerator": {"backend": "rocm"}, "memory": {"unified": True}}, + "memory_key": "system_gib", + "reserve_gib": RESERVE_GIB, + "pin_required": True, + "skippy_env": rocm_skippy_env, + "reference_cmake": rocm_reference_cmake, + "tool_check": rocm_tool_check, + "toolkit_script": None, + "device_prefixes": ("ROCm", "HIP"), + "facts": rocm_facts, + "free_memory": rocm_free, + "env": {"HIP_VISIBLE_DEVICES": "0"}, + }, } diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index edb48360..6ee7995b 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -151,6 +151,21 @@ def test_a_cuda_x86_plan_targets_one_pinned_discrete_gpu(self): self.assertEqual(spec["target"]["nodes"], ["lab-a33338"]) self.assertEqual(spec["runtime"]["env"].get("CUDA_VISIBLE_DEVICES"), "0") + def test_a_rocm_plan_targets_one_pinned_unified_host(self): + arm_list = performance_plan.arms(self.candidate, self.baseline, self.pin) + with self.assertRaisesRegex(ValueError, "must name exactly one node"): + performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 3, None, "any", + backend="rocm") + spec = performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 3, "lab-004309", "r", + backend="rocm") + selector = spec["target"]["selector"] + self.assertEqual(selector["arch"], {"in": ["x86_64"]}) + self.assertEqual(selector["accelerator"], {"backend": "rocm"}) + self.assertIs(selector["memory"]["unified"], True) + self.assertGreaterEqual(selector["memory"]["system_gib"]["min"], 18) + self.assertEqual(spec["target"]["nodes"], ["lab-004309"]) + self.assertEqual(spec["runtime"]["env"].get("HIP_VISIBLE_DEVICES"), "0") + def test_models_must_be_ladder_ids(self): with self.assertRaises(ValueError): performance_plan.models(["qwen35-4b", "qwen35-4b"]) @@ -303,6 +318,36 @@ def test_cuda_x86_admission_takes_the_lesser_of_gpu0_free_vram_and_host_memory(s self.assertEqual(performance_backends.cuda_x86_free( {"gpu_memory_free_bytes": free_vram}), expected) + def test_the_rocm_entry_builds_both_arms_for_the_hosts_gfx_target(self): + calls = [] + with patch("lib.performance_backends.rocm_gfx", return_value="gfx1151"): + with TemporaryDirectory() as directory: + with patch("lib.performance_arms.checkout", return_value=Path(directory)), \ + patch("lib.performance_arms.command", + side_effect=lambda args, **kwargs: calls.append((args, kwargs)) or None), \ + patch("lib.performance_arms.digest", return_value="0" * 64): + built = performance_arms.build(self.skippy, Path(directory) / "b.log", "rocm") + self.assertEqual(calls[0][1]["overrides"]["LLAMA_STAGE_BACKEND"], "rocm") + self.assertEqual(calls[0][1]["overrides"]["LLAMA_STAGE_AMDGPU_TARGETS"], "gfx1151") + self.assertEqual(built["gpu_architecture"], "gfx1151") + del calls[:] + performance_arms.build(self.reference, Path(directory) / "r.log", "rocm") + self.assertIn("-DGGML_HIP=ON", calls[0][0]) + self.assertIn("-DAMDGPU_TARGETS=gfx1151", calls[0][0]) + self.assertNotIn("-DGGML_CUDA=ON", calls[0][0]) + self.assertIsNone(calls[0][1]["overrides"]) + + def test_rocm_admission_takes_the_lesser_of_memory_and_free_vram_plus_gtt(self): + gib = 1024**3 + host = {"vram_total_bytes": 90 * gib, "vram_used_bytes": 10 * gib, + "gtt_total_bytes": 80 * gib, "gtt_used_bytes": 20 * gib} + with patch("lib.performance_backends.Path") as path: + path.return_value.read_text.return_value = "MemAvailable: 104857600 kB\n" # 100 GiB + self.assertEqual(performance_backends.rocm_free(host), 100 * gib) + with patch("lib.performance_backends.Path") as path: + path.return_value.read_text.return_value = "MemAvailable: 209715200 kB\n" # 200 GiB + self.assertEqual(performance_backends.rocm_free(host), 140 * gib) + class RejectionTests(unittest.TestCase): point = {"id": "c4-depth4096-pool16k", "concurrency": 4, "depth": 4096, "input_tokens": 512, From 2686265ac26a25bd297f284d7955b1e0e27e4f85 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Wed, 25 Nov 2026 17:10:01 +1100 Subject: [PATCH 07/50] fix(ci): stop a built arm shadowing the backend entry in performance execution --- scripts/inference-performance.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/scripts/inference-performance.py b/scripts/inference-performance.py index dad6fec2..529773fe 100644 --- a/scripts/inference-performance.py +++ b/scripts/inference-performance.py @@ -327,11 +327,11 @@ def execute(): plan = native_plan() entry = BACKENDS[plan["backend"]] built = read_json(BUILT) - if [(entry["label"], entry["sha"]) for entry in built] != [(arm["label"], arm["sha"]) for arm in plan["arms"]]: + if [(arm["label"], arm["sha"]) for arm in built] != [(arm["label"], arm["sha"]) for arm in plan["arms"]]: raise ValueError("built arms differ from the admitted plan") - for entry in built: - if digest(Path(entry["binary"])) != entry["binary_sha256"]: - raise ValueError(f'{entry["label"]} binary changed after it was built') + for arm in built: + if digest(Path(arm["binary"])) != arm["binary_sha256"]: + raise ValueError(f'{arm["label"]} binary changed after it was built') output = Path(os.environ["JIANYANG_ARTIFACT_DIR"]) output.mkdir(parents=True, exist_ok=True) for log in WORK.glob("build-*.log"): From 0159514b595d94f6bb8f127e94af9a744113760d Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Wed, 25 Nov 2026 17:10:01 +1100 Subject: [PATCH 08/50] fix(ci): quote llama prefix-map flags for workspaces with spaces --- scripts/build-llama.sh | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/scripts/build-llama.sh b/scripts/build-llama.sh index 3d1bc64d..73323011 100755 --- a/scripts/build-llama.sh +++ b/scripts/build-llama.sh @@ -316,7 +316,11 @@ fi # embedded source/build paths so the archived link closure does not retain a # producer-local workspace path. if [[ "$LLAMA_LINK_MODE" == "static" ]]; then - PREFIX_MAP_FLAGS="-ffile-prefix-map=$ROOT=/skippy -fdebug-prefix-map=$ROOT=/skippy -fmacro-prefix-map=$ROOT=/skippy" + # CMake splits CMAKE__FLAGS on spaces without shell quoting, so a + # workspace under a path such as "Library/Application Support" would hand + # clang the map's path as several arguments and fail the compiler test. + # Each flag carries its own quotes inside the CMake variable instead. + PREFIX_MAP_FLAGS="\"-ffile-prefix-map=$ROOT=/skippy\" \"-fdebug-prefix-map=$ROOT=/skippy\" \"-fmacro-prefix-map=$ROOT=/skippy\"" case "$(uname -s)" in MINGW*|MSYS*|CYGWIN*) # Setting CMAKE__FLAGS replaces CMake's platform defaults, which From 686474fb3b011cc2c228ee22e7f104c4a8be5305 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Wed, 25 Nov 2026 17:39:15 +1100 Subject: [PATCH 09/50] fix(ci): read the AIPerf summary at the artifact root --- scripts/lib/performance_load.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/scripts/lib/performance_load.py b/scripts/lib/performance_load.py index 359dcac0..97700bd0 100644 --- a/scripts/lib/performance_load.py +++ b/scripts/lib/performance_load.py @@ -105,7 +105,10 @@ def run_point(endpoint, point, coordinate, tokenizer_path, warmup, directory: Pa return dict.fromkeys(METRICS), rejected if failure is not None: raise failure - exports = list(directory.rglob("profile_export_aiperf.json")) - if len(exports) != 1: - raise ValueError(f'{point["id"]}: expected one AIPerf export, found {len(exports)}') - return measurements(read_json(exports[0])), None + # AIPerf 0.13.0 writes the summary at the artifact root and each phase under + # phases/, so a recursive search sees three exports; the summary is the file + # this point's numbers come from. + export = directory / "profile_export_aiperf.json" + if not export.is_file(): + raise ValueError(f'{point["id"]}: no AIPerf export in {directory}') + return measurements(read_json(export)), None From f2a4c453b35f4e243f28d47dc592815898061e1d Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Wed, 25 Nov 2026 18:43:13 +1100 Subject: [PATCH 10/50] fix(ci): run AIPerf with a short TMPDIR so its ZMQ sockets fit --- scripts/lib/performance_load.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/scripts/lib/performance_load.py b/scripts/lib/performance_load.py index 97700bd0..8021d880 100644 --- a/scripts/lib/performance_load.py +++ b/scripts/lib/performance_load.py @@ -1,7 +1,9 @@ """Drive one load point with the pinned AIPerf and read back what it measured.""" import json +import shutil import subprocess +import tempfile from collections import Counter from pathlib import Path @@ -95,11 +97,19 @@ def rejection(directory, requests): def run_point(endpoint, point, coordinate, tokenizer_path, warmup, directory: Path, *, may_reject): """One point's metrics, or null metrics and what the server rejected where it may reject.""" failure = None + # AIPerf stages its ZeroMQ event bus under TMPDIR, and a workspace path longer + # than the 103-byte unix-socket limit (this Mac's "Application Support" tree) + # or holding a space breaks the ipc:// endpoints before a request is sent, so + # every AIPerf run gets its own short, space-free TMPDIR. + short_tmp = Path(tempfile.mkdtemp(prefix="aiperf-tmp-")) try: - command(profile_args(endpoint, point, coordinate, tokenizer_path, warmup, directory), timeout=5400) + command(profile_args(endpoint, point, coordinate, tokenizer_path, warmup, directory), + timeout=5400, overrides={"TMPDIR": str(short_tmp)}) except subprocess.CalledProcessError as error: # AIPerf exits non-zero, with no summary export, when every measured request failed. failure = error + finally: + shutil.rmtree(short_tmp, ignore_errors=True) rejected = rejection(directory, point["requests"]) if may_reject else None if rejected is not None: return dict.fromkeys(METRICS), rejected From 57ff22919c5c5efdb038d38610e14a48c0f35c7e Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Wed, 25 Nov 2026 19:13:18 +1100 Subject: [PATCH 11/50] fix(ci): anchor AIPerf's short TMPDIR at /tmp --- scripts/lib/performance_load.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/scripts/lib/performance_load.py b/scripts/lib/performance_load.py index 8021d880..da8eb43f 100644 --- a/scripts/lib/performance_load.py +++ b/scripts/lib/performance_load.py @@ -97,11 +97,11 @@ def rejection(directory, requests): def run_point(endpoint, point, coordinate, tokenizer_path, warmup, directory: Path, *, may_reject): """One point's metrics, or null metrics and what the server rejected where it may reject.""" failure = None - # AIPerf stages its ZeroMQ event bus under TMPDIR, and a workspace path longer - # than the 103-byte unix-socket limit (this Mac's "Application Support" tree) - # or holding a space breaks the ipc:// endpoints before a request is sent, so - # every AIPerf run gets its own short, space-free TMPDIR. - short_tmp = Path(tempfile.mkdtemp(prefix="aiperf-tmp-")) + # AIPerf stages its ZeroMQ event bus under TMPDIR, and the job's own TMPDIR + # lives under the workspace, whose path can exceed the 103-byte unix-socket + # limit (this Mac's "Application Support" tree) before AIPerf adds its own + # nesting. Anchor a short, space-free TMPDIR at /tmp instead. + short_tmp = Path(tempfile.mkdtemp(prefix="aiperf-tmp-", dir="/tmp")) try: command(profile_args(endpoint, point, coordinate, tokenizer_path, warmup, directory), timeout=5400, overrides={"TMPDIR": str(short_tmp)}) From 4070ad869bf261295b77d020979c635579eae195 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Wed, 25 Nov 2026 19:44:33 +1100 Subject: [PATCH 12/50] fix(ci): print the traceback when performance execution fails --- scripts/inference-performance.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scripts/inference-performance.py b/scripts/inference-performance.py index 529773fe..1a7fe0a8 100644 --- a/scripts/inference-performance.py +++ b/scripts/inference-performance.py @@ -9,6 +9,7 @@ import shutil import subprocess import sys +import traceback import tarfile import time from datetime import datetime, timezone @@ -411,4 +412,5 @@ def main(): main() except (OSError, ValueError, KeyError, TypeError, RuntimeError, subprocess.SubprocessError, KeyboardInterrupt) as error: + traceback.print_exc() sys.exit(str(error)) From 4a41df5c20b5873603d9c310fd6a6ec7775ff7d3 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Wed, 25 Nov 2026 20:48:13 +1100 Subject: [PATCH 13/50] fix(ci): target the pinned rocm node with a bare pin --- ci/INFERENCE_PERFORMANCE.md | 6 ++++-- scripts/lib/performance_backends.py | 5 +++-- scripts/lib/performance_plan.py | 13 +++++++++---- scripts/tests/inference_performance_contracts.py | 10 +++------- 4 files changed, 19 insertions(+), 15 deletions(-) diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index 0ac6bb9a..c0687107 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -63,8 +63,10 @@ GitHub workflow still dispatches Metal only. other compute process already on GPU 0. `rocm` is AMD ROCm on Linux x86_64, written for the lab's Strix-Halo-class hosts with -unified memory. A plan must name exactly one node, and the job pins GPU 0 with -`HIP_VISIBLE_DEVICES=0`; no `HSA_OVERRIDE_GFX_VERSION` or other override is set. Both +unified memory. A plan must name exactly one node and targets it bare — the lab's ROCm +agents report no `os` facts, and a selector holding an `os` key never matches them — +and the job pins GPU 0 with `HIP_VISIBLE_DEVICES=0`; no `HSA_OVERRIDE_GFX_VERSION` or +other override is set. Both arms read the first GPU agent's `gfx` target from `rocminfo` at build time: Skippy as `LLAMA_STAGE_AMDGPU_TARGETS`, the reference as `-DGGML_HIP=ON -DAMDGPU_TARGETS=`, the variable the pinned llama.cpp's `ggml-hip/CMakeLists.txt` forwards to diff --git a/scripts/lib/performance_backends.py b/scripts/lib/performance_backends.py index d53c7972..dbcd2abc 100644 --- a/scripts/lib/performance_backends.py +++ b/scripts/lib/performance_backends.py @@ -267,8 +267,9 @@ def rocm_free(host): # exercises Skippy's Linux ROCm build; a performance smoke job is its first run. "rocm": { "description": "Same-host ROCm comparison", - "selector": {"os": {"family": "linux"}, "arch": {"in": ["x86_64"]}, - "accelerator": {"backend": "rocm"}, "memory": {"unified": True}}, + # The lab's ROCm agents report no os facts and any selector holding an os + # key never matches them, so a rocm plan targets its pinned node bare. + "selector": {}, "memory_key": "system_gib", "reserve_gib": RESERVE_GIB, "pin_required": True, diff --git a/scripts/lib/performance_plan.py b/scripts/lib/performance_plan.py index 00903ee5..a3c4dfdd 100644 --- a/scripts/lib/performance_plan.py +++ b/scripts/lib/performance_plan.py @@ -125,10 +125,15 @@ def job_spec(harness, arm_list, keys, rounds, node, label, *, trace=False, backe if entry["pin_required"] and node is None: raise ValueError(f"a {backend} plan must name exactly one node: its GPUs differ between hosts") largest = max(sum(file["size"] for file in fixture(key)["files"]) for key in keys) - selector = {key: value for key, value in entry["selector"].items() if key != "memory"} - selector["memory"] = {entry["memory_key"]: {"min": math.ceil(largest / 1024**3) + entry["reserve_gib"]}, - **entry["selector"].get("memory", {})} - target = {"executor": "lab", "num_nodes": 1, "selector": selector} + if entry["selector"]: + selector = {key: value for key, value in entry["selector"].items() if key != "memory"} + selector["memory"] = {entry["memory_key"]: {"min": math.ceil(largest / 1024**3) + entry["reserve_gib"]}, + **entry["selector"].get("memory", {})} + target = {"executor": "lab", "num_nodes": 1, "selector": selector} + else: + # An entry with no selector targets its pinned node bare: the selector's + # os and accelerator facts are exactly what some lab agents never report. + target = {"executor": "lab", "num_nodes": 1} if node is not None: target["nodes"] = [node] repos = [{"url": SKIPPY, "rev": harness, "path": "harness"}] + [ diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index 6ee7995b..c17d7ce1 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -156,14 +156,10 @@ def test_a_rocm_plan_targets_one_pinned_unified_host(self): with self.assertRaisesRegex(ValueError, "must name exactly one node"): performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 3, None, "any", backend="rocm") - spec = performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 3, "lab-004309", "r", + spec = performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 3, "lab-003827", "r", backend="rocm") - selector = spec["target"]["selector"] - self.assertEqual(selector["arch"], {"in": ["x86_64"]}) - self.assertEqual(selector["accelerator"], {"backend": "rocm"}) - self.assertIs(selector["memory"]["unified"], True) - self.assertGreaterEqual(selector["memory"]["system_gib"]["min"], 18) - self.assertEqual(spec["target"]["nodes"], ["lab-004309"]) + self.assertNotIn("selector", spec["target"]) + self.assertEqual(spec["target"]["nodes"], ["lab-003827"]) self.assertEqual(spec["runtime"]["env"].get("HIP_VISIBLE_DEVICES"), "0") def test_models_must_be_ladder_ids(self): From 0f46b69275523ca8eeec6822eea24c01f61fecee Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Wed, 25 Nov 2026 20:48:13 +1100 Subject: [PATCH 14/50] fix(ci): pin the rocm gfx target and toolchain paths in the job env --- ci/INFERENCE_PERFORMANCE.md | 12 ++++--- scripts/lib/performance_backends.py | 11 ++++-- .../tests/inference_performance_contracts.py | 35 ++++++++++--------- 3 files changed, 33 insertions(+), 25 deletions(-) diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index c0687107..a2ae7001 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -66,11 +66,13 @@ GitHub workflow still dispatches Metal only. unified memory. A plan must name exactly one node and targets it bare — the lab's ROCm agents report no `os` facts, and a selector holding an `os` key never matches them — and the job pins GPU 0 with `HIP_VISIBLE_DEVICES=0`; no `HSA_OVERRIDE_GFX_VERSION` or -other override is set. Both -arms read the first GPU agent's `gfx` target from `rocminfo` at build time: Skippy as -`LLAMA_STAGE_AMDGPU_TARGETS`, the reference as `-DGGML_HIP=ON -DAMDGPU_TARGETS=`, -the variable the pinned llama.cpp's `ggml-hip/CMakeLists.txt` forwards to -`CMAKE_HIP_ARCHITECTURES`. No optional HIP feature is enabled in either build. The tool +other override is set. Both builds carry the pinned target `gfx1151`: the job env sets +`SKIPPY_AMDGPU_TARGETS=gfx1151` (which `scripts/build-llama.sh` falls back to) and puts +`/opt/rocm/bin` on `PATH` and `/opt/rocm/lib` on `LD_LIBRARY_PATH`, which the job shell +does not inherit on its own; the reference arm configures with +`-DGGML_HIP=ON -DAMDGPU_TARGETS=gfx1151`, the variable the pinned llama.cpp's +`ggml-hip/CMakeLists.txt` forwards to `CMAKE_HIP_ARCHITECTURES`. No optional HIP +feature is enabled in either build. The tool check runs `rocminfo` and requires `rocm-smi` or `amd-smi`; the host facts record the GPU's name and `gfx` target, the ROCm version from `/opt/rocm/.info/version`, the amdgpu driver version, VRAM and GTT total and used, the OS release and kernel. Admission is the diff --git a/scripts/lib/performance_backends.py b/scripts/lib/performance_backends.py index dbcd2abc..a75a7796 100644 --- a/scripts/lib/performance_backends.py +++ b/scripts/lib/performance_backends.py @@ -136,15 +136,18 @@ def rocm_gfx(): return rocm_agent()[0] +ROCM_GFX_TARGET = "gfx1151" + + def rocm_skippy_env(): return {"LLAMA_STAGE_BACKEND": "rocm", "LLAMA_STAGE_LINK_MODE": "static", - "LLAMA_STAGE_AMDGPU_TARGETS": rocm_gfx()} + "LLAMA_STAGE_AMDGPU_TARGETS": ROCM_GFX_TARGET} def rocm_reference_cmake(): # The pinned llama.cpp's ggml-hip/CMakeLists.txt forwards AMDGPU_TARGETS to # CMAKE_HIP_ARCHITECTURES, so this is the variable Skippy's build also sets. - return ["-DGGML_HIP=ON", f"-DAMDGPU_TARGETS={rocm_gfx()}"] + return ["-DGGML_HIP=ON", f"-DAMDGPU_TARGETS={ROCM_GFX_TARGET}"] def rocm_tool_check(): @@ -280,6 +283,8 @@ def rocm_free(host): "device_prefixes": ("ROCm", "HIP"), "facts": rocm_facts, "free_memory": rocm_free, - "env": {"HIP_VISIBLE_DEVICES": "0"}, + "env": {"HIP_VISIBLE_DEVICES": "0", "SKIPPY_AMDGPU_TARGETS": ROCM_GFX_TARGET, + "PATH": "/opt/rocm/bin:/usr/local/bin:/usr/bin:/bin", + "LD_LIBRARY_PATH": "/opt/rocm/lib"}, }, } diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index c17d7ce1..b0d7f232 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -161,6 +161,9 @@ def test_a_rocm_plan_targets_one_pinned_unified_host(self): self.assertNotIn("selector", spec["target"]) self.assertEqual(spec["target"]["nodes"], ["lab-003827"]) self.assertEqual(spec["runtime"]["env"].get("HIP_VISIBLE_DEVICES"), "0") + self.assertEqual(spec["runtime"]["env"].get("SKIPPY_AMDGPU_TARGETS"), "gfx1151") + self.assertTrue(spec["runtime"]["env"].get("PATH", "").startswith("/opt/rocm/bin")) + self.assertEqual(spec["runtime"]["env"].get("LD_LIBRARY_PATH"), "/opt/rocm/lib") def test_models_must_be_ladder_ids(self): with self.assertRaises(ValueError): @@ -314,24 +317,22 @@ def test_cuda_x86_admission_takes_the_lesser_of_gpu0_free_vram_and_host_memory(s self.assertEqual(performance_backends.cuda_x86_free( {"gpu_memory_free_bytes": free_vram}), expected) - def test_the_rocm_entry_builds_both_arms_for_the_hosts_gfx_target(self): + def test_the_rocm_entry_builds_both_arms_for_the_pinned_gfx_target(self): calls = [] - with patch("lib.performance_backends.rocm_gfx", return_value="gfx1151"): - with TemporaryDirectory() as directory: - with patch("lib.performance_arms.checkout", return_value=Path(directory)), \ - patch("lib.performance_arms.command", - side_effect=lambda args, **kwargs: calls.append((args, kwargs)) or None), \ - patch("lib.performance_arms.digest", return_value="0" * 64): - built = performance_arms.build(self.skippy, Path(directory) / "b.log", "rocm") - self.assertEqual(calls[0][1]["overrides"]["LLAMA_STAGE_BACKEND"], "rocm") - self.assertEqual(calls[0][1]["overrides"]["LLAMA_STAGE_AMDGPU_TARGETS"], "gfx1151") - self.assertEqual(built["gpu_architecture"], "gfx1151") - del calls[:] - performance_arms.build(self.reference, Path(directory) / "r.log", "rocm") - self.assertIn("-DGGML_HIP=ON", calls[0][0]) - self.assertIn("-DAMDGPU_TARGETS=gfx1151", calls[0][0]) - self.assertNotIn("-DGGML_CUDA=ON", calls[0][0]) - self.assertIsNone(calls[0][1]["overrides"]) + with TemporaryDirectory() as directory: + with patch("lib.performance_arms.checkout", return_value=Path(directory)), \ + patch("lib.performance_arms.command", + side_effect=lambda args, **kwargs: calls.append((args, kwargs)) or None), \ + patch("lib.performance_arms.digest", return_value="0" * 64): + built = performance_arms.build(self.skippy, Path(directory) / "b.log", "rocm") + self.assertEqual(calls[0][1]["overrides"]["LLAMA_STAGE_BACKEND"], "rocm") + self.assertEqual(calls[0][1]["overrides"]["LLAMA_STAGE_AMDGPU_TARGETS"], "gfx1151") + self.assertEqual(built["gpu_architecture"], "gfx1151") + del calls[:] + performance_arms.build(self.reference, Path(directory) / "r.log", "rocm") + self.assertIn("-DGGML_HIP=ON", calls[0][0]) + self.assertIn("-DAMDGPU_TARGETS=gfx1151", calls[0][0]) + self.assertNotIn("-DGGML_CUDA=ON", calls[0][0]) def test_rocm_admission_takes_the_lesser_of_memory_and_free_vram_plus_gtt(self): gib = 1024**3 From bffc5c83b805a8d8432fa5a6c546e31bb04f776d Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Thu, 26 Nov 2026 05:05:55 +1100 Subject: [PATCH 15/50] Treat Darwin's EPERM from an exiting process group as gone killpg(pgid, 0) on macOS can fail with EPERM while a group's last members are exiting. The poll before it still saw the server running, so stop() raised after a clean shutdown and the job died mid-campaign on every Mac. Ask ps whether a process of ours that can still run is in the group instead, which also covers a recycled pgid. --- scripts/lib/ci_process.py | 42 +++++++++++++++------------ scripts/tests/automation_contracts.py | 24 +++++++++++++-- 2 files changed, 45 insertions(+), 21 deletions(-) diff --git a/scripts/lib/ci_process.py b/scripts/lib/ci_process.py index ea20bb62..058f1602 100644 --- a/scripts/lib/ci_process.py +++ b/scripts/lib/ci_process.py @@ -39,9 +39,9 @@ def graceful_stop(child): except ProcessLookupError: pass except PermissionError: - # A recycled pgid names a group we cannot signal; once the child - # has exited there is nothing of ours left to signal. - if child.poll() is None: + # A recycled pgid, or a group whose members are all exiting, cannot be + # signalled; that is only an error while a process of ours is still in it. + if live_member(child.pid): raise @@ -54,11 +54,25 @@ def force_stop(child): except ProcessLookupError: pass except PermissionError: - if child.poll() is None: + if live_member(child.pid): raise child.wait(timeout=10) +def live_member(group): + """Whether a process of ours that can still run is in `group`. Zombies cannot + execute, and a process of another user's means the pgid was recycled.""" + rows = subprocess.check_output( + ["ps", "-axo", "pgid=,uid=,stat="], timeout=5, text=True, env=environment(), + ) + uid = os.getuid() + for row in rows.splitlines(): + pgid, owner, state = row.split(None, 2) + if int(pgid) == group and int(owner) == uid and not state.startswith(("Z", "X")): + return True + return False + + def group_alive(child): exited = child.poll() is not None if os.name == "nt": @@ -68,23 +82,13 @@ def group_alive(child): except ProcessLookupError: return False except PermissionError: - if not exited: - raise - # EPERM on signal-0 means the pgid now holds processes we cannot - # signal: the id was recycled after our group exited. - return False + # Darwin answers EPERM for a group whose members are all exiting, which can + # happen between the poll above and the signal, as well as for a recycled pgid. + return live_member(child.pid) if not exited: return True - # A group containing only unreaped descendants can still be visible to - # killpg. Zombies cannot execute and may be owned by another reaper. - rows = subprocess.check_output( - ["ps", "-axo", "pgid=,stat="], timeout=5, text=True, env=environment(), - ) - for row in rows.splitlines(): - group, state = row.split(None, 1) - if int(group) == child.pid and not state.startswith(("Z", "X")): - return True - return False + # A group containing only unreaped descendants can still be visible to killpg. + return live_member(child.pid) def stop(child): diff --git a/scripts/tests/automation_contracts.py b/scripts/tests/automation_contracts.py index e15ff21f..fe442c37 100644 --- a/scripts/tests/automation_contracts.py +++ b/scripts/tests/automation_contracts.py @@ -10,9 +10,9 @@ import tempfile import unittest from pathlib import Path -from unittest.mock import patch +from unittest.mock import Mock, patch -from lib import ci_artifacts, ci_smoke +from lib import ci_artifacts, ci_process, ci_smoke from lib.ci_process import command from lib.graph_contracts import MANIFEST from lib.upgrade_source import git, restore_at @@ -457,5 +457,25 @@ def test_layout_signature_binds_workspace_and_cargo_home(self): "layout digest must cover both the cargo home and the workspace") +class ProcessGroups(unittest.TestCase): + """Darwin's killpg answers EPERM for an exiting group and for a recycled pgid.""" + + def alive(self, ps, exited): + child = Mock(pid=4242) + child.poll.return_value = 0 if exited else None + with patch.object(ci_process.os, "killpg", side_effect=PermissionError), \ + patch.object(ci_process.subprocess, "check_output", return_value=ps): + return ci_process.group_alive(child) + + def test_a_group_exiting_after_the_poll_is_not_alive(self): + self.assertFalse(self.alive(f"4242 {os.getuid()} Z\n", exited=False)) + + def test_a_recycled_pgid_is_not_our_group(self): + self.assertFalse(self.alive(f"4242 {os.getuid() + 1} S\n", exited=True)) + + def test_a_running_process_of_ours_keeps_the_group_alive(self): + self.assertTrue(self.alive(f" 99 {os.getuid()} S\n4242 {os.getuid()} R+\n", exited=False)) + + if __name__ == "__main__": unittest.main() From b3326844a4f1a066e499559e8358fbb25c55a5fa Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Thu, 26 Nov 2026 06:30:01 +1100 Subject: [PATCH 16/50] Turn off AIPerf's optional collectors in performance runs AIPerf 0.13 scrapes server metrics and GPU telemetry by default. Under 16-way load on the Macs and the GB10 those collectors missed heartbeats, and AIPerf then marked the run incomplete or exited non-zero, failing jobs whose requests had all completed. The harness reads neither, so it no longer starts them. --- scripts/lib/performance_load.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/scripts/lib/performance_load.py b/scripts/lib/performance_load.py index da8eb43f..8f28f0ab 100644 --- a/scripts/lib/performance_load.py +++ b/scripts/lib/performance_load.py @@ -40,6 +40,9 @@ def tokenizer(fixture): def profile_args(endpoint, point, coordinate, tokenizer_path, warmup, directory): args = [ *AIPERF, "--ui", "simple", "--url", endpoint, "--endpoint-type", "chat", "--streaming", + # Nothing here reads AIPerf's server metrics or GPU telemetry, and under load their + # optional collectors miss heartbeats, which marks the whole run incomplete. + "--no-server-metrics", "--no-gpu-telemetry", "--model", coordinate, "--tokenizer", str(tokenizer_path), "--random-seed", "42", "--use-server-token-count", "--concurrency", str(point["concurrency"]), "--request-count", str(point["requests"]), "--warmup-request-count", str(warmup), From edf8f22032a0574e784a18f61534ae7b2583b7df Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Fri, 27 Nov 2026 09:26:26 +1100 Subject: [PATCH 17/50] Let a performance plan name the servers it runs Looking inside one slow point meant rerunning the whole scenario, every server's points on every arm. SERVERS=a,b admits a plan with only those servers and their points, recorded in plan.json so the job runs the same subset; an empty or unknown name is refused. --- scripts/inference-performance.py | 8 +++++--- scripts/lib/performance_plan.py | 15 ++++++++++++--- scripts/tests/inference_performance_contracts.py | 8 ++++++++ 3 files changed, 25 insertions(+), 6 deletions(-) diff --git a/scripts/inference-performance.py b/scripts/inference-performance.py index 1a7fe0a8..a4fc0071 100644 --- a/scripts/inference-performance.py +++ b/scripts/inference-performance.py @@ -106,14 +106,16 @@ def admit(evidence): keys = models([key.strip() for key in os.environ["MODELS"].split(",") if key.strip()]) pins = nodes([node.strip() for node in os.environ.get("NODES", "").split(",") if node.strip()]) rounds = int(os.environ.get("ROUNDS") or 3) + servers = [server.strip() for server in os.environ.get("SERVERS", "").split(",") if server.strip()] or None jobs = [{"label": node or "any", "spec": job_spec(harness, arm_list, keys, rounds, node, node or "any", - trace=trace, backend=backend)} + trace=trace, backend=backend, servers=servers)} for node in (pins or [None])] evidence.mkdir(parents=True, exist_ok=True) write_json(evidence / "plan.json", {"harness": harness, "backend": backend, "arms": arm_list, "models": keys, - "rounds": rounds, "trace": trace, "pull_requests": pull_requests, + "rounds": rounds, "trace": trace, "servers": servers, + "pull_requests": pull_requests, "branches": branches, "committed_at": committed_at(arm_list), "jobs": jobs}) for arm in arm_list: @@ -337,7 +339,7 @@ def execute(): output.mkdir(parents=True, exist_ok=True) for log in WORK.glob("build-*.log"): (output / log.name).write_bytes(log.read_bytes()) - shape, helps = scenario(), {entry["label"]: capabilities(entry) for entry in built} + shape, helps = scenario(plan.get("servers")), {entry["label"]: capabilities(entry) for entry in built} record = {"schema_version": 1, "harness": plan["harness"], "scenario_sha256": digest(SCENARIO), "started_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), "host": {"node": os.environ.get("JIANYANG_NODE"), "backend": plan["backend"], diff --git a/scripts/lib/performance_plan.py b/scripts/lib/performance_plan.py index a3c4dfdd..a4999eb5 100644 --- a/scripts/lib/performance_plan.py +++ b/scripts/lib/performance_plan.py @@ -28,7 +28,9 @@ def count(value, name, minimum=1): return value -def scenario(): +def scenario(named=None): + """The checked scenario; with `named`, only those servers and their points, to rerun one + workload without the rest.""" value = read_json(SCENARIO) if (set(value) != {"schema_version", "context_per_lane", "warmup_requests", "servers"} or value["schema_version"] != 1 or not value["servers"]): @@ -56,6 +58,11 @@ def scenario(): raise ValueError(f'{point["id"]}: concurrency exceeds the server\'s lanes') if point["depth"] + point["input_tokens"] + point["output_tokens"] > context: raise ValueError(f'{point["id"]}: one request exceeds a lane\'s context') + if named is not None: + unknown = set(named) - servers + if not named or unknown: + raise ValueError(f"unknown performance servers: {', '.join(sorted(unknown)) or 'none named'}") + value = {**value, "servers": [server for server in value["servers"] if server["id"] in named]} return value @@ -110,7 +117,7 @@ def nodes(values): return values -def job_spec(harness, arm_list, keys, rounds, node, label, *, trace=False, backend="metal"): +def job_spec(harness, arm_list, keys, rounds, node, label, *, trace=False, backend="metal", servers=None): """`trace` adds one diagnostic pass of the candidate with debug telemetry, kept out of the measurements: tracing costs time, so a traced arm is not a comparable one.""" count(rounds, "rounds") @@ -120,7 +127,7 @@ def job_spec(harness, arm_list, keys, rounds, node, label, *, trace=False, backe raise ValueError(f"at most {MAX_ROUNDS} rounds fit the job's time budget") if backend not in BACKENDS: raise ValueError(f"unknown backend {backend!r}; the table holds {', '.join(sorted(BACKENDS))}") - shape = scenario() + shape = scenario(servers) entry = BACKENDS[backend] if entry["pin_required"] and node is None: raise ValueError(f"a {backend} plan must name exactly one node: its GPUs differ between hosts") @@ -141,6 +148,8 @@ def job_spec(harness, arm_list, keys, rounds, node, label, *, trace=False, backe for arm in arm_list] plan = {"harness": harness, "backend": backend, "arms": arm_list, "models": keys, "rounds": rounds, "trace": trace} + if servers is not None: + plan["servers"] = servers points = [point for server in shape["servers"] for point in server["points"]] return { "name": f"skippy-inference-performance-{label}", diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index b0d7f232..ee216df6 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -35,6 +35,14 @@ def test_scenario_rejects_impossible_servers(self): with self.assertRaises(ValueError): performance_plan.scenario() + def test_named_servers_keep_only_their_points(self): + first = performance_plan.scenario()["servers"][0] + shape = performance_plan.scenario([first["id"]]) + self.assertEqual(shape["servers"], [first]) + for names in ([], ["no-such-server"]): + with self.assertRaises(ValueError): + performance_plan.scenario(names) + class PlanTests(unittest.TestCase): candidate, baseline, pin = "a" * 40, "b" * 40, "c" * 40 From 019e4e16a16cce55635848da045808d35b7fac2c Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Fri, 27 Nov 2026 15:07:59 +1100 Subject: [PATCH 18/50] Let a performance plan run a variant of a server with its own Skippy flags Skippy's time to first token trails llama-server's at four overlapping long prompts while its decode is faster and request latency matches, which points at how each schedules prefill against decode. A variant server with a larger prefill step measures that on the same machine and rounds as the server it varies. Variants run only when named, so campaigns keep their cells. --- ci/INFERENCE_PERFORMANCE.md | 8 ++++ ci/inference-performance.json | 9 ++++ scripts/inference-performance.py | 6 ++- scripts/lib/performance_arms.py | 15 +++++++ scripts/lib/performance_plan.py | 41 +++++++++++++++---- .../tests/inference_performance_contracts.py | 30 ++++++++++++++ 6 files changed, 99 insertions(+), 10 deletions(-) diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index a2ae7001..9cb4f7b2 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -116,6 +116,14 @@ output, sixteen lanes with and without a 4,096-token shared prefix in a 32K pool, and four lanes at that depth with 16K and 32K pools: the cells where KV pressure and batching show. +A server with `skippy_flags` is a variant of another: the same lanes and pool, +with Skippy flags of its own, such as a larger prefill step. It runs only when a +plan names it in `SERVERS`, so a campaign keeps the same cells. Its flags reach +Skippy arms only, never `llama-server`, and may not set what the harness sets +itself (context, lanes, pool, speculation, telemetry). An arm whose build lacks +one of them fails before any round, since without it the variant would measure +the server it varies. + An arm that lacks a setting, such as `--kv-pool-tokens` on a commit from before the pool existed, runs without it. Each sample records what was applied and what the arm did not support. All arms are probed before model measurements begin. diff --git a/ci/inference-performance.json b/ci/inference-performance.json index 362cb063..5b913c9d 100644 --- a/ci/inference-performance.json +++ b/ci/inference-performance.json @@ -44,6 +44,15 @@ "points": [ {"id": "c4-depth4096-pool32k", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 16} ] + }, + { + "id": "lanes4-pool32k-prefill2048", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"prefill-chunk-size": 2048, "microbatch-size": 2048}, + "points": [ + {"id": "c4-depth4096-pool32k-prefill2048", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 16} + ] } ] } diff --git a/scripts/inference-performance.py b/scripts/inference-performance.py index a4fc0071..f10eda4e 100644 --- a/scripts/inference-performance.py +++ b/scripts/inference-performance.py @@ -24,7 +24,7 @@ from lib.inference_inputs import admit as admit_model from lib.inference_inputs import fixture from lib.jy_qualification import ORIGIN, Pilot -from lib.performance_arms import build, capabilities, may_reject, server_args, supports +from lib.performance_arms import build, capabilities, may_reject, server_args, server_flags, supports from lib.performance_backends import BACKENDS from lib.performance_load import run_point, tokenizer from lib.performance_plan import (SCENARIO, arms, branch_name, job_spec, models, nodes, pull_request_head, @@ -340,6 +340,10 @@ def execute(): for log in WORK.glob("build-*.log"): (output / log.name).write_bytes(log.read_bytes()) shape, helps = scenario(plan.get("servers")), {entry["label"]: capabilities(entry) for entry in built} + # before any round, so a variant whose flag an arm lacks fails before it measures anything + for arm in built: + for server in shape["servers"]: + server_flags(arm, helps[arm["label"]], server) record = {"schema_version": 1, "harness": plan["harness"], "scenario_sha256": digest(SCENARIO), "started_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), "host": {"node": os.environ.get("JIANYANG_NODE"), "backend": plan["backend"], diff --git a/scripts/lib/performance_arms.py b/scripts/lib/performance_arms.py index f157ee7e..3e772eb3 100644 --- a/scripts/lib/performance_arms.py +++ b/scripts/lib/performance_arms.py @@ -95,6 +95,18 @@ def require_capabilities(built, help_text): raise ValueError(f'{built["label"]} unsupported: required server options missing: {", ".join(missing)}') +def server_flags(built, help_text, server): + """A variant server's own Skippy flags as arguments. They are what the variant measures, so an + arm whose build lacks one stops instead of running as the server it varies.""" + if built["kind"] != "skippy" or "skippy_flags" not in server: + return [] + missing = [name for name in server["skippy_flags"] if not supports(help_text, f"--{name}")] + if missing: + raise ValueError(f'{built["label"]} unsupported: {server["id"]} needs ' + f'{", ".join("--" + name for name in missing)}') + return [(f"--{name}", value) for name, value in server["skippy_flags"].items()] + + def server_args(built, help_text, model, coordinate, context, server): require_capabilities(built, help_text) lanes, pool = server["lanes"], server["pool_tokens"] @@ -120,6 +132,9 @@ def server_args(built, help_text, model, coordinate, context, server): continue args += [flag] if value is None else [flag, str(value)] applied[flag.removeprefix("--").replace("-", "_")] = True if value is None else value + for flag, value in server_flags(built, help_text, server): + args += [flag, str(value)] + applied[flag.removeprefix("--").replace("-", "_")] = value return args, applied, missing diff --git a/scripts/lib/performance_plan.py b/scripts/lib/performance_plan.py index a4999eb5..fdcee6ea 100644 --- a/scripts/lib/performance_plan.py +++ b/scripts/lib/performance_plan.py @@ -20,6 +20,12 @@ NODE = re.compile(r"[A-Za-z0-9._-]{1,64}") MAX_ROUNDS = 9 POINT_FIELDS = {"id", "concurrency", "depth", "input_tokens", "output_tokens", "requests"} +SERVER_FIELDS = {"id", "lanes", "pool_tokens", "points"} +SKIPPY_FLAG = re.compile(r"[a-z][a-z0-9]*(?:-[a-z0-9]+)*") +FLAG_VALUE = re.compile(r"[A-Za-z0-9._,:-]{1,64}") +# server_args sets these on every Skippy arm, so a variant's own flags cannot change them +HARNESS_FLAGS = {"startup-timeout-secs", "ctx-size", "n-gpu-layers", "bind-addr", "model-path", "model-id", + "generation-concurrency", "speculative-strategy", "kv-pool-tokens", "debug", "telemetry-level"} def count(value, name, minimum=1): @@ -28,19 +34,36 @@ def count(value, name, minimum=1): return value +def skippy_flags(server): + """A variant server's own Skippy flags: names without the dashes, positive counts or short words.""" + flags = server["skippy_flags"] + if type(flags) is not dict or not flags: + raise ValueError(f'{server["id"]}: skippy_flags must name at least one flag') + for name, value in flags.items(): + if not SKIPPY_FLAG.fullmatch(name) or name in HARNESS_FLAGS: + raise ValueError(f'{server["id"]}: --{name} is not a flag a variant may set') + if not (type(value) is int and value >= 1 or type(value) is str and FLAG_VALUE.fullmatch(value)): + raise ValueError(f'{server["id"]}: --{name} needs a positive integer or a short word') + return flags + + def scenario(named=None): """The checked scenario; with `named`, only those servers and their points, to rerun one - workload without the rest.""" + workload without the rest. A server with its own `skippy_flags` is a variant of another, + run only when named, so a campaign keeps the same cells.""" value = read_json(SCENARIO) if (set(value) != {"schema_version", "context_per_lane", "warmup_requests", "servers"} or value["schema_version"] != 1 or not value["servers"]): raise ValueError("invalid performance scenario") context = count(value["context_per_lane"], "context_per_lane") count(value["warmup_requests"], "warmup_requests", 0) - servers, points = set(), set() + servers, points, variants = set(), set(), set() for server in value["servers"]: - if set(server) != {"id", "lanes", "pool_tokens", "points"} or not server["points"]: + if set(server) - {"skippy_flags"} != SERVER_FIELDS or not server["points"]: raise ValueError("invalid performance server") + if "skippy_flags" in server: + skippy_flags(server) + variants.add(server["id"]) if server["id"] in servers: raise ValueError(f'duplicate performance server: {server["id"]}') servers.add(server["id"]) @@ -58,12 +81,12 @@ def scenario(named=None): raise ValueError(f'{point["id"]}: concurrency exceeds the server\'s lanes') if point["depth"] + point["input_tokens"] + point["output_tokens"] > context: raise ValueError(f'{point["id"]}: one request exceeds a lane\'s context') - if named is not None: - unknown = set(named) - servers - if not named or unknown: - raise ValueError(f"unknown performance servers: {', '.join(sorted(unknown)) or 'none named'}") - value = {**value, "servers": [server for server in value["servers"] if server["id"] in named]} - return value + if named is None: + return {**value, "servers": [server for server in value["servers"] if server["id"] not in variants]} + unknown = set(named) - servers + if not named or unknown: + raise ValueError(f"unknown performance servers: {', '.join(sorted(unknown)) or 'none named'}") + return {**value, "servers": [server for server in value["servers"] if server["id"] in named]} def pull_request_number(ref): diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index ee216df6..116f547d 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -43,6 +43,22 @@ def test_named_servers_keep_only_their_points(self): with self.assertRaises(ValueError): performance_plan.scenario(names) + def test_a_variant_server_runs_only_when_named(self): + variant = "lanes4-pool32k-prefill2048" + self.assertNotIn(variant, [server["id"] for server in performance_plan.scenario()["servers"]]) + named = performance_plan.scenario(["lanes4-pool32k", variant])["servers"] + self.assertEqual([server["id"] for server in named], ["lanes4-pool32k", variant]) + + def test_a_variant_cannot_set_what_the_harness_sets_or_nothing(self): + shape = performance_plan.read_json(performance_plan.SCENARIO) + for flags in ({}, {"debug": 1}, {"kv-pool-tokens": 4096}, {"Prefill Chunk": 1}, + {"prefill-chunk-size": 0}, {"prefill-chunk-size": "two words"}, []): + broken = json.loads(json.dumps(shape)) + broken["servers"][0]["skippy_flags"] = flags + with patch.object(performance_plan, "read_json", return_value=broken): + with self.assertRaises(ValueError): + performance_plan.scenario() + class PlanTests(unittest.TestCase): candidate, baseline, pin = "a" * 40, "b" * 40, "c" * 40 @@ -238,6 +254,20 @@ def test_required_options_are_probed_before_any_measured_round(self): with self.assertRaisesRegex(ValueError, "unsupported"): server_args(self.skippy, help_text, "/m.gguf", "org/m@rev", 8192, self.server) + def test_a_variant_passes_its_flags_to_skippy_only_and_needs_them(self): + variant = dict(self.server, id="v", skippy_flags={"prefill-chunk-size": 2048, "microbatch-size": 2048}) + help_text = " ".join(REQUIRED) + " --prefill-chunk-size --microbatch-size \n" + args, applied, _ = server_args(self.skippy, help_text, "/m.gguf", "org/m@rev", 8192, variant) + self.assertEqual(args[args.index("--prefill-chunk-size") + 1], "2048") + self.assertEqual(args[args.index("--microbatch-size") + 1], "2048") + self.assertEqual(applied["microbatch_size"], 2048) + reference = {"label": "reference", "kind": "llama-server", "binary": "/b/llama-server"} + args, _, _ = server_args(reference, "", "/m.gguf", "org/m@rev", 8192, variant) + self.assertNotIn("--prefill-chunk-size", args) + with self.assertRaisesRegex(ValueError, "unsupported.*--microbatch-size"): + server_args(self.skippy, " ".join(REQUIRED) + " --prefill-chunk-size ", "/m.gguf", + "org/m@rev", 8192, variant) + def test_llama_server_gets_the_same_cells(self): built = {"label": "reference", "kind": "llama-server", "binary": "/b/llama-server"} args, applied, _ = server_args(built, "", "/m.gguf", "org/m@rev", 8192, self.server) From 0f6cbec5c8ba8ea9840ebcfdc2add1136d884e05 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Fri, 27 Nov 2026 15:26:26 +1100 Subject: [PATCH 19/50] Measure llama.cpp at both pins when a change moves the pin A Skippy change that moves the llama.cpp pin compares two llama.cpp builds as well as two Skippy builds, so llama-server at only the candidate's pin cannot say whether a regression is Skippy's or llama.cpp's. The baseline's pin now joins as baseline-reference, and the report compares the two references beside the candidate and baseline. --- scripts/inference-performance.py | 6 ++- scripts/lib/performance_plan.py | 21 +++++++--- scripts/lib/performance_report.py | 42 +++++++++++++------ .../tests/inference_performance_contracts.py | 23 ++++++++++ 4 files changed, 72 insertions(+), 20 deletions(-) diff --git a/scripts/inference-performance.py b/scripts/inference-performance.py index f10eda4e..2ef47e32 100644 --- a/scripts/inference-performance.py +++ b/scripts/inference-performance.py @@ -102,7 +102,8 @@ def admit(evidence): with_reference = os.environ.get("REFERENCE", "true") == "true" trace = os.environ.get("TRACE", "false") == "true" backend = os.environ.get("BACKEND") or "metal" - arm_list = arms(candidate, baseline, reference_pin(candidate) if with_reference else None) + arm_list = (arms(candidate, baseline, reference_pin(candidate), reference_pin(baseline)) if with_reference + else arms(candidate, baseline, None)) keys = models([key.strip() for key in os.environ["MODELS"].split(",") if key.strip()]) pins = nodes([node.strip() for node in os.environ.get("NODES", "").split(",") if node.strip()]) rounds = int(os.environ.get("ROUNDS") or 3) @@ -234,7 +235,8 @@ def native_plan(): if capture(["git", "rev-parse", "HEAD"]).strip() != plan["harness"]: raise ValueError("harness checkout differs from the admitted harness commit") labels = {arm["label"]: arm["sha"] for arm in plan["arms"]} - expected = arms(labels["candidate"], labels["baseline"], labels.get("reference")) + expected = arms(labels["candidate"], labels["baseline"], labels.get("reference"), + labels.get("baseline-reference")) if plan.get("backend") not in BACKENDS: raise ValueError(f'performance plan backend {plan.get("backend")!r} has no entry in the table') if (plan["arms"] != expected or plan["models"] != models(plan["models"]) diff --git a/scripts/lib/performance_plan.py b/scripts/lib/performance_plan.py index fdcee6ea..246dadbd 100644 --- a/scripts/lib/performance_plan.py +++ b/scripts/lib/performance_plan.py @@ -108,16 +108,25 @@ def pull_request_head(pull, repository): return pull["head"]["sha"] -def arms(candidate, baseline, reference): - """Candidate and baseline are Skippy commits; reference is llama.cpp's own server at its pin.""" +def arms(candidate, baseline, reference, baseline_reference=None): + """Candidate and baseline are Skippy commits; reference is llama.cpp's own server at the candidate's + pin. A baseline on another pin adds llama.cpp at that pin as baseline-reference, so a change that + moves the pin shows whether llama.cpp moved as well as whether Skippy did.""" if not SHA.fullmatch(candidate) or not SHA.fullmatch(baseline): raise ValueError("arms must be immutable 40-digit commit SHAs") result = [{"label": "candidate", "kind": "skippy", "sha": candidate, "path": "candidate"}, {"label": "baseline", "kind": "skippy", "sha": baseline, "path": "baseline"}] - if reference is not None: - if not SHA.fullmatch(reference): - raise ValueError("the reference pin must be a 40-digit llama.cpp commit") - result.append({"label": "reference", "kind": "llama-server", "sha": reference, "path": "reference"}) + pins = [("reference", reference)] + if baseline_reference not in (None, reference): + if reference is None: + raise ValueError("a baseline reference needs the reference arm") + pins.append(("baseline-reference", baseline_reference)) + for label, pin in pins: + if pin is None: + continue + if not SHA.fullmatch(pin): + raise ValueError(f"the {label} pin must be a 40-digit llama.cpp commit") + result.append({"label": label, "kind": "llama-server", "sha": pin, "path": label}) return result diff --git a/scripts/lib/performance_report.py b/scripts/lib/performance_report.py index 99408362..2fa9812f 100644 --- a/scripts/lib/performance_report.py +++ b/scripts/lib/performance_report.py @@ -11,6 +11,8 @@ # Higher is better for rates; lower is better for latencies. HEADLINE = {"output_tok_s": "higher", "ttft_ms_p50": "lower", "itl_ms_p50": "lower"} +ARM_TITLES = {"baseline": "Baseline", "candidate": "Candidate", "reference": "Reference", + "baseline-reference": "Baseline reference"} def summarize(samples): @@ -34,7 +36,9 @@ def summarize(samples): "n": len(values)} for arm, values in sorted(by_arm.items())} rows.append({"model": model, "server": server, "point": point, "metric": metric, "arms": arms, "rejected": rejected.get((model, server, point), {}), - "candidate_vs_baseline": change(arms.get("candidate"), arms.get("baseline"))}) + "candidate_vs_baseline": change(arms.get("candidate"), arms.get("baseline")), + "reference_vs_baseline_reference": change(arms.get("reference"), + arms.get("baseline-reference"))}) return rows @@ -54,16 +58,23 @@ def cell(stats, rejected): return f"{measured}; rejected n={rejected}" if rejected else measured -def verdict(row): - delta = row["candidate_vs_baseline"] - if delta is None: - return "New series" - arms = row["arms"] - result = classify(row["metric"], arms["candidate"]["median"], arms["baseline"]["median"]) +def described(row, delta, measured, previous): + result = classify(row["metric"], row["arms"][measured]["median"], row["arms"][previous]["median"]) overlap = "; round ranges overlap" if delta["ranges_overlap"] else "; round ranges do not overlap" return f'{delta["percent"]:+.2f}% · {HEALTH_LABELS[result]}{overlap}' +def verdict(row): + delta = row["candidate_vs_baseline"] + return "New series" if delta is None else described(row, delta, "candidate", "baseline") + + +def llama_change(row): + """llama.cpp at the candidate's pin against the baseline's: moving with Skippy means llama.cpp moved.""" + delta = row["reference_vs_baseline_reference"] + return "—" if delta is None else described(row, delta, "reference", "baseline-reference") + + def report_view(host, rows, record): """Adapt real controlled measurements to the common inference health report.""" candidate = next(arm for arm in record["arms"] if arm["label"] == "candidate") @@ -81,8 +92,8 @@ def report_view(host, rows, record): arms = row["arms"] metric = {"metric": row["metric"], "workload": configuration["workload"], "measured": arms["candidate"]["median"], - "comparison_arms": [(label.title(), arms[label]["median"]) - for label in ("baseline", "candidate", "reference") if label in arms]} + "comparison_arms": [(title, arms[label]["median"]) + for label, title in ARM_TITLES.items() if label in arms]} if "baseline" in arms: metric["reference"] = {"value": arms["baseline"]["median"]} configuration["metrics"].append(metric) @@ -100,14 +111,21 @@ def markdown(title, host, rows, record): "Its measurements are shown separately from the candidate/baseline verdict. " "Rejected is the number of rounds in which its server failed requests at a point " "that needs more KV than its pool holds.", ""] + pinned = any("baseline-reference" in row["arms"] for row in rows) + if pinned: + lines += ["The candidate moves the llama.cpp pin, so Baseline reference is llama.cpp at the " + "baseline's pin, and llama.cpp change compares the two references: a change in both " + "columns is llama.cpp's, a change in Change alone is Skippy's.", ""] + shown = [label for label in ARM_TITLES if pinned or label != "baseline-reference"] detail = [] for row in rows: if row["metric"] in HEADLINE: arms = row["arms"] detail.append([plain(row[field]) for field in ("model", "server", "point", "metric")] + - [cell(arms.get(arm), row["rejected"].get(arm, 0)) - for arm in ("baseline", "candidate", "reference")] + [verdict(row)]) - lines.extend(table(["Model", "Server", "Point", "Metric", "Baseline", "Candidate", "Reference", "Change"], detail)) + [cell(arms.get(arm), row["rejected"].get(arm, 0)) for arm in shown] + [verdict(row)] + + ([llama_change(row)] if pinned else [])) + lines.extend(table(["Model", "Server", "Point", "Metric", *(ARM_TITLES[arm] for arm in shown), "Change", + *(["llama.cpp change"] if pinned else [])], detail)) return "\n".join(lines) + "\n" diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index 116f547d..fb5f4d33 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -66,6 +66,13 @@ class PlanTests(unittest.TestCase): def test_arms_are_immutable_commits_and_reference_is_optional(self): labels = [arm["label"] for arm in performance_plan.arms(self.candidate, self.baseline, self.pin)] self.assertEqual(labels, ["candidate", "baseline", "reference"]) + same = performance_plan.arms(self.candidate, self.baseline, self.pin, self.pin) + self.assertEqual([arm["label"] for arm in same], labels) + moved = performance_plan.arms(self.candidate, self.baseline, self.pin, "d" * 40) + self.assertEqual([(arm["label"], arm["sha"]) for arm in moved[2:]], + [("reference", self.pin), ("baseline-reference", "d" * 40)]) + with self.assertRaises(ValueError): + performance_plan.arms(self.candidate, self.baseline, None, "d" * 40) self.assertEqual(len(performance_plan.arms(self.candidate, self.candidate, None)), 2) for bad in ("main", "a" * 39): with self.assertRaises(ValueError): @@ -505,6 +512,22 @@ def sample(arm, value): self.assertIn("+20.00% · Improved", markdown("t", "h", rows, self.record)) close = summarize([sample("baseline", v) for v in (100, 110)] + [sample("candidate", v) for v in (105, 108)]) self.assertIn("round ranges overlap", markdown("t", "h", close, self.record)) + self.assertNotIn("llama.cpp change", markdown("t", "h", rows, self.record)) + + def test_a_moved_pin_says_whether_llama_cpp_moved_too(self): + def sample(arm, value): + return {"model": "m", "server": "s", "point": "p", "arm": arm, "metrics": {"output_tok_s": value}, + "rejected": None} + + rows = summarize([sample(arm, v) for arm, values in (("baseline", (100, 101, 99)), + ("candidate", (90, 91, 89)), + ("baseline-reference", (200, 201, 199)), + ("reference", (180, 181, 179))) + for v in values]) + self.assertAlmostEqual(rows[0]["reference_vs_baseline_reference"]["percent"], -10.0) + report = markdown("t", "h", rows, self.record) + self.assertIn("| Baseline reference | Change | llama.cpp change |", report) + self.assertIn("-10.00% · Regressed", performance_report.llama_change(rows[0])) def test_one_percent_rule_keeps_range_uncertainty_and_actual_p50_labels(self): def row(metric, candidate): From 80b4641f7bbcab52d3667b55d27fc77de21189a5 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Fri, 27 Nov 2026 16:15:34 +1100 Subject: [PATCH 20/50] Collect a performance job with the servers its plan named A plan that names a variant server measures points the default scenario leaves out, so collecting with the default scenario could not find them. --- scripts/inference-performance.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/inference-performance.py b/scripts/inference-performance.py index 2ef47e32..ce1aa59b 100644 --- a/scripts/inference-performance.py +++ b/scripts/inference-performance.py @@ -184,8 +184,8 @@ def collect(pilot, job, plan, label, evidence): write_json(evidence / f"{label}-performance.json", result) (evidence / f"{label}-rows.jsonl").write_text( "".join(json.dumps(row, sort_keys=True) + "\n" - for row in rows(result, scenario(), plan["committed_at"], job["id"], plan["pull_requests"], - plan.get("branches"))), + for row in rows(result, scenario(plan.get("servers")), plan["committed_at"], job["id"], + plan["pull_requests"], plan.get("branches"))), encoding="utf-8") if plan["trace"]: download(pilot, run_id, "traces.tar.gz", evidence / f"{label}-traces.tar.gz") From df0406a7889aa9af63a22c9298157b933a22e4d9 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Fri, 27 Nov 2026 17:54:31 +1100 Subject: [PATCH 21/50] Run a performance job as steps that report their progress Each arm builds, and each server, round and trace pass runs, as its own step of the job's command, which writes the percent of the job's expected time spent after each one. --- Justfile | 13 +- ci/INFERENCE_PERFORMANCE.md | 9 + ci/inference-performance.json | 36 ++++ scripts/inference-performance.py | 157 +++++++++++------- scripts/lib/performance_plan.py | 60 ++++++- .../tests/inference_performance_contracts.py | 21 +++ 6 files changed, 231 insertions(+), 65 deletions(-) diff --git a/Justfile b/Justfile index 01be0c90..66a551e7 100644 --- a/Justfile +++ b/Justfile @@ -239,12 +239,17 @@ inference-performance-dispatch evidence="target/ci-evidence/inference-performanc inference-performance-cancel ledger="target/ci-evidence/inference-performance/jobs.json": @"{{ automation_python }}" scripts/inference-performance.py cancel "$@" -inference-performance-build: +# The steps of a performance job, in the order its command runs them. +inference-performance-toolcheck: @command -v hf uv cmake ninja cargo && {{ automation_python }} scripts/inference-performance.py toolcheck - @"{{ automation_python }}" scripts/inference-performance.py build -inference-performance-execute: - @"{{ automation_python }}" scripts/inference-performance.py execute +[positional-arguments] +inference-performance-build-arm arm: + @"{{ automation_python }}" scripts/inference-performance.py build "$@" + +[positional-arguments] +inference-performance-step +args: + @"{{ automation_python }}" scripts/inference-performance.py step "$@" # Linux diagnostic: retain all MiMo2 graph assertions and report peak memory. native-contract-build: llama-prepare diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index 9cb4f7b2..c8a1d6a1 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -111,6 +111,15 @@ one host, never across hosts. The job refuses to run as root. `ci/inference-performance.json`, then drives each of its points with the pinned AIPerf. +Each of these is a step of its own in the job's command (`just +inference-performance-build-arm` per arm, then `just inference-performance-step` +for the start, each model, each arm's server in each round, each trace pass and +the final archive), and after each the command writes the percent of the job's +expected time spent to `$JIANYANG_PROGRESS_PATH`, with what just finished. The +expected times are rough: fifteen minutes for a Skippy build, five for +`llama-server`, and half a minute per server start plus two seconds per request. +A failed step names itself on stderr and the archive still runs. + The scenario covers one request at a time, four lanes with short and long output, sixteen lanes with and without a 4,096-token shared prefix in a 32K pool, and four lanes at that depth with 16K and 32K pools: the cells where KV diff --git a/ci/inference-performance.json b/ci/inference-performance.json index 5b913c9d..863c93cf 100644 --- a/ci/inference-performance.json +++ b/ci/inference-performance.json @@ -53,6 +53,42 @@ "points": [ {"id": "c4-depth4096-pool32k-prefill2048", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 16} ] + }, + { + "id": "lanes4-pool32k-prompt-order", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"batch-policy": "prompt_order"}, + "points": [ + {"id": "c4-depth4096-pool32k-prompt-order", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 16} + ] + }, + { + "id": "lanes4-pool32k-prompt-order2", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"batch-policy": "prompt_order", "batch-prefill-prompts": 2}, + "points": [ + {"id": "c4-depth4096-pool32k-prompt-order2", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 16} + ] + }, + { + "id": "lanes4-pool32k-prompt-order-active", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"batch-policy": "prompt_order", "batch-prefill-wait": "active"}, + "points": [ + {"id": "c4-depth4096-pool32k-prompt-order-active", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 16} + ] + }, + { + "id": "lanes4-pool32k-prompt-order-separate", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"batch-policy": "prompt_order", "batch-mixing": "separate"}, + "points": [ + {"id": "c4-depth4096-pool32k-prompt-order-separate", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 16} + ] } ] } diff --git a/scripts/inference-performance.py b/scripts/inference-performance.py index ce1aa59b..16e9273f 100644 --- a/scripts/inference-performance.py +++ b/scripts/inference-performance.py @@ -28,13 +28,18 @@ from lib.performance_backends import BACKENDS from lib.performance_load import run_point, tokenizer from lib.performance_plan import (SCENARIO, arms, branch_name, job_spec, models, nodes, pull_request_head, - pull_request_number, round_order, scenario) + pull_request_number, scenario) from lib.performance_report import markdown, rows, summarize REPO = "Mesh-LLM/skippy" LLAMA_REPO = "ggml-org/llama.cpp" WORK = Path("target/inference-performance") -BUILT = WORK / "built.json" +# One file per arm, as each arm builds in a job step of its own. +BUILT = WORK / "built" +# What the steps after `start` and `model` read back: each arm's options, each admitted model. +HELPS = WORK / "helps.json" +MODELS = WORK / "models" +RECORD = "performance.json" # Outside the artifact directory: artifact names are flat, so the traces travel as one archive. TRACES = WORK / "traces" TERMINAL = {"succeeded", "failed", "cancelled", "expired"} @@ -254,20 +259,19 @@ def toolcheck(): command(check, timeout=120, capture_stdout=True) -def build_arms(): +def build_arm(label): plan = native_plan() - WORK.mkdir(parents=True, exist_ok=True) + arm = next((arm for arm in plan["arms"] if arm["label"] == label), None) + if arm is None: + raise ValueError(f"{label} is not an arm of the admitted plan") + BUILT.mkdir(parents=True, exist_ok=True) + log = WORK / f"build-{label}.log" try: - write_json(BUILT, [build(arm, WORK / f'build-{arm["label"]}.log', plan["backend"]) - for arm in plan["arms"]]) + write_json(BUILT / f"{label}.json", build(arm, log, plan["backend"])) finally: - # execute() is the only other place build logs reach the artifact - # directory, and it never runs after a build failure. - output = os.environ.get("JIANYANG_ARTIFACT_DIR") - if output: - Path(output).mkdir(parents=True, exist_ok=True) - for log in WORK.glob("build-*.log"): - (Path(output) / log.name).write_bytes(log.read_bytes()) + # Copied at once, failed or not: a failed build ends the job. + if log.is_file(): + (artifacts() / log.name).write_bytes(log.read_bytes()) def ready(server, seconds): @@ -326,26 +330,30 @@ def measure(built, help_text, model, inputs, key, index, server, shape, output, return samples -def execute(): +def artifacts(): + output = Path(os.environ["JIANYANG_ARTIFACT_DIR"]) + output.mkdir(parents=True, exist_ok=True) + return output + + +def start_measurement(): + """Check every arm before any round, so a variant whose flag an arm lacks fails before + anything is measured, and write the record the later steps add to.""" if os.geteuid() == 0: raise ValueError("native inference must not execute as root") plan = native_plan() entry = BACKENDS[plan["backend"]] - built = read_json(BUILT) + built = [read_json(BUILT / f'{arm["label"]}.json') for arm in plan["arms"]] if [(arm["label"], arm["sha"]) for arm in built] != [(arm["label"], arm["sha"]) for arm in plan["arms"]]: raise ValueError("built arms differ from the admitted plan") for arm in built: if digest(Path(arm["binary"])) != arm["binary_sha256"]: raise ValueError(f'{arm["label"]} binary changed after it was built') - output = Path(os.environ["JIANYANG_ARTIFACT_DIR"]) - output.mkdir(parents=True, exist_ok=True) - for log in WORK.glob("build-*.log"): - (output / log.name).write_bytes(log.read_bytes()) - shape, helps = scenario(plan.get("servers")), {entry["label"]: capabilities(entry) for entry in built} - # before any round, so a variant whose flag an arm lacks fails before it measures anything + shape, helps = scenario(plan.get("servers")), {arm["label"]: capabilities(arm) for arm in built} for arm in built: for server in shape["servers"]: server_flags(arm, helps[arm["label"]], server) + write_json(HELPS, helps) record = {"schema_version": 1, "harness": plan["harness"], "scenario_sha256": digest(SCENARIO), "started_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), "host": {"node": os.environ.get("JIANYANG_NODE"), "backend": plan["backend"], @@ -355,39 +363,55 @@ def execute(): # Tracing slows the arm it runs on, so its samples never join the comparison. record["diagnostic"] = {"telemetry": "debug", "arm": "candidate", "samples": []} TRACES.mkdir(parents=True, exist_ok=True) - try: - for key in plan["models"]: - inputs = fixture(key) - available = entry["free_memory"](record["host"]) - reserve = entry["reserve_gib"] * 1024**3 - if available < sum(file["size"] for file in inputs["files"]) + reserve: - raise ValueError(f"{key}: insufficient {plan['backend']} free memory for weights and reserve") - model = admit_model(key, inputs) - inputs = {**inputs, "tokenizer_path": tokenizer(inputs)} - record["models"][key] = {"repo": inputs["repo"], "revision": inputs["revision"], - "files": inputs["files"]} - for index in range(plan["rounds"]): - for arm in round_order(built, index): - for server in shape["servers"]: - record["samples"] += measure(arm, helps[arm["label"]], model, inputs, key, - index, server, shape, output, - prefixes=entry["device_prefixes"]) - write_json(output / "performance.json", record) - if plan["trace"]: - candidate = next(arm for arm in built if arm["label"] == "candidate") - for server in shape["servers"]: - record["diagnostic"]["samples"] += measure( - candidate, helps["candidate"], model, inputs, key, None, server, shape, output, - trace=TRACES / f'{key}-{server["id"]}', prefixes=entry["device_prefixes"]) - write_json(output / "performance.json", record) - finally: - write_json(output / "performance.json", record) - if (WORK / "aiperf").is_dir(): - with tarfile.open(output / "aiperf.tar.gz", "w:gz") as archive: - archive.add(WORK / "aiperf", arcname="aiperf") - if TRACES.is_dir(): - with tarfile.open(output / "traces.tar.gz", "w:gz") as archive: - archive.add(TRACES, arcname="traces") + write_json(artifacts() / RECORD, record) + + +def prepare_model(key): + plan = native_plan() + if key not in plan["models"]: + raise ValueError(f"{key} is not a model of the admitted plan") + entry, record = BACKENDS[plan["backend"]], read_json(artifacts() / RECORD) + inputs = fixture(key) + available = entry["free_memory"](record["host"]) + if available < sum(file["size"] for file in inputs["files"]) + entry["reserve_gib"] * 1024**3: + raise ValueError(f"{key}: insufficient {plan['backend']} free memory for weights and reserve") + model = admit_model(key, inputs) + inputs = {**inputs, "tokenizer_path": str(tokenizer(inputs))} + record["models"][key] = {"repo": inputs["repo"], "revision": inputs["revision"], "files": inputs["files"]} + MODELS.mkdir(parents=True, exist_ok=True) + write_json(MODELS / f"{key}.json", {"model": str(model), "inputs": inputs}) + write_json(artifacts() / RECORD, record) + + +def measure_step(key, label, server_id, round_number=None): + """One arm on one server for one round, or the candidate's diagnostic pass without a round.""" + plan = native_plan() + shape = scenario(plan.get("servers")) + server = next((server for server in shape["servers"] if server["id"] == server_id), None) + diagnostic = round_number is None + if (server is None or label not in {arm["label"] for arm in plan["arms"]} + or not diagnostic and not 1 <= round_number <= plan["rounds"] + or diagnostic and (not plan["trace"] or label != "candidate")): + raise ValueError(f"{label} on {server_id} is not a step of the admitted plan") + output = artifacts() + record, prepared = read_json(output / RECORD), read_json(MODELS / f"{key}.json") + samples = measure(read_json(BUILT / f"{label}.json"), read_json(HELPS)[label], Path(prepared["model"]), + prepared["inputs"], key, None if diagnostic else round_number - 1, server, shape, + output, trace=TRACES / f"{key}-{server_id}" if diagnostic else None, + prefixes=BACKENDS[plan["backend"]]["device_prefixes"]) + (record["diagnostic"] if diagnostic else record)["samples"] += samples + write_json(output / RECORD, record) + + +def finish_measurement(): + """Archive what the steps measured; the job runs it after a failure too.""" + output = artifacts() + if (WORK / "aiperf").is_dir(): + with tarfile.open(output / "aiperf.tar.gz", "w:gz") as archive: + archive.add(WORK / "aiperf", arcname="aiperf") + if TRACES.is_dir(): + with tarfile.open(output / "traces.tar.gz", "w:gz") as archive: + archive.add(TRACES, arcname="traces") def main(): @@ -397,8 +421,17 @@ def main(): actions.add_parser(name).add_argument("evidence", type=Path) actions.add_parser("cancel").add_argument("ledger", type=Path) actions.add_parser("toolcheck") - actions.add_parser("build") - actions.add_parser("execute") + actions.add_parser("build").add_argument("arm") + step = actions.add_parser("step").add_subparsers(dest="step", required=True) + step.add_parser("start") + step.add_parser("model").add_argument("model") + measured = step.add_parser("measure") + for name in ("model", "round", "arm", "server"): + measured.add_argument(name, type=int if name == "round" else str) + traced_pass = step.add_parser("trace") + for name in ("model", "server"): + traced_pass.add_argument(name) + step.add_parser("finish") args = parser.parse_args() if args.action == "admit": admit(args.evidence) @@ -409,9 +442,17 @@ def main(): elif args.action == "toolcheck": toolcheck() elif args.action == "build": - build_arms() + build_arm(args.arm) + elif args.step == "start": + start_measurement() + elif args.step == "model": + prepare_model(args.model) + elif args.step == "measure": + measure_step(args.model, args.arm, args.server, args.round) + elif args.step == "trace": + measure_step(args.model, "candidate", args.server) else: - execute() + finish_measurement() if __name__ == "__main__": diff --git a/scripts/lib/performance_plan.py b/scripts/lib/performance_plan.py index 246dadbd..8711b63b 100644 --- a/scripts/lib/performance_plan.py +++ b/scripts/lib/performance_plan.py @@ -3,6 +3,7 @@ import json import math import re +import shlex from pathlib import Path from .ci_artifacts import digest, read_json @@ -26,6 +27,11 @@ # server_args sets these on every Skippy arm, so a variant's own flags cannot change them HARNESS_FLAGS = {"startup-timeout-secs", "ctx-size", "n-gpu-layers", "bind-addr", "model-path", "model-id", "generation-concurrency", "speculative-strategy", "kv-pool-tokens", "debug", "telemetry-level"} +# What a step is expected to take, in minutes, so the job's progress follows time rather than step count. +BUILD_MINUTES = {"skippy": 15, "llama-server": 5} +NOTE = re.compile(r"[A-Za-z0-9 ._:+-]{1,59}") +PROGRESS = ("progress() { printf '%s%% %s\\n' \"$1\" \"$2\" > \"$JIANYANG_PROGRESS_PATH\"; " + "echo \"PROGRESS ${JIANYANG_NODE:-?} $(date +%T) $1% $2\"; }") def count(value, name, minimum=1): @@ -136,6 +142,53 @@ def round_order(arm_list, index): return arm_list[shift:] + arm_list[:shift] +def measure_minutes(server): + """A server's start and its points' requests, about two seconds each at the scenario's loads.""" + return 0.5 + sum(point["requests"] for point in server["points"]) * 2 / 60 + + +def job_steps(arm_list, keys, rounds, servers, trace): + """The job's commands in the order they run: each a `just` recipe and its arguments, what it + finishes, and the minutes it is expected to take.""" + steps = [(["inference-performance-toolcheck"], "tools checked", 0.2)] + steps += [(["inference-performance-build-arm", arm["label"]], f'{arm["label"]} built', + BUILD_MINUTES[arm["kind"]]) for arm in arm_list] + steps.append((["inference-performance-step", "start"], "measurement ready", 0.3)) + for key in keys: + steps.append((["inference-performance-step", "model", key], f"{key} admitted", 1)) + for index in range(rounds): + for arm in round_order(arm_list, index): + steps += [(["inference-performance-step", "measure", key, str(index + 1), arm["label"], + server["id"]], f'r{index + 1} {arm["label"]} {server["id"]}', + measure_minutes(server)) for server in servers] + if trace: + steps += [(["inference-performance-step", "trace", key, server["id"]], f'trace {server["id"]}', + measure_minutes(server) * 1.5) for server in servers] + steps.append((["inference-performance-step", "finish"], "evidence archived", 0.5)) + return steps + + +def job_command(steps): + """A shell script that runs `steps` from the harness checkout and reports progress after each: + the percent of the expected time spent, never falling, and 100 only once all have run. A + failure names the command that stopped it and still archives what was measured.""" + total = sum(minutes for _, _, minutes in steps) + lines = ["set -euo pipefail", PROGRESS, + "trap 'echo \"inference performance stopped at: $BASH_COMMAND\" >&2' ERR", + "trap 'status=$?; if [ \"$status\" -ne 0 ]; then just inference-performance-step finish " + ">/dev/null 2>&1 || true; fi' EXIT", + 'progress 0 "starting"', "cd harness"] + spent = 0 + for args, note, minutes in steps: + note = note[:59] + if not NOTE.fullmatch(note): + raise ValueError(f"progress note {note!r} needs letters, digits and . _ : + - only") + spent += minutes + lines += [shlex.join(["just", *args]), f'progress {min(99, math.floor(spent / total * 100))} "{note}"'] + lines.append('progress 100 "done"') + return "\n".join(lines) + "\n" + + def models(keys): known = {model["id"] for model in ladder_models()} if not keys or len(set(keys)) != len(keys) or not set(keys) <= known: @@ -192,11 +245,12 @@ def job_spec(harness, arm_list, keys, rounds, node, label, *, trace=False, backe "runtime": { "model_package": {"ref": "skippy://inference-performance/" + "+".join(keys), "sha256": fixture(keys[0])["files"][0]["sha256"], "egress": "lab_only"}, - "workspace": {"repos": repos, "build": "cd harness && just inference-performance-build", - "retain": "on_failure"}, + # The arms build in the command rather than the workspace build, so + # the job's progress covers its longest steps. + "workspace": {"repos": repos, "retain": "on_failure"}, "env": {"SKIPPY_PERFORMANCE_PLAN": json.dumps(plan, separators=(",", ":")), **entry["env"]}, - "command": "cd harness && just inference-performance-execute", + "command": job_command(job_steps(arm_list, keys, rounds, shape["servers"], trace)), }, "harness": { "name": "custom", "version": "aiperf-0.13.0", diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index fb5f4d33..6b80b440 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -146,6 +146,27 @@ def test_job_runs_every_arm_from_its_own_checkout_on_a_metal_host(self): with self.assertRaises(ValueError): performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], performance_plan.MAX_ROUNDS + 1, None, "x") + def test_the_job_reports_progress_after_every_step_and_ends_at_100(self): + arm_list = performance_plan.arms(self.candidate, self.baseline, self.pin) + spec = performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 3, None, "any", trace=True) + self.assertNotIn("build", spec["runtime"]["workspace"]) + lines = spec["runtime"]["command"].splitlines() + self.assertEqual(lines[0], "set -euo pipefail") + self.assertEqual((lines[4], lines[-1]), ('progress 0 "starting"', 'progress 100 "done"')) + steps = [line for line in lines if line.startswith("just ")] + reports = [line for line in lines if line.startswith("progress ")][1:-1] + self.assertEqual(len(steps), len(reports)) + percents = [int(report.split()[1]) for report in reports] + self.assertEqual(percents, sorted(percents)) + self.assertLess(percents[-1], 100) + self.assertEqual(steps[1:4], [f"just inference-performance-build-arm {arm}" + for arm in ("candidate", "baseline", "reference")]) + measured = [step.split()[5] for step in steps if " measure " in step] + per_round = len(measured) // 3 + # every arm leads one round + self.assertEqual([measured[index * per_round] for index in range(3)], + ["candidate", "baseline", "reference"]) + def test_a_cuda_plan_targets_a_dgx_spark(self): arm_list = performance_plan.arms(self.candidate, self.baseline, self.pin) spec = performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 3, "spark-000137", "sp", From e896fa594850ab4c71123d838373076a58a59413 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Fri, 27 Nov 2026 19:29:08 +1100 Subject: [PATCH 22/50] Let a performance point send requests at a fixed rate Kept in flight, requests that finish together are replaced together, so a closed-loop point keeps waves in step. A point with request_rate sends requests on a seeded Poisson schedule per backend instead, with concurrency only as a ceiling. --- ci/INFERENCE_PERFORMANCE.md | 10 ++++++ ci/inference-performance.json | 27 ++++++++++++++ scripts/inference-performance.py | 9 ++--- scripts/lib/performance_load.py | 24 +++++++++++-- scripts/lib/performance_plan.py | 35 ++++++++++++++----- scripts/lib/performance_report.py | 4 ++- .../tests/inference_performance_contracts.py | 24 ++++++++++++- 7 files changed, 116 insertions(+), 17 deletions(-) diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index c8a1d6a1..3d6a1ae4 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -133,6 +133,16 @@ itself (context, lanes, pool, speculation, telemetry). An arm whose build lacks one of them fails before any round, since without it the variant would measure the server it varies. +A point drives its server one of two ways. By default AIPerf keeps `concurrency` +requests in flight, sending the next as one finishes. Requests that finish together +are then replaced together, so a policy that lets them finish together keeps every +wave as synchronized as the first. A point with `request_rate` instead sends requests +at that many a second, in a Poisson schedule seeded the same for every arm, with +`concurrency` only as a ceiling. The rate is set per backend, at about 60% of what the +slowest arm served with four in flight on the lab's host for it, as each backend's +hardware serves a different rate; a plan for a backend a rate point has no rate for +is refused. + An arm that lacks a setting, such as `--kv-pool-tokens` on a commit from before the pool existed, runs without it. Each sample records what was applied and what the arm did not support. All arms are probed before model measurements begin. diff --git a/ci/inference-performance.json b/ci/inference-performance.json index 863c93cf..d34908b9 100644 --- a/ci/inference-performance.json +++ b/ci/inference-performance.json @@ -89,6 +89,33 @@ "points": [ {"id": "c4-depth4096-pool32k-prompt-order-separate", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 16} ] + }, + { + "id": "lanes4-pool32k-rate", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"batch-policy": "arrival_order"}, + "points": [ + {"id": "rate-depth4096-pool32k", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 24, "request_rate": {"metal": 0.22, "cuda": 0.34, "cuda-x86": 0.9}} + ] + }, + { + "id": "lanes4-pool32k-prompt-order-rate", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"batch-policy": "prompt_order"}, + "points": [ + {"id": "rate-depth4096-pool32k-prompt-order", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 24, "request_rate": {"metal": 0.22, "cuda": 0.34, "cuda-x86": 0.9}} + ] + }, + { + "id": "lanes4-pool32k-prompt-order2-rate", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"batch-policy": "prompt_order", "batch-prefill-prompts": 2}, + "points": [ + {"id": "rate-depth4096-pool32k-prompt-order2", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 24, "request_rate": {"metal": 0.22, "cuda": 0.34, "cuda-x86": 0.9}} + ] } ] } diff --git a/scripts/inference-performance.py b/scripts/inference-performance.py index 16e9273f..1037cb3b 100644 --- a/scripts/inference-performance.py +++ b/scripts/inference-performance.py @@ -26,7 +26,7 @@ from lib.jy_qualification import ORIGIN, Pilot from lib.performance_arms import build, capabilities, may_reject, server_args, server_flags, supports from lib.performance_backends import BACKENDS -from lib.performance_load import run_point, tokenizer +from lib.performance_load import request_rate, run_point, tokenizer from lib.performance_plan import (SCENARIO, arms, branch_name, job_spec, models, nodes, pull_request_head, pull_request_number, scenario) from lib.performance_report import markdown, rows, summarize @@ -299,7 +299,7 @@ def traced(built, help_text, args, applied, missing, trace): def measure(built, help_text, model, inputs, key, index, server, shape, output, trace=None, - prefixes=("MTL",)): + prefixes=("MTL",), backend=None): """`index` is the round, or None for a diagnostic pass that writes `trace`.""" coordinate = f'{inputs["repo"]}@{inputs["revision"]}' args, applied, missing = server_args(built, help_text, model, coordinate, @@ -317,7 +317,8 @@ def measure(built, help_text, model, inputs, key, index, server, shape, output, for point in server["points"]: metrics, rejected = run_point(ENDPOINT, point, coordinate, inputs["tokenizer_path"], shape["warmup_requests"], WORK / "aiperf" / name / point["id"], - may_reject=may_reject(built, server, point)) + may_reject=may_reject(built, server, point), + rate=request_rate(point, backend)) # A rejection is the answer of a server that is still serving; one that died is a fault. if rejected is not None and process.poll() is not None: raise RuntimeError("server exited while it was rejecting requests; inspect its log") @@ -398,7 +399,7 @@ def measure_step(key, label, server_id, round_number=None): samples = measure(read_json(BUILT / f"{label}.json"), read_json(HELPS)[label], Path(prepared["model"]), prepared["inputs"], key, None if diagnostic else round_number - 1, server, shape, output, trace=TRACES / f"{key}-{server_id}" if diagnostic else None, - prefixes=BACKENDS[plan["backend"]]["device_prefixes"]) + prefixes=BACKENDS[plan["backend"]]["device_prefixes"], backend=plan["backend"]) (record["diagnostic"] if diagnostic else record)["samples"] += samples write_json(output / RECORD, record) diff --git a/scripts/lib/performance_load.py b/scripts/lib/performance_load.py index 8f28f0ab..9e027c2c 100644 --- a/scripts/lib/performance_load.py +++ b/scripts/lib/performance_load.py @@ -37,7 +37,19 @@ def tokenizer(fixture): return path -def profile_args(endpoint, point, coordinate, tokenizer_path, warmup, directory): +def request_rate(point, backend): + """A rate point's arrivals per second on `backend`, or None for a point that keeps its + concurrency in flight. A rate is set per backend, as each runs a different share of what + its hardware can serve.""" + rates = point.get("request_rate") + if rates is None: + return None + if backend not in rates: + raise ValueError(f'{point["id"]} has no request rate for the {backend} backend') + return rates[backend] + + +def profile_args(endpoint, point, coordinate, tokenizer_path, warmup, directory, rate=None): args = [ *AIPERF, "--ui", "simple", "--url", endpoint, "--endpoint-type", "chat", "--streaming", # Nothing here reads AIPerf's server metrics or GPU telemetry, and under load their @@ -51,6 +63,11 @@ def profile_args(endpoint, point, coordinate, tokenizer_path, warmup, directory) "--output-tokens-stddev", "0", "--extra-inputs", "ignore_eos:true", "--artifact-dir", str(directory), ] + if rate is not None: + # Requests arrive on their own schedule, seeded so every arm sees the same one, and the + # concurrency is only a ceiling. Kept in flight instead, requests that finish together + # are replaced together, and every later wave queues the way the first one did. + args += ["--request-rate", str(rate), "--arrival-pattern", "poisson"] if point["depth"]: # One shared prefix per concurrent request: each conversation re-reads its own # prefix, so the KV pool has to hold concurrency x depth to keep them resident. @@ -97,7 +114,8 @@ def rejection(directory, requests): for error, count in sorted(failed.items())]} -def run_point(endpoint, point, coordinate, tokenizer_path, warmup, directory: Path, *, may_reject): +def run_point(endpoint, point, coordinate, tokenizer_path, warmup, directory: Path, *, may_reject, + rate=None): """One point's metrics, or null metrics and what the server rejected where it may reject.""" failure = None # AIPerf stages its ZeroMQ event bus under TMPDIR, and the job's own TMPDIR @@ -106,7 +124,7 @@ def run_point(endpoint, point, coordinate, tokenizer_path, warmup, directory: Pa # nesting. Anchor a short, space-free TMPDIR at /tmp instead. short_tmp = Path(tempfile.mkdtemp(prefix="aiperf-tmp-", dir="/tmp")) try: - command(profile_args(endpoint, point, coordinate, tokenizer_path, warmup, directory), + command(profile_args(endpoint, point, coordinate, tokenizer_path, warmup, directory, rate), timeout=5400, overrides={"TMPDIR": str(short_tmp)}) except subprocess.CalledProcessError as error: # AIPerf exits non-zero, with no summary export, when every measured request failed. diff --git a/scripts/lib/performance_plan.py b/scripts/lib/performance_plan.py index 8711b63b..79c72785 100644 --- a/scripts/lib/performance_plan.py +++ b/scripts/lib/performance_plan.py @@ -10,6 +10,7 @@ from .inference_inputs import fixture from .inference_ladder import ladder_models from .performance_backends import BACKENDS +from .performance_load import request_rate ROOT = Path(__file__).resolve().parents[2] SCENARIO = ROOT / "ci/inference-performance.json" @@ -53,6 +54,15 @@ def skippy_flags(server): return flags +def rates(point): + """A point's per-backend arrivals per second, each a positive number for a backend in the table.""" + value = point["request_rate"] + if (type(value) is not dict or not value or not set(value) <= set(BACKENDS) + or not all(type(rate) in {int, float} and 0 < rate <= 100 for rate in value.values())): + raise ValueError(f'{point["id"]}: request_rate maps backends to positive arrivals per second') + return value + + def scenario(named=None): """The checked scenario; with `named`, only those servers and their points, to rerun one workload without the rest. A server with its own `skippy_flags` is a variant of another, @@ -77,8 +87,10 @@ def scenario(named=None): if server["pool_tokens"] is not None and count(server["pool_tokens"], "pool_tokens") < context: raise ValueError(f'{server["id"]}: a KV pool must hold at least one lane\'s context') for point in server["points"]: - if set(point) != POINT_FIELDS or point["id"] in points: + if set(point) - {"request_rate"} != POINT_FIELDS or point["id"] in points: raise ValueError("invalid or duplicate performance point") + if "request_rate" in point: + rates(point) points.add(point["id"]) for field in ("concurrency", "input_tokens", "output_tokens", "requests"): count(point[field], f'{point["id"]} {field}') @@ -142,12 +154,16 @@ def round_order(arm_list, index): return arm_list[shift:] + arm_list[:shift] -def measure_minutes(server): - """A server's start and its points' requests, about two seconds each at the scenario's loads.""" - return 0.5 + sum(point["requests"] for point in server["points"]) * 2 / 60 +def measure_minutes(server, backend): + """A server's start and its points' requests: about two seconds each when kept in flight, + and as long as their arrivals take at a point's own rate.""" + def seconds(point): + rate = request_rate(point, backend) + return point["requests"] * 2 if rate is None else point["requests"] / rate + 10 + return 0.5 + sum(seconds(point) for point in server["points"]) / 60 -def job_steps(arm_list, keys, rounds, servers, trace): +def job_steps(arm_list, keys, rounds, servers, trace, backend): """The job's commands in the order they run: each a `just` recipe and its arguments, what it finishes, and the minutes it is expected to take.""" steps = [(["inference-performance-toolcheck"], "tools checked", 0.2)] @@ -160,10 +176,10 @@ def job_steps(arm_list, keys, rounds, servers, trace): for arm in round_order(arm_list, index): steps += [(["inference-performance-step", "measure", key, str(index + 1), arm["label"], server["id"]], f'r{index + 1} {arm["label"]} {server["id"]}', - measure_minutes(server)) for server in servers] + measure_minutes(server, backend)) for server in servers] if trace: steps += [(["inference-performance-step", "trace", key, server["id"]], f'trace {server["id"]}', - measure_minutes(server) * 1.5) for server in servers] + measure_minutes(server, backend) * 1.5) for server in servers] steps.append((["inference-performance-step", "finish"], "evidence archived", 0.5)) return steps @@ -214,6 +230,9 @@ def job_spec(harness, arm_list, keys, rounds, node, label, *, trace=False, backe raise ValueError(f"unknown backend {backend!r}; the table holds {', '.join(sorted(BACKENDS))}") shape = scenario(servers) entry = BACKENDS[backend] + for server in shape["servers"]: + for point in server["points"]: + request_rate(point, backend) if entry["pin_required"] and node is None: raise ValueError(f"a {backend} plan must name exactly one node: its GPUs differ between hosts") largest = max(sum(file["size"] for file in fixture(key)["files"]) for key in keys) @@ -250,7 +269,7 @@ def job_spec(harness, arm_list, keys, rounds, node, label, *, trace=False, backe "workspace": {"repos": repos, "retain": "on_failure"}, "env": {"SKIPPY_PERFORMANCE_PLAN": json.dumps(plan, separators=(",", ":")), **entry["env"]}, - "command": job_command(job_steps(arm_list, keys, rounds, shape["servers"], trace)), + "command": job_command(job_steps(arm_list, keys, rounds, shape["servers"], trace, backend)), }, "harness": { "name": "custom", "version": "aiperf-0.13.0", diff --git a/scripts/lib/performance_report.py b/scripts/lib/performance_report.py index 2fa9812f..f3308fba 100644 --- a/scripts/lib/performance_report.py +++ b/scripts/lib/performance_report.py @@ -8,6 +8,7 @@ from .inference_charts import health_charts from .inference_markdown import HEALTH_LABELS, health_sections, plain, table from .inference_nightly_metrics import metric_value +from .performance_load import request_rate # Higher is better for rates; lower is better for latencies. HEADLINE = {"output_tok_s": "higher", "ttft_ms_p50": "lower", "itl_ms_p50": "lower"} @@ -165,7 +166,8 @@ def rows(record, shape, committed_at, job, pull_requests, branches=None): "server": sample["server"], "lanes": server["lanes"], "pool_tokens": server["pool_tokens"], "point": sample["point"], "concurrency": point["concurrency"], "depth": point["depth"], "input_tokens": point["input_tokens"], "output_tokens": point["output_tokens"], - "requests": point["requests"], "round": sample["round"], + "requests": point["requests"], "request_rate": request_rate(point, host.get("backend")), + "round": sample["round"], "applied": json.dumps(sample["applied"], sort_keys=True), "unsupported": json.dumps(sample["unsupported"]), "rejected": None if sample["rejected"] is None else json.dumps(sample["rejected"], sort_keys=True), diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index 6b80b440..3515c0d6 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -9,7 +9,7 @@ from lib import performance_arms, performance_backends, performance_plan from lib.performance_arms import REQUIRED, capabilities, may_reject, server_args -from lib.performance_load import measurements, rejection, run_point +from lib.performance_load import measurements, profile_args, rejection, request_rate, run_point from lib import performance_report from lib.performance_report import markdown, summarize @@ -49,6 +49,22 @@ def test_a_variant_server_runs_only_when_named(self): named = performance_plan.scenario(["lanes4-pool32k", variant])["servers"] self.assertEqual([server["id"] for server in named], ["lanes4-pool32k", variant]) + def test_a_rate_point_names_a_positive_rate_per_backend_and_runs_on_its_own_schedule(self): + rated = "lanes4-pool32k-rate" + point = performance_plan.scenario([rated])["servers"][0]["points"][0] + args = profile_args("http://e", point, "m@r", "/t", 2, Path("/a"), request_rate(point, "metal")) + self.assertEqual(args[args.index("--request-rate") + 1], str(point["request_rate"]["metal"])) + self.assertEqual(args[args.index("--arrival-pattern") + 1], "poisson") + self.assertNotIn("--request-rate", profile_args("http://e", point, "m@r", "/t", 2, Path("/a"))) + shape = performance_plan.read_json(performance_plan.SCENARIO) + index = next(index for index, server in enumerate(shape["servers"]) if server["id"] == rated) + for rate in ({}, {"metal": 0}, {"metal": "fast"}, {"space-heater": 1}, 0.2): + broken = json.loads(json.dumps(shape)) + broken["servers"][index]["points"][0]["request_rate"] = rate + with patch.object(performance_plan, "read_json", return_value=broken): + with self.assertRaises(ValueError): + performance_plan.scenario([rated]) + def test_a_variant_cannot_set_what_the_harness_sets_or_nothing(self): shape = performance_plan.read_json(performance_plan.SCENARIO) for flags in ({}, {"debug": 1}, {"kv-pool-tokens": 4096}, {"Prefill Chunk": 1}, @@ -181,6 +197,12 @@ def test_a_cuda_plan_targets_a_dgx_spark(self): self.assertIn("Same-host CUDA comparison", spec["description"]) self.assertEqual(json.loads(spec["runtime"]["env"]["SKIPPY_PERFORMANCE_PLAN"])["backend"], "cuda") + def test_a_rate_point_is_refused_on_a_backend_it_has_no_rate_for(self): + arm_list = performance_plan.arms(self.candidate, self.baseline, self.pin) + with self.assertRaisesRegex(ValueError, "no request rate for the rocm backend"): + performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 3, "rocm-1", "r", backend="rocm", + servers=["lanes4-pool32k-rate"]) + def test_an_unknown_backend_is_refused_at_plan_time(self): arm_list = performance_plan.arms(self.candidate, self.baseline, self.pin) with self.assertRaisesRegex(ValueError, "unknown backend"): From 119c0ce11776130ec970b0241917656d92ba58a4 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Sat, 28 Nov 2026 00:47:26 +1100 Subject: [PATCH 23/50] Add rate servers for load-sized prefill chunks --- ci/inference-performance.json | 36 +++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/ci/inference-performance.json b/ci/inference-performance.json index d34908b9..adf4b83a 100644 --- a/ci/inference-performance.json +++ b/ci/inference-performance.json @@ -116,6 +116,42 @@ "points": [ {"id": "rate-depth4096-pool32k-prompt-order2", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 24, "request_rate": {"metal": 0.22, "cuda": 0.34, "cuda-x86": 0.9}} ] + }, + { + "id": "lanes4-pool32k-prompt-order-active-rate", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"batch-policy": "prompt_order", "batch-prefill-wait": "active"}, + "points": [ + {"id": "rate-depth4096-pool32k-prompt-order-active", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 24, "request_rate": {"metal": 0.22, "cuda": 0.34, "cuda-x86": 0.9}} + ] + }, + { + "id": "lanes4-pool32k-prompt-order-adaptive-rate", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"batch-policy": "prompt_order", "batch-prefill-chunk": "adaptive"}, + "points": [ + {"id": "rate-depth4096-pool32k-prompt-order-adaptive", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 24, "request_rate": {"metal": 0.22, "cuda": 0.34, "cuda-x86": 0.9}} + ] + }, + { + "id": "lanes4-pool32k-load-chunks-rate", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"batch-policy": "prompt_order", "batch-prefill-wait": "active", "batch-wait-sessions": "direct", "batch-prefill-chunk": "adaptive", "batch-checkpoint-align": "microbatch"}, + "points": [ + {"id": "rate-depth4096-pool32k-load-chunks", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 24, "request_rate": {"metal": 0.22, "cuda": 0.34, "cuda-x86": 0.9}} + ] + }, + { + "id": "lanes4-pool32k-load-chunks2048-rate", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"batch-policy": "prompt_order", "batch-prefill-wait": "active", "batch-wait-sessions": "direct", "batch-prefill-chunk": "adaptive", "batch-checkpoint-align": "microbatch", "batch-prefill-shared-tokens": 2048}, + "points": [ + {"id": "rate-depth4096-pool32k-load-chunks2048", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 24, "request_rate": {"metal": 0.22, "cuda": 0.34, "cuda-x86": 0.9}} + ] } ] } From b6c11ee4f0c4255395566d38083ebbe9f2676344 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Sun, 29 Nov 2026 06:36:28 +1100 Subject: [PATCH 24/50] Compare checkpoint admission across model families The performance comparison took its models from the CI ladder, which holds only Qwen models, so it could not measure other architectures. It now takes any model pinned in ci/inference-artifacts.json; the ladder, and so CI qualification, is unchanged. Adds the performance-coverage families at their canary pins (Llama 3.2 1B, Gemma 3 1B, gpt-oss 20B, DeepSeek Coder V2 Lite, phi-4, Mistral Small 3.2 24B, Falcon Mamba 7B, Granite 4.0 H 350M), and four more recurrent families (Falcon-H1 1.5B, Jamba2 3B, LFM2 350M, Nemotron 3.5 Lightning 30B-A3B), each with a pinned tokenizer. Adds two variant servers, lanes4-pool32k-admission-grid and -branch, that run the depth-4096 shared-prefix point and the long-output point with --batch-checkpoint-admission set to each value. --- ci/inference-artifacts.json | 265 ++++++++++++++++++ ci/inference-performance.json | 20 ++ scripts/lib/performance_plan.py | 6 +- .../tests/inference_performance_contracts.py | 4 +- 4 files changed, 291 insertions(+), 4 deletions(-) diff --git a/ci/inference-artifacts.json b/ci/inference-artifacts.json index 171df66d..6710a993 100644 --- a/ci/inference-artifacts.json +++ b/ci/inference-artifacts.json @@ -197,5 +197,270 @@ "tokenizer_config.json", "vocab.json" ] + }, + "perf-llama-3-2-1b-q4": { + "repo": "bartowski/Llama-3.2-1B-Instruct-GGUF", + "revision": "067b946cf014b7c697f3654f621d577a3e3afd1c", + "files": [ + { + "path": "Llama-3.2-1B-Instruct-Q4_K_M.gguf", + "sha256": "6f85a640a97cf2bf5b8e764087b1e83da0fdb51d7c9fab7d0fece9385611df83", + "size": 807694464 + } + ], + "tokenizer_repo": "unsloth/Llama-3.2-1B-Instruct", + "tokenizer_revision": "5a8abab4a5d6f164389b1079fb721cfab8d7126c", + "layers": 16, + "activation_width": 2048, + "tokenizer_files": [ + "chat_template.jinja", + "config.json", + "special_tokens_map.json", + "tokenizer.json", + "tokenizer_config.json" + ] + }, + "perf-gemma3-1b-q4": { + "repo": "ggml-org/gemma-3-1b-it-GGUF", + "revision": "f9c28bcd85737ffc5aef028638d3341d49869c27", + "files": [ + { + "path": "gemma-3-1b-it-Q4_K_M.gguf", + "sha256": "8ccc5cd1f1b3602548715ae25a66ed73fd5dc68a210412eea643eb20eb75a135", + "size": 806058240 + } + ], + "tokenizer_repo": "unsloth/gemma-3-1b-it", + "tokenizer_revision": "5b11413a10db4e486ef16a20101fd028f8f2499c", + "layers": 26, + "activation_width": 1152, + "tokenizer_files": [ + "chat_template.jinja", + "config.json", + "special_tokens_map.json", + "tokenizer.json", + "tokenizer.model", + "tokenizer_config.json" + ] + }, + "perf-gpt-oss-20b-mxfp4": { + "repo": "ggml-org/gpt-oss-20b-GGUF", + "revision": "ef9b12f2ff56c69cf32153a02784e7a3c88bf524", + "files": [ + { + "path": "gpt-oss-20b-MXFP4.gguf", + "sha256": "27cd6c432c7672cb812a92f611cf3ba7bbc35928262bb1e1253ff4ee6ae35901", + "size": 12109566624 + } + ], + "tokenizer_repo": "openai/gpt-oss-20b", + "tokenizer_revision": "6cee5e81ee83917806bbde320786a8fb61efebee", + "layers": 24, + "activation_width": 2880, + "tokenizer_files": [ + "chat_template.jinja", + "config.json", + "special_tokens_map.json", + "tokenizer.json", + "tokenizer_config.json" + ] + }, + "perf-deepseek2-coder-lite-q4": { + "repo": "bartowski/DeepSeek-Coder-V2-Lite-Instruct-GGUF", + "revision": "8f248fa2072348f77a8bc37754e470de1f61866e", + "files": [ + { + "path": "DeepSeek-Coder-V2-Lite-Instruct-Q4_K_M.gguf", + "sha256": "603bd3f8a0281d16571da7c08bd661ee17ff0d1be6fcbd1b42242da257ef0bb8", + "size": 10364416768 + } + ], + "tokenizer_repo": "deepseek-ai/DeepSeek-Coder-V2-Lite-Instruct", + "tokenizer_revision": "e434a23f91ba5b4923cf6c9d9a238eb4a08e3a11", + "layers": 27, + "activation_width": 2048, + "tokenizer_files": [ + "config.json", + "tokenizer.json", + "tokenizer_config.json" + ] + }, + "perf-phi4-q4": { + "repo": "unsloth/phi-4-GGUF", + "revision": "5110b7771e8166d5530e73346a15aea096a8cb99", + "files": [ + { + "path": "phi-4-Q4_K_M.gguf", + "sha256": "01e1f25b3e6931054c6c2227b06f4969828434eebc299e8e171f55dab6814485", + "size": 8890306112 + } + ], + "tokenizer_repo": "unsloth/phi-4", + "tokenizer_revision": "c6220bde10fff762dbd72c3331894aa4cade249d", + "layers": 40, + "activation_width": 5120, + "tokenizer_files": [ + "config.json", + "merges.txt", + "special_tokens_map.json", + "tokenizer.json", + "tokenizer_config.json", + "vocab.json" + ] + }, + "perf-mistral-small-24b-q4": { + "repo": "unsloth/Mistral-Small-3.2-24B-Instruct-2506-GGUF", + "revision": "b750ec2299225e492f1bd27cab88a0a595fa848f", + "files": [ + { + "path": "Mistral-Small-3.2-24B-Instruct-2506-Q4_K_M.gguf", + "sha256": "a3cc56310807ed0d145eaf9f018ccda9ae7ad8edb41ec870aa2454b0d4700b3c", + "size": 14333922848 + } + ], + "tokenizer_repo": "unsloth/Mistral-Small-3.2-24B-Instruct-2506", + "tokenizer_revision": "3ed8d341b53ea3d0e4194689905477688a6cf733", + "layers": 40, + "activation_width": 5120, + "tokenizer_files": [ + "chat_template.jinja", + "config.json", + "special_tokens_map.json", + "tokenizer.json", + "tokenizer_config.json" + ] + }, + "perf-falcon-mamba-7b-q4": { + "repo": "bartowski/falcon-mamba-7b-GGUF", + "revision": "1236a076ebddbcfcbd6ba0fe310d473d20527f11", + "files": [ + { + "path": "falcon-mamba-7b-Q4_K_M.gguf", + "sha256": "ef8ba78a1fd0b0fd1d1c966acc5f4c043b12fbbd7044f4d9aad82e6b7a51e0a7", + "size": 4204230656 + } + ], + "tokenizer_repo": "tiiuae/falcon-mamba-7b", + "tokenizer_revision": "080ad94b3619e2c2d0afa59bafdc6113465b7006", + "layers": 64, + "activation_width": 4096, + "tokenizer_files": [ + "config.json", + "special_tokens_map.json", + "tokenizer.json", + "tokenizer_config.json" + ] + }, + "perf-granite-4-h-350m-q4": { + "repo": "ibm-granite/granite-4.0-h-350m-GGUF", + "revision": "a864f823cce6e6048b5752e2816fe7a23987d790", + "files": [ + { + "path": "granite-4.0-h-350m-Q4_K_M.gguf", + "sha256": "0a8d6a7373602fadfba274a640ba784b86cc6847f1c67f1b0a90fa2ec266b7fb", + "size": 222662560 + } + ], + "tokenizer_repo": "ibm-granite/granite-4.0-h-350m", + "tokenizer_revision": "3b17b717b8f2f5d305b0a92c1491e239aeda19c8", + "layers": 32, + "activation_width": 768, + "tokenizer_files": [ + "chat_template.jinja", + "config.json", + "merges.txt", + "special_tokens_map.json", + "tokenizer.json", + "tokenizer_config.json", + "vocab.json" + ] + }, + "perf-falcon-h1-1-5b-q4": { + "repo": "tiiuae/Falcon-H1-1.5B-Instruct-GGUF", + "revision": "0d3a6cfe25fb4eeab0153fb8623aac5b69d6bd0a", + "files": [ + { + "path": "Falcon-H1-1.5B-Instruct-Q4_K_M.gguf", + "sha256": "8b51aa2aa34a0373fd0cd64c02eb91d1bc1da681c09e955ad769d4a9b2d8385f", + "size": 944786656 + } + ], + "tokenizer_repo": "tiiuae/Falcon-H1-1.5B-Instruct", + "tokenizer_revision": "80ebc50d7799a440b96c93bb6686a3924a09b0cb", + "layers": 24, + "activation_width": 2048, + "tokenizer_files": [ + "chat_template.jinja", + "config.json", + "special_tokens_map.json", + "tokenizer.json", + "tokenizer_config.json" + ] + }, + "perf-jamba2-3b-q4": { + "repo": "bartowski/ai21labs_AI21-Jamba2-3B-GGUF", + "revision": "02d70acd708332ec4e78e9ceefe116851a307411", + "files": [ + { + "path": "ai21labs_AI21-Jamba2-3B-Q4_K_M.gguf", + "sha256": "fa0876fa152f38689cefd6d498907d6255cf515780d65b16346d3190df6a0794", + "size": 1932696448 + } + ], + "tokenizer_repo": "ai21labs/AI21-Jamba2-3B", + "tokenizer_revision": "525c6c8e1d9f5bddedfbdc1dbb0ade2df84230c9", + "layers": 28, + "activation_width": 2560, + "tokenizer_files": [ + "chat_template.jinja", + "config.json", + "special_tokens_map.json", + "tokenizer.json", + "tokenizer_config.json" + ] + }, + "perf-lfm2-350m-q4": { + "repo": "LiquidAI/LFM2-350M-GGUF", + "revision": "8fdc9d526b7ed346b19257551b05816c7912ecc2", + "files": [ + { + "path": "LFM2-350M-Q4_K_M.gguf", + "sha256": "a4d000c7064bd3b2e42c6845836286a899a4e79cf1791da1a6797b58d575957d", + "size": 229309376 + } + ], + "tokenizer_repo": "LiquidAI/LFM2-350M", + "tokenizer_revision": "f37d3f5c8c5484bc01dad379a595cf4c68c4e70e", + "layers": 16, + "activation_width": 1024, + "tokenizer_files": [ + "chat_template.jinja", + "config.json", + "special_tokens_map.json", + "tokenizer.json", + "tokenizer_config.json" + ] + }, + "perf-nemotron35-lightning-30b-a3b-q4": { + "repo": "unsloth/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-GGUF", + "revision": "f2d3fe3694501008786e81e5f20360cbf715496a", + "files": [ + { + "path": "NVIDIA-Nemotron-3.5-Lightning-30B-A3B-UD-Q4_K_M.gguf", + "sha256": "edcb5d4650796ed2fb412498de6f83b585862312c747ddb74f0ea04b22206181", + "size": 25266255936 + } + ], + "tokenizer_repo": "nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16", + "tokenizer_revision": "a9904d24bcc1d289a1950fa9d2b978c47cf903b9", + "layers": 52, + "activation_width": 2688, + "tokenizer_files": [ + "chat_template.jinja", + "config.json", + "special_tokens_map.json", + "tokenizer.json", + "tokenizer_config.json" + ] } } diff --git a/ci/inference-performance.json b/ci/inference-performance.json index adf4b83a..25a8470e 100644 --- a/ci/inference-performance.json +++ b/ci/inference-performance.json @@ -152,6 +152,26 @@ "points": [ {"id": "rate-depth4096-pool32k-load-chunks2048", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 24, "request_rate": {"metal": 0.22, "cuda": 0.34, "cuda-x86": 0.9}} ] + }, + { + "id": "lanes4-pool32k-admission-grid", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"batch-checkpoint-admission": "grid"}, + "points": [ + {"id": "c4-depth4096-pool32k-admission-grid", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 16}, + {"id": "c4-long-output-admission-grid", "concurrency": 4, "depth": 0, "input_tokens": 512, "output_tokens": 2048, "requests": 8} + ] + }, + { + "id": "lanes4-pool32k-admission-branch", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"batch-checkpoint-admission": "branch"}, + "points": [ + {"id": "c4-depth4096-pool32k-admission-branch", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 16}, + {"id": "c4-long-output-admission-branch", "concurrency": 4, "depth": 0, "input_tokens": 512, "output_tokens": 2048, "requests": 8} + ] } ] } diff --git a/scripts/lib/performance_plan.py b/scripts/lib/performance_plan.py index 79c72785..7497b206 100644 --- a/scripts/lib/performance_plan.py +++ b/scripts/lib/performance_plan.py @@ -8,7 +8,6 @@ from .ci_artifacts import digest, read_json from .inference_inputs import fixture -from .inference_ladder import ladder_models from .performance_backends import BACKENDS from .performance_load import request_rate @@ -206,9 +205,10 @@ def job_command(steps): def models(keys): - known = {model["id"] for model in ladder_models()} + # any pinned model, not only the CI ladder's, so a comparison can cover other families + known = set(read_json(ROOT / "ci/inference-artifacts.json")) if not keys or len(set(keys)) != len(keys) or not set(keys) <= known: - raise ValueError(f"models must be distinct ladder ids from: {', '.join(sorted(known))}") + raise ValueError(f"models must be distinct pinned models from: {', '.join(sorted(known))}") return keys diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index 3515c0d6..833d693b 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -239,7 +239,9 @@ def test_a_rocm_plan_targets_one_pinned_unified_host(self): self.assertTrue(spec["runtime"]["env"].get("PATH", "").startswith("/opt/rocm/bin")) self.assertEqual(spec["runtime"]["env"].get("LD_LIBRARY_PATH"), "/opt/rocm/lib") - def test_models_must_be_ladder_ids(self): + def test_models_must_be_distinct_pinned_models(self): + self.assertEqual(performance_plan.models(["qwen35-4b", "perf-falcon-mamba-7b-q4"]), + ["qwen35-4b", "perf-falcon-mamba-7b-q4"]) with self.assertRaises(ValueError): performance_plan.models(["qwen35-4b", "qwen35-4b"]) with self.assertRaises(ValueError): From 2533d7a3c3a9bdd0f8510dda7ef4bf3787752a43 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Mon, 30 Nov 2026 15:17:00 +1100 Subject: [PATCH 25/50] Let a performance point replay recorded conversations Generated prompts show how a server handles fixed request shapes, not how it handles a chat. A point with `dataset` now replays recorded conversations through AIPerf, each turn sent with every turn before it, so a conversation re-reads its own growing prefix the way a client does: - agentx: the Claude Code traces already pinned for qualification, under the nightly's inferencex-agentx-mvp scenario, run for `duration_s`. - sharegpt: ShareGPT's split conversations, pinned in ci/inference-chat-corpus.json, run for `requests` turns with ignore_eos so every arm generates the same tokens. Both loaders resolve the dataset's main branch, so a point checks main against its pin before and after it runs, as qualification does. A server may set its own `context_per_lane` for conversations longer than the scenario's. Its pool, if it has one, must hold a full lane for each conversation in flight, so a failed request is a fault on every arm rather than a pool llama-server could not fit. Rows gain the dataset, duration and lane context (schema 3), and a replaying job is bounded by its duration, with its trace recorded as a file. --- ci/INFERENCE_PERFORMANCE.md | 33 +++++- ci/inference-chat-corpus.json | 5 + scripts/inference-performance.py | 10 +- scripts/lib/inference_checks.py | 2 +- scripts/lib/performance_arms.py | 6 +- scripts/lib/performance_load.py | 63 ++++++++-- scripts/lib/performance_plan.py | 77 +++++++++--- scripts/lib/performance_report.py | 11 +- .../tests/inference_performance_contracts.py | 110 +++++++++++++++++- 9 files changed, 274 insertions(+), 43 deletions(-) create mode 100644 ci/inference-chat-corpus.json diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index 3d6a1ae4..2cb0d449 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -117,7 +117,9 @@ for the start, each model, each arm's server in each round, each trace pass and the final archive), and after each the command writes the percent of the job's expected time spent to `$JIANYANG_PROGRESS_PATH`, with what just finished. The expected times are rough: fifteen minutes for a Skippy build, five for -`llama-server`, and half a minute per server start plus two seconds per request. +`llama-server`, and half a minute per server start plus two seconds per request, +or for a conversation point two minutes to load its dataset plus its duration or +four seconds a turn. A failed step names itself on stderr and the archive still runs. The scenario covers one request at a time, four lanes with short and long @@ -133,7 +135,7 @@ itself (context, lanes, pool, speculation, telemetry). An arm whose build lacks one of them fails before any round, since without it the variant would measure the server it varies. -A point drives its server one of two ways. By default AIPerf keeps `concurrency` +A point drives its server one of three ways. By default AIPerf keeps `concurrency` requests in flight, sending the next as one finishes. Requests that finish together are then replaced together, so a policy that lets them finish together keeps every wave as synchronized as the first. A point with `request_rate` instead sends requests @@ -143,6 +145,25 @@ slowest arm served with four in flight on the lab's host for it, as each backend hardware serves a different rate; a plan for a backend a rate point has no rate for is refused. +A point with `dataset` replays recorded conversations instead of generated prompts, +`concurrency` of them at a time, each turn sent with every turn before it, so a +conversation re-reads its own growing prefix the way a chat client does: + +- `agentx` replays the Claude Code traces admitted in `inference-corpus.json` under + the nightly's `inferencex-agentx-mvp` scenario, keeping only traces whose peak + context fits a lane. The traces pace their own turns, so the point runs for + `duration_s` (60 to 3,600 seconds); below the scenario's 900 it passes + `--unsafe-override`, which marks the run as no submission and changes nothing else. +- `sharegpt` replays ShareGPT's conversations, as split to about 2,048 tokens, + pinned in `inference-chat-corpus.json`, for `requests` turns. Each turn asks for + its recorded reply's length with `ignore_eos`, so every arm generates the same tokens. + +AIPerf's loaders resolve each dataset's main branch, so the point checks main +against the pin before and after it runs, as qualification does, and keeps both +answers beside its AIPerf export. A server may set its own `context_per_lane` for +conversations longer than the scenario's, and its pool, if it has one, must hold +that much for each conversation in flight. + An arm that lacks a setting, such as `--kv-pool-tokens` on a commit from before the pool existed, runs without it. Each sample records what was applied and what the arm did not support. All arms are probed before model measurements begin. @@ -156,7 +177,8 @@ A failed request fails the job: a point counts only when AIPerf reports every request served. `llama-server` has one exception. It frees KV from idle slots only, so at a point whose requests, all in flight, need more than its pool holds it fails them: sixteen lanes at depth 4,096 in the 32K pool, and four lanes at -that depth in the 16K pool. There the failures are its result. The sample keeps +that depth in the 16K pool. There the failures are its result; a conversation +point's pool is held to fit, so there they are faults as well. The sample keeps them as `rejected`, with null metrics, and the summary table shows `rejected` for that arm. The server must still be running afterwards, or the job fails. A Skippy arm is held to every point. @@ -205,8 +227,9 @@ Stored rows retain their actual timestamps for future trend analysis. For graphs over time it also writes `LABEL-rows.jsonl` beside each job's `LABEL-performance.json`, LABEL being the job's node or `any`: one row per measured sample, with the job, when the run started, the host, the arm's commit and when it was -committed, the model revision, the server's lanes and pool, the point's -concurrency, depth and token counts, the round, and each metric as its own column. +committed, the model revision, the server's lanes, pool and context per lane, the +point's concurrency, dataset, depth, token counts, requests and duration (null +where the point has none), the round, and each metric as its own column. A rejected point keeps its row, with null metrics and the `rejected` entry as JSON text. An arm taken from a pull request has `on_main` false and its number in `pull_request`; one taken from a branch has `on_main` false and its name in `branch`; diff --git a/ci/inference-chat-corpus.json b/ci/inference-chat-corpus.json new file mode 100644 index 00000000..370fe6a1 --- /dev/null +++ b/ci/inference-chat-corpus.json @@ -0,0 +1,5 @@ +{ + "repo": "anon8231489123/ShareGPT_Vicuna_unfiltered", + "revision": "192ab2185289094fc556ec8ce5ce1e8e587154ca", + "alias": "sharegpt" +} diff --git a/scripts/inference-performance.py b/scripts/inference-performance.py index 1037cb3b..976f310b 100644 --- a/scripts/inference-performance.py +++ b/scripts/inference-performance.py @@ -27,8 +27,8 @@ from lib.performance_arms import build, capabilities, may_reject, server_args, server_flags, supports from lib.performance_backends import BACKENDS from lib.performance_load import request_rate, run_point, tokenizer -from lib.performance_plan import (SCENARIO, arms, branch_name, job_spec, models, nodes, pull_request_head, - pull_request_number, scenario) +from lib.performance_plan import (SCENARIO, arms, branch_name, job_spec, lane_context, models, nodes, + pull_request_head, pull_request_number, scenario) from lib.performance_report import markdown, rows, summarize REPO = "Mesh-LLM/skippy" @@ -302,8 +302,8 @@ def measure(built, help_text, model, inputs, key, index, server, shape, output, prefixes=("MTL",), backend=None): """`index` is the round, or None for a diagnostic pass that writes `trace`.""" coordinate = f'{inputs["repo"]}@{inputs["revision"]}' - args, applied, missing = server_args(built, help_text, model, coordinate, - shape["context_per_lane"], server) + context = lane_context(shape, server) + args, applied, missing = server_args(built, help_text, model, coordinate, context, server) overrides = None if trace is None else traced(built, help_text, args, applied, missing, trace) pass_name = "trace" if index is None else f"r{index + 1}" name = f'{key}-{pass_name}-{built["label"]}-{server["id"]}' @@ -318,7 +318,7 @@ def measure(built, help_text, model, inputs, key, index, server, shape, output, metrics, rejected = run_point(ENDPOINT, point, coordinate, inputs["tokenizer_path"], shape["warmup_requests"], WORK / "aiperf" / name / point["id"], may_reject=may_reject(built, server, point), - rate=request_rate(point, backend)) + rate=request_rate(point, backend), context=context) # A rejection is the answer of a server that is still serving; one that died is a fault. if rejected is not None and process.poll() is not None: raise RuntimeError("server exited while it was rejecting requests; inspect its log") diff --git a/scripts/lib/inference_checks.py b/scripts/lib/inference_checks.py index 15ef45c8..7adda1c8 100644 --- a/scripts/lib/inference_checks.py +++ b/scripts/lib/inference_checks.py @@ -103,7 +103,7 @@ def verify_corpus(corpus, output, phase): f'https://huggingface.co/api/datasets/{corpus["repo"]}/revision/main'], 60, local=False)) write_json(output / f"corpus-{phase}.json", result) if not re.fullmatch(r"[0-9a-f]{40}", corpus["revision"]) or result.get("sha") != corpus["revision"]: - raise ValueError("AgentX corpus revision differs from the admitted pin") + raise ValueError(f'{corpus["repo"]} revision differs from the admitted pin') def retain(directory, output): diff --git a/scripts/lib/performance_arms.py b/scripts/lib/performance_arms.py index 3e772eb3..66e6805b 100644 --- a/scripts/lib/performance_arms.py +++ b/scripts/lib/performance_arms.py @@ -146,5 +146,7 @@ def may_reject(built, server, point): held to every point, and so is `llama-server` inside its pool. """ pool = server["pool_tokens"] - in_flight = point["concurrency"] * (point["depth"] + point["input_tokens"] + point["output_tokens"]) - return built["kind"] == "llama-server" and pool is not None and in_flight > pool + if built["kind"] != "llama-server" or pool is None or "dataset" in point: + # A conversation point's pool holds a full lane for each conversation, as the scenario checks. + return False + return point["concurrency"] * (point["depth"] + point["input_tokens"] + point["output_tokens"]) > pool diff --git a/scripts/lib/performance_load.py b/scripts/lib/performance_load.py index 9e027c2c..47049d76 100644 --- a/scripts/lib/performance_load.py +++ b/scripts/lib/performance_load.py @@ -9,10 +9,21 @@ from .ci_artifacts import read_json from .ci_process import command +from .inference_checks import verify_corpus from .inference_inputs import downloaded_path, safe_relative AIPERF = ["uv", "tool", "run", "--python", "3.12", "--constraints", "ci/aiperf-requirements.lock", "--from", "aiperf==0.13.0", "aiperf", "profile"] +# A conversation point replays recorded conversations, each turn sent with the turns before it, +# instead of generated prompts. `bound` is what ends it: AgentX paces its turns from the traces' +# own gaps, so it runs for a time; ShareGPT sends each turn once the last is answered, so it runs +# for a number of requests. +DATASETS = { + "agentx": {"corpus": "ci/inference-corpus.json", "bound": "duration_s"}, + "sharegpt": {"corpus": "ci/inference-chat-corpus.json", "bound": "requests"}, +} +# AgentX's scenario holds a shorter run to be no submission; a comparison is not one. +AGENTX_MINIMUM_S = 900 # Output name -> (AIPerf export metric, statistic). Missing metrics stay null; the raw # export is retained beside them, so a renamed field is visible rather than zero. METRICS = { @@ -49,19 +60,45 @@ def request_rate(point, backend): return rates[backend] -def profile_args(endpoint, point, coordinate, tokenizer_path, warmup, directory, rate=None): - args = [ +def dataset(point): + """The dataset a conversation point replays, or None for a point of generated prompts.""" + return DATASETS[point["dataset"]] if "dataset" in point else None + + +def common_args(endpoint, point, coordinate, tokenizer_path, directory): + return [ *AIPERF, "--ui", "simple", "--url", endpoint, "--endpoint-type", "chat", "--streaming", # Nothing here reads AIPerf's server metrics or GPU telemetry, and under load their # optional collectors miss heartbeats, which marks the whole run incomplete. "--no-server-metrics", "--no-gpu-telemetry", "--model", coordinate, "--tokenizer", str(tokenizer_path), "--random-seed", "42", "--use-server-token-count", "--concurrency", str(point["concurrency"]), + "--artifact-dir", str(directory), + ] + + +def conversation_args(endpoint, point, coordinate, tokenizer_path, warmup, directory, context, corpus): + args = [*common_args(endpoint, point, coordinate, tokenizer_path, directory), + "--public-dataset", corpus["alias"]] + if point["dataset"] == "agentx": + # The scenario the nightly runs: it sets the trace pacing and ignore_eos itself, and + # keeps only the traces whose turns fit a lane. + args += ["--scenario", "inferencex-agentx-mvp", "--max-context-length", str(context), + "--cache-bust", "first-turn-prefix", "--benchmark-duration", str(point["duration_s"])] + return args + (["--unsafe-override"] if point["duration_s"] < AGENTX_MINIMUM_S else []) + # Each turn asks for its recorded reply's length and gets all of it, so every arm + # generates the same tokens whatever its model would have stopped at. + return args + ["--request-count", str(point["requests"]), "--warmup-request-count", str(warmup), + "--extra-inputs", "ignore_eos:true"] + + +def profile_args(endpoint, point, coordinate, tokenizer_path, warmup, directory, rate=None): + args = [ + *common_args(endpoint, point, coordinate, tokenizer_path, directory), "--request-count", str(point["requests"]), "--warmup-request-count", str(warmup), "--synthetic-input-tokens-mean", str(point["input_tokens"]), "--synthetic-input-tokens-stddev", "0", "--output-tokens-mean", str(point["output_tokens"]), "--output-tokens-stddev", "0", "--extra-inputs", "ignore_eos:true", - "--artifact-dir", str(directory), ] if rate is not None: # Requests arrive on their own schedule, seeded so every arm sees the same one, and the @@ -114,23 +151,33 @@ def rejection(directory, requests): for error, count in sorted(failed.items())]} -def run_point(endpoint, point, coordinate, tokenizer_path, warmup, directory: Path, *, may_reject, +def run_point(endpoint, point, coordinate, tokenizer_path, warmup, directory: Path, *, may_reject, context, rate=None): - """One point's metrics, or null metrics and what the server rejected where it may reject.""" - failure = None + """One point's metrics, or null metrics and what the server rejected where it may reject. + `context` is a lane's, which every turn of a replayed AgentX trace must fit.""" + failure, entry = None, dataset(point) + if entry is None: + args = profile_args(endpoint, point, coordinate, tokenizer_path, warmup, directory, rate) + else: + corpus = read_json(Path(entry["corpus"])) + directory.parent.mkdir(parents=True, exist_ok=True) + # The loader resolves the dataset's main branch; the pin holds only if main has not moved. + verify_corpus(corpus, directory.parent, f'{point["id"]}-before') + args = conversation_args(endpoint, point, coordinate, tokenizer_path, warmup, directory, context, corpus) # AIPerf stages its ZeroMQ event bus under TMPDIR, and the job's own TMPDIR # lives under the workspace, whose path can exceed the 103-byte unix-socket # limit (this Mac's "Application Support" tree) before AIPerf adds its own # nesting. Anchor a short, space-free TMPDIR at /tmp instead. short_tmp = Path(tempfile.mkdtemp(prefix="aiperf-tmp-", dir="/tmp")) try: - command(profile_args(endpoint, point, coordinate, tokenizer_path, warmup, directory, rate), - timeout=5400, overrides={"TMPDIR": str(short_tmp)}) + command(args, timeout=5400, overrides={"TMPDIR": str(short_tmp)}) except subprocess.CalledProcessError as error: # AIPerf exits non-zero, with no summary export, when every measured request failed. failure = error finally: shutil.rmtree(short_tmp, ignore_errors=True) + if entry is not None: + verify_corpus(corpus, directory.parent, f'{point["id"]}-after') rejected = rejection(directory, point["requests"]) if may_reject else None if rejected is not None: return dict.fromkeys(METRICS), rejected diff --git a/scripts/lib/performance_plan.py b/scripts/lib/performance_plan.py index 7497b206..2d1eb419 100644 --- a/scripts/lib/performance_plan.py +++ b/scripts/lib/performance_plan.py @@ -9,7 +9,7 @@ from .ci_artifacts import digest, read_json from .inference_inputs import fixture from .performance_backends import BACKENDS -from .performance_load import request_rate +from .performance_load import DATASETS, dataset, request_rate ROOT = Path(__file__).resolve().parents[2] SCENARIO = ROOT / "ci/inference-performance.json" @@ -22,6 +22,9 @@ MAX_ROUNDS = 9 POINT_FIELDS = {"id", "concurrency", "depth", "input_tokens", "output_tokens", "requests"} SERVER_FIELDS = {"id", "lanes", "pool_tokens", "points"} +# A conversation point's run is long enough to replay whole conversations, and ends well +# inside the time AIPerf is given. +DURATION_S = range(60, 3601) SKIPPY_FLAG = re.compile(r"[a-z][a-z0-9]*(?:-[a-z0-9]+)*") FLAG_VALUE = re.compile(r"[A-Za-z0-9._,:-]{1,64}") # server_args sets these on every Skippy arm, so a variant's own flags cannot change them @@ -62,6 +65,41 @@ def rates(point): return value +def lane_context(shape, server): + """A server's context per lane: its own, for conversations that outgrow the scenario's.""" + return server.get("context_per_lane", shape["context_per_lane"]) + + +def generated_point(point, context): + """A point of generated prompts: its request shape, which one lane must hold whole.""" + if set(point) - {"request_rate"} != POINT_FIELDS: + raise ValueError("invalid or duplicate performance point") + if "request_rate" in point: + rates(point) + for field in ("concurrency", "input_tokens", "output_tokens", "requests"): + count(point[field], f'{point["id"]} {field}') + count(point["depth"], f'{point["id"]} depth', 0) + if point["depth"] + point["input_tokens"] + point["output_tokens"] > context: + raise ValueError(f'{point["id"]}: one request exceeds a lane\'s context') + + +def conversation_point(point, context, pool): + """A point replaying a pinned dataset, with only the bound its dataset runs to. A + conversation grows toward a lane's context, so the pool must hold a full lane for each one + in flight: a failed request is then a fault on every arm, never a pool `llama-server` + could not fit.""" + entry = DATASETS.get(point["dataset"]) if type(point["dataset"]) is str else None + if entry is None or set(point) != {"id", "dataset", "concurrency", entry["bound"]}: + raise ValueError(f'{point["id"]}: a conversation point names one of {", ".join(DATASETS)} ' + "and the bound it runs to") + concurrency = count(point["concurrency"], f'{point["id"]} concurrency') + bound = count(point[entry["bound"]], f'{point["id"]} {entry["bound"]}') + if entry["bound"] == "duration_s" and bound not in DURATION_S: + raise ValueError(f'{point["id"]}: duration_s must be {DURATION_S.start} to {DURATION_S.stop - 1}') + if pool is not None and pool < concurrency * context: + raise ValueError(f'{point["id"]}: the pool must hold a full lane for every conversation in flight') + + def scenario(named=None): """The checked scenario; with `named`, only those servers and their points, to rerun one workload without the rest. A server with its own `skippy_flags` is a variant of another, @@ -70,11 +108,11 @@ def scenario(named=None): if (set(value) != {"schema_version", "context_per_lane", "warmup_requests", "servers"} or value["schema_version"] != 1 or not value["servers"]): raise ValueError("invalid performance scenario") - context = count(value["context_per_lane"], "context_per_lane") + count(value["context_per_lane"], "context_per_lane") count(value["warmup_requests"], "warmup_requests", 0) servers, points, variants = set(), set(), set() for server in value["servers"]: - if set(server) - {"skippy_flags"} != SERVER_FIELDS or not server["points"]: + if set(server) - {"skippy_flags", "context_per_lane"} != SERVER_FIELDS or not server["points"]: raise ValueError("invalid performance server") if "skippy_flags" in server: skippy_flags(server) @@ -83,21 +121,19 @@ def scenario(named=None): raise ValueError(f'duplicate performance server: {server["id"]}') servers.add(server["id"]) lanes = count(server["lanes"], f'{server["id"]} lanes') + context = count(lane_context(value, server), f'{server["id"]} context_per_lane') if server["pool_tokens"] is not None and count(server["pool_tokens"], "pool_tokens") < context: raise ValueError(f'{server["id"]}: a KV pool must hold at least one lane\'s context') for point in server["points"]: - if set(point) - {"request_rate"} != POINT_FIELDS or point["id"] in points: + if type(point) is not dict or "id" not in point or point["id"] in points: raise ValueError("invalid or duplicate performance point") - if "request_rate" in point: - rates(point) points.add(point["id"]) - for field in ("concurrency", "input_tokens", "output_tokens", "requests"): - count(point[field], f'{point["id"]} {field}') - count(point["depth"], f'{point["id"]} depth', 0) + if "dataset" in point: + conversation_point(point, context, server["pool_tokens"]) + else: + generated_point(point, context) if point["concurrency"] > lanes: raise ValueError(f'{point["id"]}: concurrency exceeds the server\'s lanes') - if point["depth"] + point["input_tokens"] + point["output_tokens"] > context: - raise ValueError(f'{point["id"]}: one request exceeds a lane\'s context') if named is None: return {**value, "servers": [server for server in value["servers"] if server["id"] not in variants]} unknown = set(named) - servers @@ -155,8 +191,12 @@ def round_order(arm_list, index): def measure_minutes(server, backend): """A server's start and its points' requests: about two seconds each when kept in flight, - and as long as their arrivals take at a point's own rate.""" + and as long as their arrivals take at a point's own rate. A conversation point loads its + dataset for about two minutes, then runs its own time or about four seconds a turn.""" def seconds(point): + entry = dataset(point) + if entry is not None: + return 120 + (point["duration_s"] if entry["bound"] == "duration_s" else point["requests"] * 4) rate = request_rate(point, backend) return point["requests"] * 2 if rate is None else point["requests"] / rate + 10 return 0.5 + sum(seconds(point) for point in server["points"]) / 60 @@ -255,6 +295,12 @@ def job_spec(harness, arm_list, keys, rounds, node, label, *, trace=False, backe if servers is not None: plan["servers"] = servers points = [point for server in shape["servers"] for point in server["points"]] + runs = rounds * len(arm_list) * len(keys) + # A replayed point's requests are the dataset's; the scenario names it at its pin. + request_trace = {"kind": "file" if any(dataset(point) for point in points) else "synthetic", + "ref": f"ci/inference-performance.json@{harness}", "sha256": digest(SCENARIO)} + bounds = {"request_count": sum(point.get("requests", 0) for point in points) * runs, + "duration_s": sum(point.get("duration_s", 0) for point in points) * runs} return { "name": f"skippy-inference-performance-{label}", "description": entry["description"] + " of " + ", ".join( @@ -272,12 +318,11 @@ def job_spec(harness, arm_list, keys, rounds, node, label, *, trace=False, backe "command": job_command(job_steps(arm_list, keys, rounds, shape["servers"], trace, backend)), }, "harness": { - "name": "custom", "version": "aiperf-0.13.0", - "trace": {"kind": "synthetic", "ref": f"ci/inference-performance.json@{harness}", - "sha256": digest(SCENARIO)}, + "name": "custom", "version": "aiperf-0.13.0", "trace": request_trace, "seed": 42, "warmup_requests": shape["warmup_requests"], "concurrency": sorted({point["concurrency"] for point in points}), - "request_count": sum(point["requests"] for point in points) * rounds * len(arm_list) * len(keys), + # JY needs at least one; a bound no point uses stays out rather than reading zero. + **{name: value for name, value in bounds.items() if value}, }, "budget": {"max_usd": 0, "max_duration_s": 18000, "grace_s": 300}, } diff --git a/scripts/lib/performance_report.py b/scripts/lib/performance_report.py index f3308fba..4448a3ee 100644 --- a/scripts/lib/performance_report.py +++ b/scripts/lib/performance_report.py @@ -9,6 +9,7 @@ from .inference_markdown import HEALTH_LABELS, health_sections, plain, table from .inference_nightly_metrics import metric_value from .performance_load import request_rate +from .performance_plan import lane_context # Higher is better for rates; lower is better for latencies. HEADLINE = {"output_tok_s": "higher", "ttft_ms_p50": "lower", "itl_ms_p50": "lower"} @@ -151,7 +152,7 @@ def rows(record, shape, committed_at, job, pull_requests, branches=None): branch = (branches or {}).get(sample["arm"]) server, point = points[(sample["server"], sample["point"])] yield { - "schema_version": 2, "job": job, "started_at": record.get("started_at"), + "schema_version": 3, "job": job, "started_at": record.get("started_at"), "harness": record["harness"], "scenario_sha256": record["scenario_sha256"], "backend": host.get("backend"), "gpu": host.get("gpu"), "chip": host.get("chip"), "macos": host.get("macos"), "os": host.get("os"), "os_version": host.get("os_version"), @@ -164,9 +165,11 @@ def rows(record, shape, committed_at, job, pull_requests, branches=None): "pull_request": pull_request, "branch": branch, "model": sample["model"], "model_revision": record["models"][sample["model"]]["revision"], "server": sample["server"], "lanes": server["lanes"], "pool_tokens": server["pool_tokens"], - "point": sample["point"], "concurrency": point["concurrency"], "depth": point["depth"], - "input_tokens": point["input_tokens"], "output_tokens": point["output_tokens"], - "requests": point["requests"], "request_rate": request_rate(point, host.get("backend")), + "context_per_lane": lane_context(shape, server), + "point": sample["point"], "concurrency": point["concurrency"], "dataset": point.get("dataset"), + "depth": point.get("depth"), "input_tokens": point.get("input_tokens"), + "output_tokens": point.get("output_tokens"), "requests": point.get("requests"), + "duration_s": point.get("duration_s"), "request_rate": request_rate(point, host.get("backend")), "round": sample["round"], "applied": json.dumps(sample["applied"], sort_keys=True), "unsupported": json.dumps(sample["unsupported"]), diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index 833d693b..eb690325 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -9,7 +9,8 @@ from lib import performance_arms, performance_backends, performance_plan from lib.performance_arms import REQUIRED, capabilities, may_reject, server_args -from lib.performance_load import measurements, profile_args, rejection, request_rate, run_point +from lib.performance_load import (DATASETS, conversation_args, measurements, profile_args, rejection, + request_rate, run_point) from lib import performance_report from lib.performance_report import markdown, summarize @@ -76,6 +77,95 @@ def test_a_variant_cannot_set_what_the_harness_sets_or_nothing(self): performance_plan.scenario() +CONVERSATIONS = {"id": "lanes4-conversations", "lanes": 4, "pool_tokens": None, "context_per_lane": 16384, + "points": [{"id": "c1-agentx", "dataset": "agentx", "concurrency": 1, "duration_s": 600}, + {"id": "c4-sharegpt", "dataset": "sharegpt", "concurrency": 4, "requests": 32}]} + + +def with_server(server): + """The shipped scenario plus `server`, as `read_json` would return it.""" + shape = performance_plan.read_json(performance_plan.SCENARIO) + shape["servers"].append(json.loads(json.dumps(server))) + return shape + + +class ConversationTests(unittest.TestCase): + def test_every_dataset_is_pinned_to_a_commit(self): + for entry in DATASETS.values(): + corpus = performance_plan.read_json(performance_plan.ROOT / entry["corpus"]) + self.assertEqual(set(corpus), {"repo", "revision", "alias"}) + self.assertRegex(corpus["revision"], "^[0-9a-f]{40}$") + + def test_a_conversation_point_names_a_dataset_and_only_the_bound_it_runs_to(self): + with patch.object(performance_plan, "read_json", return_value=with_server(CONVERSATIONS)): + server, = performance_plan.scenario([CONVERSATIONS["id"]])["servers"] + self.assertEqual(performance_plan.lane_context({"context_per_lane": 8192}, server), 16384) + for change in ({"dataset": "wikipedia"}, {"dataset": ["agentx"]}, {"requests": 8}, {"duration_s": 59}, + {"duration_s": 3601}, {"depth": 0}, {"concurrency": 5}): + broken = json.loads(json.dumps(CONVERSATIONS)) + broken["points"][0].update(change) + with patch.object(performance_plan, "read_json", return_value=with_server(broken)): + with self.assertRaises(ValueError): + performance_plan.scenario([broken["id"]]) + + def test_a_conversation_servers_pool_holds_a_full_lane_for_each_conversation_in_flight(self): + reference = {"label": "reference", "kind": "llama-server", "binary": "/b/llama-server"} + for pool in (16384 * 4, 16384 * 4 - 1): + server = {**CONVERSATIONS, "pool_tokens": pool} + with patch.object(performance_plan, "read_json", return_value=with_server(server)): + if pool < 16384 * 4: + with self.assertRaises(ValueError): + performance_plan.scenario([server["id"]]) + continue + checked, = performance_plan.scenario([server["id"]])["servers"] + # Fitted, a conversation's failed request is a fault on every arm. + self.assertFalse(any(may_reject(reference, checked, point) for point in checked["points"])) + + def test_a_conversation_point_replays_its_dataset_instead_of_generated_prompts(self): + agentx, sharegpt = CONVERSATIONS["points"] + args = conversation_args("http://e", agentx, "m@r", "/t", 2, Path("/a"), 16384, {"alias": "traces"}) + self.assertEqual([args[args.index(flag) + 1] for flag in ("--scenario", "--public-dataset", + "--max-context-length", "--benchmark-duration")], + ["inferencex-agentx-mvp", "traces", "16384", "600"]) + self.assertIn("--unsafe-override", args) + full = conversation_args("http://e", {**agentx, "duration_s": 900}, "m@r", "/t", 2, Path("/a"), 16384, + {"alias": "traces"}) + self.assertNotIn("--unsafe-override", full) + chat = conversation_args("http://e", sharegpt, "m@r", "/t", 2, Path("/a"), 16384, {"alias": "sharegpt"}) + self.assertEqual([chat[chat.index(flag) + 1] for flag in ("--public-dataset", "--request-count", + "--concurrency", "--extra-inputs")], + ["sharegpt", "32", "4", "ignore_eos:true"]) + self.assertFalse([arg for arg in chat if arg.startswith("--synthetic") or arg == "--scenario"]) + + def test_a_conversation_point_checks_its_pin_before_and_after_even_when_aiperf_fails(self): + from subprocess import CalledProcessError + from tempfile import TemporaryDirectory + agentx = CONVERSATIONS["points"][0] + with TemporaryDirectory() as directory, patch("lib.performance_load.verify_corpus") as verify, \ + patch("lib.performance_load.command", side_effect=CalledProcessError(1, ["aiperf"])) as load: + with self.assertRaises(CalledProcessError): + run_point("http://e", agentx, "m@r", "/t", 2, Path(directory) / "run" / agentx["id"], + may_reject=False, context=16384) + self.assertTrue((Path(directory) / "run").is_dir()) + self.assertEqual([call.args[2] for call in verify.call_args_list], ["c1-agentx-before", "c1-agentx-after"]) + self.assertIn("--max-context-length", load.call_args.args[0]) + + def test_a_replaying_plan_is_bounded_by_its_time_and_estimates_it(self): + arm_list = performance_plan.arms("a" * 40, "b" * 40, None) + agentx = CONVERSATIONS["points"][0] + traces = {**CONVERSATIONS, "id": "lanes1-agentx", "lanes": 1, "points": [agentx]} + with patch.object(performance_plan, "read_json", return_value=with_server(traces)): + harness = performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 3, None, "any", + servers=[traces["id"]])["harness"] + self.assertEqual((harness["trace"]["kind"], harness["duration_s"]), ("file", 600 * 3 * 2)) + self.assertNotIn("request_count", harness) + generated = performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 3, None, "any")["harness"] + self.assertEqual(generated["trace"]["kind"], "synthetic") + self.assertNotIn("duration_s", generated) + self.assertAlmostEqual(performance_plan.measure_minutes(CONVERSATIONS, "metal"), + 0.5 + (120 + 600 + 120 + 32 * 4) / 60) + + class PlanTests(unittest.TestCase): candidate, baseline, pin = "a" * 40, "b" * 40, "c" * 40 @@ -458,7 +548,7 @@ def request(phase, error, metrics): def drive(self, directory, may_reject): return run_point("http://127.0.0.1:9337", self.point, "org/m@rev", "/t", 2, Path(directory), - may_reject=may_reject) + may_reject=may_reject, context=8192) def test_rejection_counts_failed_and_cut_short_requests_among_the_measured_ones(self): from tempfile import TemporaryDirectory @@ -650,6 +740,22 @@ def test_stored_rows_carry_their_arm_point_and_host_but_not_the_trace_pass(self) record["samples"] = [{**measured, "metrics": {"output_tok_s": None}, "rejected": rejected}] stored, = performance_report.rows(record, shape, {}, "job_1", {}) self.assertEqual((stored["output_tok_s"], json.loads(stored["rejected"])), (None, rejected)) + self.assertEqual((stored["dataset"], stored["duration_s"], stored["context_per_lane"]), + (None, None, shape["context_per_lane"])) + + def test_a_conversation_row_names_its_dataset_and_has_no_generated_shape(self): + shape = {**performance_plan.scenario(), "servers": [CONVERSATIONS]} + sample = {"model": "qwen35-4b", "round": 1, "arm": "candidate", "server": CONVERSATIONS["id"], + "point": "c1-agentx", "applied": {}, "unsupported": [], "metrics": {"output_tok_s": 40.0}, + "rejected": None} + record = {"harness": "d" * 40, "scenario_sha256": "e" * 64, "host": {"backend": "metal"}, + "arms": [{"label": "candidate", "kind": "skippy", "sha": "a" * 40, "binary_sha256": "f" * 64}], + "models": {"qwen35-4b": {"revision": "r1"}}, "samples": [sample]} + row, = performance_report.rows(record, shape, {}, "job_1", {}) + self.assertEqual((row["schema_version"], row["dataset"], row["duration_s"], row["context_per_lane"]), + (3, "agentx", 600, 16384)) + self.assertEqual((row["depth"], row["input_tokens"], row["requests"], row["request_rate"]), + (None, None, None, None)) if __name__ == "__main__": From 85fd8c1ff193d95161759a9b73eaa7ac5edc1115 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Mon, 30 Nov 2026 15:17:00 +1100 Subject: [PATCH 26/50] Add conversation servers for AgentX and ShareGPT A campaign can now name servers that replay real conversations: one lane at a 64K context for ten minutes of AgentX's Claude Code traces, and four lanes for 64 ShareGPT turns, each with a grid and a branch checkpoint admission variant so admission can be tuned on other model families. A conversation point takes minutes, so like a variant these servers run only when a plan names them in SERVERS, and a default campaign keeps its cells and its time. The workflow's models input now names ci/inference-artifacts.json ids, which is what the plan accepts since comparisons cover other families. --- .github/workflows/inference-performance.yml | 2 +- ci/INFERENCE_PERFORMANCE.md | 6 ++ ci/inference-performance.json | 55 +++++++++++++++++++ scripts/lib/performance_plan.py | 10 ++-- .../tests/inference_performance_contracts.py | 18 ++++-- 5 files changed, 82 insertions(+), 9 deletions(-) diff --git a/.github/workflows/inference-performance.yml b/.github/workflows/inference-performance.yml index e14c21e5..5ed796e3 100644 --- a/.github/workflows/inference-performance.yml +++ b/.github/workflows/inference-performance.yml @@ -15,7 +15,7 @@ on: type: boolean default: true models: - description: Comma-separated ci/inference-ladder.json ids. + description: Comma-separated ci/inference-artifacts.json model ids. type: string default: qwen35-4b nodes: diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index 2cb0d449..17ab96fc 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -127,6 +127,12 @@ output, sixteen lanes with and without a 4,096-token shared prefix in a 32K pool, and four lanes at that depth with 16K and 32K pools: the cells where KV pressure and batching show. +Two more servers replay conversations, minutes a point: one lane at a 64K +context for ten minutes of AgentX's traces, and four lanes for 64 ShareGPT +turns, each with a grid and a branch admission variant. Like a variant, each +runs only when a plan names it in `SERVERS`, so a default campaign keeps its +cells and its time. + A server with `skippy_flags` is a variant of another: the same lanes and pool, with Skippy flags of its own, such as a larger prefill step. It runs only when a plan names it in `SERVERS`, so a campaign keeps the same cells. Its flags reach diff --git a/ci/inference-performance.json b/ci/inference-performance.json index 25a8470e..d7df7af1 100644 --- a/ci/inference-performance.json +++ b/ci/inference-performance.json @@ -172,6 +172,61 @@ {"id": "c4-depth4096-pool32k-admission-branch", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 16}, {"id": "c4-long-output-admission-branch", "concurrency": 4, "depth": 0, "input_tokens": 512, "output_tokens": 2048, "requests": 8} ] + }, + { + "id": "lanes1-agentx-ctx64k", + "lanes": 1, + "pool_tokens": null, + "context_per_lane": 65536, + "points": [ + {"id": "c1-agentx", "dataset": "agentx", "concurrency": 1, "duration_s": 600} + ] + }, + { + "id": "lanes4-sharegpt", + "lanes": 4, + "pool_tokens": null, + "points": [ + {"id": "c4-sharegpt", "dataset": "sharegpt", "concurrency": 4, "requests": 64} + ] + }, + { + "id": "lanes1-agentx-ctx64k-admission-grid", + "lanes": 1, + "pool_tokens": null, + "context_per_lane": 65536, + "skippy_flags": {"batch-checkpoint-admission": "grid"}, + "points": [ + {"id": "c1-agentx-admission-grid", "dataset": "agentx", "concurrency": 1, "duration_s": 600} + ] + }, + { + "id": "lanes4-sharegpt-admission-grid", + "lanes": 4, + "pool_tokens": null, + "skippy_flags": {"batch-checkpoint-admission": "grid"}, + "points": [ + {"id": "c4-sharegpt-admission-grid", "dataset": "sharegpt", "concurrency": 4, "requests": 64} + ] + }, + { + "id": "lanes1-agentx-ctx64k-admission-branch", + "lanes": 1, + "pool_tokens": null, + "context_per_lane": 65536, + "skippy_flags": {"batch-checkpoint-admission": "branch"}, + "points": [ + {"id": "c1-agentx-admission-branch", "dataset": "agentx", "concurrency": 1, "duration_s": 600} + ] + }, + { + "id": "lanes4-sharegpt-admission-branch", + "lanes": 4, + "pool_tokens": null, + "skippy_flags": {"batch-checkpoint-admission": "branch"}, + "points": [ + {"id": "c4-sharegpt-admission-branch", "dataset": "sharegpt", "concurrency": 4, "requests": 64} + ] } ] } diff --git a/scripts/lib/performance_plan.py b/scripts/lib/performance_plan.py index 2d1eb419..b59fc1e8 100644 --- a/scripts/lib/performance_plan.py +++ b/scripts/lib/performance_plan.py @@ -103,20 +103,21 @@ def conversation_point(point, context, pool): def scenario(named=None): """The checked scenario; with `named`, only those servers and their points, to rerun one workload without the rest. A server with its own `skippy_flags` is a variant of another, - run only when named, so a campaign keeps the same cells.""" + and one that replays conversations takes minutes a point: both run only when named, so a + campaign keeps the same cells and about the same time.""" value = read_json(SCENARIO) if (set(value) != {"schema_version", "context_per_lane", "warmup_requests", "servers"} or value["schema_version"] != 1 or not value["servers"]): raise ValueError("invalid performance scenario") count(value["context_per_lane"], "context_per_lane") count(value["warmup_requests"], "warmup_requests", 0) - servers, points, variants = set(), set(), set() + servers, points, named_only = set(), set(), set() for server in value["servers"]: if set(server) - {"skippy_flags", "context_per_lane"} != SERVER_FIELDS or not server["points"]: raise ValueError("invalid performance server") if "skippy_flags" in server: skippy_flags(server) - variants.add(server["id"]) + named_only.add(server["id"]) if server["id"] in servers: raise ValueError(f'duplicate performance server: {server["id"]}') servers.add(server["id"]) @@ -130,12 +131,13 @@ def scenario(named=None): points.add(point["id"]) if "dataset" in point: conversation_point(point, context, server["pool_tokens"]) + named_only.add(server["id"]) else: generated_point(point, context) if point["concurrency"] > lanes: raise ValueError(f'{point["id"]}: concurrency exceeds the server\'s lanes') if named is None: - return {**value, "servers": [server for server in value["servers"] if server["id"] not in variants]} + return {**value, "servers": [server for server in value["servers"] if server["id"] not in named_only]} unknown = set(named) - servers if not named or unknown: raise ValueError(f"unknown performance servers: {', '.join(sorted(unknown)) or 'none named'}") diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index eb690325..4e3f5210 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -78,8 +78,8 @@ def test_a_variant_cannot_set_what_the_harness_sets_or_nothing(self): CONVERSATIONS = {"id": "lanes4-conversations", "lanes": 4, "pool_tokens": None, "context_per_lane": 16384, - "points": [{"id": "c1-agentx", "dataset": "agentx", "concurrency": 1, "duration_s": 600}, - {"id": "c4-sharegpt", "dataset": "sharegpt", "concurrency": 4, "requests": 32}]} + "points": [{"id": "test-c1-agentx", "dataset": "agentx", "concurrency": 1, "duration_s": 600}, + {"id": "test-c4-sharegpt", "dataset": "sharegpt", "concurrency": 4, "requests": 32}]} def with_server(server): @@ -90,6 +90,15 @@ def with_server(server): class ConversationTests(unittest.TestCase): + def test_the_shipped_conversation_servers_run_only_when_named(self): + shipped = performance_plan.read_json(performance_plan.SCENARIO)["servers"] + replaying = [server["id"] for server in shipped if any("dataset" in point for point in server["points"])] + self.assertFalse(set(replaying) & {server["id"] for server in performance_plan.scenario()["servers"]}) + named = performance_plan.scenario(replaying)["servers"] + self.assertEqual({point["dataset"] for server in named for point in server["points"]}, set(DATASETS)) + self.assertEqual({server.get("skippy_flags", {}).get("batch-checkpoint-admission") for server in named}, + {None, "grid", "branch"}) + def test_every_dataset_is_pinned_to_a_commit(self): for entry in DATASETS.values(): corpus = performance_plan.read_json(performance_plan.ROOT / entry["corpus"]) @@ -147,7 +156,8 @@ def test_a_conversation_point_checks_its_pin_before_and_after_even_when_aiperf_f run_point("http://e", agentx, "m@r", "/t", 2, Path(directory) / "run" / agentx["id"], may_reject=False, context=16384) self.assertTrue((Path(directory) / "run").is_dir()) - self.assertEqual([call.args[2] for call in verify.call_args_list], ["c1-agentx-before", "c1-agentx-after"]) + self.assertEqual([call.args[2] for call in verify.call_args_list], + ["test-c1-agentx-before", "test-c1-agentx-after"]) self.assertIn("--max-context-length", load.call_args.args[0]) def test_a_replaying_plan_is_bounded_by_its_time_and_estimates_it(self): @@ -746,7 +756,7 @@ def test_stored_rows_carry_their_arm_point_and_host_but_not_the_trace_pass(self) def test_a_conversation_row_names_its_dataset_and_has_no_generated_shape(self): shape = {**performance_plan.scenario(), "servers": [CONVERSATIONS]} sample = {"model": "qwen35-4b", "round": 1, "arm": "candidate", "server": CONVERSATIONS["id"], - "point": "c1-agentx", "applied": {}, "unsupported": [], "metrics": {"output_tok_s": 40.0}, + "point": "test-c1-agentx", "applied": {}, "unsupported": [], "metrics": {"output_tok_s": 40.0}, "rejected": None} record = {"harness": "d" * 40, "scenario_sha256": "e" * 64, "host": {"backend": "metal"}, "arms": [{"label": "candidate", "kind": "skippy", "sha": "a" * 40, "binary_sha256": "f" * 64}], From f61de2caffd0cc348958f8f3bde774bd7b4e7cb1 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Mon, 30 Nov 2026 15:17:00 +1100 Subject: [PATCH 27/50] Serve each model no more context than it was trained on The AgentX server's 64K lane is longer than several families were trained on: phi-4 at 16K, and gemma3-1b, Mistral-Small and LFM2 at 32K. Past its trained context a model has never seen a position and writes nonsense, which a mixture of experts routes through other experts than real text, so its speed would not be its speed. Admission now reads `.context_length` from the model's GGUF header and records it beside the revision. Each server is started with its lane cut to that length, AgentX keeps only the traces that fit, and rows record the lane the model was served. A generated point longer than a model's trained context fails that model's step rather than running past it. Admission still counts only the fixed reserve, not the KV cache a longer lane needs; the limits now say so. --- ci/INFERENCE_PERFORMANCE.md | 20 +++++- scripts/inference-performance.py | 16 +++-- scripts/lib/gguf_header.py | 64 +++++++++++++++++ scripts/lib/performance_plan.py | 14 +++- scripts/lib/performance_report.py | 4 +- .../tests/inference_performance_contracts.py | 68 +++++++++++++++++-- 6 files changed, 171 insertions(+), 15 deletions(-) create mode 100644 scripts/lib/gguf_header.py diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index 17ab96fc..a7580b0e 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -170,6 +170,15 @@ answers beside its AIPerf export. A server may set its own `context_per_lane` fo conversations longer than the scenario's, and its pool, if it has one, must hold that much for each conversation in flight. +Every model is served a lane no longer than it was trained on: the server's +context per lane, cut to the `context_length` in the model's GGUF header, which +the record keeps beside the model's revision. Past it a model has never seen a +position and writes nonsense, which a mixture of experts routes through other +experts than real text, so its speed would not be its speed. A shorter lane also +keeps only the AgentX traces that fit it, so a model's conversation numbers +compare its arms with each other, not with another model's. A generated point +longer than a model's trained context fails that model's step. + An arm that lacks a setting, such as `--kv-pool-tokens` on a commit from before the pool existed, runs without it. Each sample records what was applied and what the arm did not support. All arms are probed before model measurements begin. @@ -233,9 +242,10 @@ Stored rows retain their actual timestamps for future trend analysis. For graphs over time it also writes `LABEL-rows.jsonl` beside each job's `LABEL-performance.json`, LABEL being the job's node or `any`: one row per measured sample, with the job, when the run started, the host, the arm's commit and when it was -committed, the model revision, the server's lanes, pool and context per lane, the -point's concurrency, dataset, depth, token counts, requests and duration (null -where the point has none), the round, and each metric as its own column. +committed, the model revision, the server's lanes and pool, the lane the model +was served, the point's concurrency, dataset, depth, token counts, requests and +duration (null where the point has none), the round, and each metric as its own +column. A rejected point keeps its row, with null metrics and the `rejected` entry as JSON text. An arm taken from a pull request has `on_main` false and its number in `pull_request`; one taken from a branch has `on_main` false and its name in `branch`; @@ -258,3 +268,7 @@ group by all order by committed_at, model, point, arm; and `ignore_eos` handling are taken from its documentation; the first run confirms them, and a renamed metric shows as null with the raw export kept. - Nothing here has run on hardware yet. +- Admission counts weights and a fixed reserve, sized for the CI ladder at a + 32K pool, not the KV cache a longer lane needs: about 10 GiB for a 24B dense + model at 64K. A model whose cache outgrows the reserve can spill KV to host + memory on a discrete GPU; its server log shows the KV buffer sizes. diff --git a/scripts/inference-performance.py b/scripts/inference-performance.py index 976f310b..a5475fdd 100644 --- a/scripts/inference-performance.py +++ b/scripts/inference-performance.py @@ -20,6 +20,7 @@ from lib.ci_artifacts import digest, read_json, write_json from lib.ci_process import cancel_on_signal, capture, command, start, stop from lib.ci_smoke import curl +from lib.gguf_header import trained_context from lib.inference_checks import ENDPOINT, offload from lib.inference_inputs import admit as admit_model from lib.inference_inputs import fixture @@ -27,8 +28,8 @@ from lib.performance_arms import build, capabilities, may_reject, server_args, server_flags, supports from lib.performance_backends import BACKENDS from lib.performance_load import request_rate, run_point, tokenizer -from lib.performance_plan import (SCENARIO, arms, branch_name, job_spec, lane_context, models, nodes, - pull_request_head, pull_request_number, scenario) +from lib.performance_plan import (SCENARIO, arms, branch_name, job_spec, model_context, models, nodes, + pull_request_head, pull_request_number, request_tokens, scenario) from lib.performance_report import markdown, rows, summarize REPO = "Mesh-LLM/skippy" @@ -302,7 +303,11 @@ def measure(built, help_text, model, inputs, key, index, server, shape, output, prefixes=("MTL",), backend=None): """`index` is the round, or None for a diagnostic pass that writes `trace`.""" coordinate = f'{inputs["repo"]}@{inputs["revision"]}' - context = lane_context(shape, server) + context = model_context(shape, server, inputs["trained_context"]) + beyond = [point["id"] for point in server["points"] + if "dataset" not in point and request_tokens(point) > context] + if beyond: + raise ValueError(f'{key} was trained on {context} tokens, fewer than {", ".join(beyond)} sends') args, applied, missing = server_args(built, help_text, model, coordinate, context, server) overrides = None if trace is None else traced(built, help_text, args, applied, missing, trace) pass_name = "trace" if index is None else f"r{index + 1}" @@ -377,8 +382,9 @@ def prepare_model(key): if available < sum(file["size"] for file in inputs["files"]) + entry["reserve_gib"] * 1024**3: raise ValueError(f"{key}: insufficient {plan['backend']} free memory for weights and reserve") model = admit_model(key, inputs) - inputs = {**inputs, "tokenizer_path": str(tokenizer(inputs))} - record["models"][key] = {"repo": inputs["repo"], "revision": inputs["revision"], "files": inputs["files"]} + inputs = {**inputs, "tokenizer_path": str(tokenizer(inputs)), "trained_context": trained_context(model)} + record["models"][key] = {"repo": inputs["repo"], "revision": inputs["revision"], "files": inputs["files"], + "trained_context": inputs["trained_context"]} MODELS.mkdir(parents=True, exist_ok=True) write_json(MODELS / f"{key}.json", {"model": str(model), "inputs": inputs}) write_json(artifacts() / RECORD, record) diff --git a/scripts/lib/gguf_header.py b/scripts/lib/gguf_header.py new file mode 100644 index 00000000..a70e4639 --- /dev/null +++ b/scripts/lib/gguf_header.py @@ -0,0 +1,64 @@ +"""Read what a model was trained for from its GGUF header, without loading the weights.""" + +import struct + +# Value types of a fixed size, as struct formats; strings and arrays carry their own lengths. +FIXED = {0: "B", 1: "b", 2: "H", 3: "h", 4: "I", 5: "i", 6: "f", 7: "?", 10: "Q", 11: "q", 12: "d"} +STRING, ARRAY = 8, 9 + + +def read(stream, fmt): + size = struct.calcsize("<" + fmt) + data = stream.read(size) + if len(data) != size: + raise ValueError("truncated GGUF header") + return struct.unpack("<" + fmt, data)[0] + + +def string(stream): + length = read(stream, "Q") + data = stream.read(length) + if len(data) != length: + raise ValueError("truncated GGUF header") + return data.decode("utf-8") + + +def value(stream, kind): + """A scalar or string value; an array is skipped, as none is needed here and the + tokenizer's hold every token in the vocabulary.""" + if kind in FIXED: + return read(stream, FIXED[kind]) + if kind == STRING: + return string(stream) + if kind != ARRAY: + raise ValueError(f"unknown GGUF value type {kind}") + item, length = read(stream, "I"), read(stream, "Q") + if item in FIXED: + stream.seek(struct.calcsize("<" + FIXED[item]) * length, 1) + else: + for _ in range(length): + value(stream, item) + return None + + +def trained_context(path): + """`.context_length`: the longest sequence the model was trained on. + For a split model, the first shard holds the header.""" + with open(path, "rb") as stream: + if stream.read(4) != b"GGUF" or read(stream, "I") not in (2, 3): + raise ValueError(f"{path} is not a GGUF v2 or v3 file") + read(stream, "Q") + architecture, lengths = None, {} + for _ in range(read(stream, "Q")): + key, kind = string(stream), read(stream, "I") + found = value(stream, kind) + if key == "general.architecture": + architecture = found + elif key.endswith(".context_length"): + lengths[key] = found + if architecture is not None and f"{architecture}.context_length" in lengths: + length = lengths[f"{architecture}.context_length"] + if type(length) is not int or length < 1: + raise ValueError(f"{path}: {architecture}.context_length is not a positive count") + return length + raise ValueError(f"{path} names no context length for its architecture") diff --git a/scripts/lib/performance_plan.py b/scripts/lib/performance_plan.py index b59fc1e8..f4d5bf3c 100644 --- a/scripts/lib/performance_plan.py +++ b/scripts/lib/performance_plan.py @@ -70,6 +70,18 @@ def lane_context(shape, server): return server.get("context_per_lane", shape["context_per_lane"]) +def model_context(shape, server, trained): + """The lane a model is served with: the server's, cut to what the model was trained on. + Past that it has never seen a position, so it writes nonsense, and a mixture of experts + routes nonsense through other experts than real text would.""" + return min(lane_context(shape, server), trained) + + +def request_tokens(point): + """What one request of generated prompts holds at its longest: prefix, prompt and output.""" + return point["depth"] + point["input_tokens"] + point["output_tokens"] + + def generated_point(point, context): """A point of generated prompts: its request shape, which one lane must hold whole.""" if set(point) - {"request_rate"} != POINT_FIELDS: @@ -79,7 +91,7 @@ def generated_point(point, context): for field in ("concurrency", "input_tokens", "output_tokens", "requests"): count(point[field], f'{point["id"]} {field}') count(point["depth"], f'{point["id"]} depth', 0) - if point["depth"] + point["input_tokens"] + point["output_tokens"] > context: + if request_tokens(point) > context: raise ValueError(f'{point["id"]}: one request exceeds a lane\'s context') diff --git a/scripts/lib/performance_report.py b/scripts/lib/performance_report.py index 4448a3ee..b465a554 100644 --- a/scripts/lib/performance_report.py +++ b/scripts/lib/performance_report.py @@ -9,7 +9,7 @@ from .inference_markdown import HEALTH_LABELS, health_sections, plain, table from .inference_nightly_metrics import metric_value from .performance_load import request_rate -from .performance_plan import lane_context +from .performance_plan import model_context # Higher is better for rates; lower is better for latencies. HEADLINE = {"output_tok_s": "higher", "ttft_ms_p50": "lower", "itl_ms_p50": "lower"} @@ -165,7 +165,7 @@ def rows(record, shape, committed_at, job, pull_requests, branches=None): "pull_request": pull_request, "branch": branch, "model": sample["model"], "model_revision": record["models"][sample["model"]]["revision"], "server": sample["server"], "lanes": server["lanes"], "pool_tokens": server["pool_tokens"], - "context_per_lane": lane_context(shape, server), + "context_per_lane": model_context(shape, server, record["models"][sample["model"]]["trained_context"]), "point": sample["point"], "concurrency": point["concurrency"], "dataset": point.get("dataset"), "depth": point.get("depth"), "input_tokens": point.get("input_tokens"), "output_tokens": point.get("output_tokens"), "requests": point.get("requests"), diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index 4e3f5210..a7969e04 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -1,6 +1,7 @@ """Offline checks for the performance comparison's plan, servers, parsing and report.""" import json +import struct import unittest from pathlib import Path from runpy import run_path @@ -8,6 +9,7 @@ from unittest.mock import Mock, patch from lib import performance_arms, performance_backends, performance_plan +from lib.gguf_header import trained_context from lib.performance_arms import REQUIRED, capabilities, may_reject, server_args from lib.performance_load import (DATASETS, conversation_args, measurements, profile_args, rejection, request_rate, run_point) @@ -89,7 +91,63 @@ def with_server(server): return shape +def gguf(path, *pairs): + """A GGUF v3 header of (key, type, value) pairs and no tensors; arrays are (item type, values).""" + def string(text): + data = text.encode() + return struct.pack(" Date: Mon, 30 Nov 2026 19:10:41 +1100 Subject: [PATCH 28/50] Let a performance plan compare one commit's servers A plan had to name a baseline commit, so comparing runtime flags on one build, such as branch against grid checkpoint admission, meant building the candidate twice to satisfy a baseline the comparison never used. Without a baseline, a plan now compares its named servers with each other. They must differ in their skippy_flags and nothing else, so a change between them is the flags'; admission and the job both refuse any other set. The workflow still always names a baseline. --- ci/INFERENCE_PERFORMANCE.md | 8 ++++ scripts/inference-performance.py | 13 ++++--- scripts/lib/performance_plan.py | 38 +++++++++++++++---- .../tests/inference_performance_contracts.py | 27 +++++++++++++ 4 files changed, 74 insertions(+), 12 deletions(-) diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index a7580b0e..e211e3af 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -141,6 +141,14 @@ itself (context, lanes, pool, speculation, telemetry). An arm whose build lacks one of them fails before any round, since without it the variant would measure the server it varies. +A plan admitted without `BASELINE` compares servers instead of commits: the +candidate alone, on two or more servers named in `SERVERS` that differ in their +`skippy_flags` and nothing else, such as a server and its variant or two +variants of one server. Admission and the job both refuse any other set, since +a change between servers of different shapes would not be the flags'. The +workflow always names a baseline, so admit such a plan with +`just inference-performance-admit`. + A point drives its server one of three ways. By default AIPerf keeps `concurrency` requests in flight, sending the next as one finishes. Requests that finish together are then replaced together, so a policy that lets them finish together keeps every diff --git a/scripts/inference-performance.py b/scripts/inference-performance.py index a5475fdd..6e4b70e0 100644 --- a/scripts/inference-performance.py +++ b/scripts/inference-performance.py @@ -28,8 +28,8 @@ from lib.performance_arms import build, capabilities, may_reject, server_args, server_flags, supports from lib.performance_backends import BACKENDS from lib.performance_load import request_rate, run_point, tokenizer -from lib.performance_plan import (SCENARIO, arms, branch_name, job_spec, model_context, models, nodes, - pull_request_head, pull_request_number, request_tokens, scenario) +from lib.performance_plan import (SCENARIO, arms, branch_name, comparison, job_spec, model_context, models, + nodes, pull_request_head, pull_request_number, request_tokens, scenario) from lib.performance_report import markdown, rows, summarize REPO = "Mesh-LLM/skippy" @@ -102,13 +102,15 @@ def committed_at(arm_list): def admit(evidence): harness = capture(["git", "rev-parse", "HEAD"]).strip() candidate, candidate_pull, candidate_branch = resolve(os.environ["CANDIDATE"]) - baseline, baseline_pull, baseline_branch = resolve(os.environ["BASELINE"]) + baseline, baseline_pull, baseline_branch = (resolve(os.environ["BASELINE"]) if os.environ.get("BASELINE") + else (None, None, None)) pull_requests = {"candidate": candidate_pull, "baseline": baseline_pull} branches = {"candidate": candidate_branch, "baseline": baseline_branch} with_reference = os.environ.get("REFERENCE", "true") == "true" trace = os.environ.get("TRACE", "false") == "true" backend = os.environ.get("BACKEND") or "metal" - arm_list = (arms(candidate, baseline, reference_pin(candidate), reference_pin(baseline)) if with_reference + arm_list = (arms(candidate, baseline, reference_pin(candidate), + None if baseline is None else reference_pin(baseline)) if with_reference else arms(candidate, baseline, None)) keys = models([key.strip() for key in os.environ["MODELS"].split(",") if key.strip()]) pins = nodes([node.strip() for node in os.environ.get("NODES", "").split(",") if node.strip()]) @@ -241,13 +243,14 @@ def native_plan(): if capture(["git", "rev-parse", "HEAD"]).strip() != plan["harness"]: raise ValueError("harness checkout differs from the admitted harness commit") labels = {arm["label"]: arm["sha"] for arm in plan["arms"]} - expected = arms(labels["candidate"], labels["baseline"], labels.get("reference"), + expected = arms(labels["candidate"], labels.get("baseline"), labels.get("reference"), labels.get("baseline-reference")) if plan.get("backend") not in BACKENDS: raise ValueError(f'performance plan backend {plan.get("backend")!r} has no entry in the table') if (plan["arms"] != expected or plan["models"] != models(plan["models"]) or type(plan.get("trace")) is not bool): raise ValueError("performance plan arms, models or trace flag are malformed") + comparison(plan["arms"], plan.get("servers")) return plan diff --git a/scripts/lib/performance_plan.py b/scripts/lib/performance_plan.py index f4d5bf3c..c3e79659 100644 --- a/scripts/lib/performance_plan.py +++ b/scripts/lib/performance_plan.py @@ -178,15 +178,16 @@ def pull_request_head(pull, repository): def arms(candidate, baseline, reference, baseline_reference=None): """Candidate and baseline are Skippy commits; reference is llama.cpp's own server at the candidate's pin. A baseline on another pin adds llama.cpp at that pin as baseline-reference, so a change that - moves the pin shows whether llama.cpp moved as well as whether Skippy did.""" - if not SHA.fullmatch(candidate) or not SHA.fullmatch(baseline): + moves the pin shows whether llama.cpp moved as well as whether Skippy did. Without a baseline the + plan compares the candidate's servers with each other instead: see `comparison`.""" + commits = {"candidate": candidate} if baseline is None else {"candidate": candidate, "baseline": baseline} + if not all(SHA.fullmatch(sha) for sha in commits.values()): raise ValueError("arms must be immutable 40-digit commit SHAs") - result = [{"label": "candidate", "kind": "skippy", "sha": candidate, "path": "candidate"}, - {"label": "baseline", "kind": "skippy", "sha": baseline, "path": "baseline"}] + result = [{"label": label, "kind": "skippy", "sha": sha, "path": label} for label, sha in commits.items()] pins = [("reference", reference)] if baseline_reference not in (None, reference): - if reference is None: - raise ValueError("a baseline reference needs the reference arm") + if reference is None or baseline is None: + raise ValueError("a baseline reference needs the baseline and reference arms") pins.append(("baseline-reference", baseline_reference)) for label, pin in pins: if pin is None: @@ -197,6 +198,27 @@ def arms(candidate, baseline, reference, baseline_reference=None): return result +def comparison(arm_list, servers): + """What a plan compares: the candidate with the baseline commit on every server, or, without a + baseline, the candidate's named servers with each other. Those must differ in their + `skippy_flags` and nothing else, so whatever changes between them is the flags'.""" + if any(arm["label"] == "baseline" for arm in arm_list): + return "commits" + shape = scenario(servers) if servers else None + if shape is None or len(shape["servers"]) < 2: + raise ValueError("a plan without a baseline compares servers, so it must name at least two") + + def setup(server): + return (server["lanes"], server["pool_tokens"], lane_context(shape, server), + [{key: value for key, value in point.items() if key != "id"} for point in server["points"]]) + + first, *rest = shape["servers"] + flags = [json.dumps(server.get("skippy_flags", {}), sort_keys=True) for server in shape["servers"]] + if any(setup(server) != setup(first) for server in rest) or len(set(flags)) != len(flags): + raise ValueError("servers compared with each other must differ in their skippy_flags and nothing else") + return "servers" + + def round_order(arm_list, index): """Each round starts one arm later, so no arm always runs first on a cold or hot machine.""" shift = index % len(arm_list) @@ -283,6 +305,7 @@ def job_spec(harness, arm_list, keys, rounds, node, label, *, trace=False, backe if backend not in BACKENDS: raise ValueError(f"unknown backend {backend!r}; the table holds {', '.join(sorted(BACKENDS))}") shape = scenario(servers) + compared = comparison(arm_list, servers) entry = BACKENDS[backend] for server in shape["servers"]: for point in server["points"]: @@ -318,7 +341,8 @@ def job_spec(harness, arm_list, keys, rounds, node, label, *, trace=False, backe return { "name": f"skippy-inference-performance-{label}", "description": entry["description"] + " of " + ", ".join( - f'{arm["label"]} {arm["sha"][:12]}' for arm in arm_list) + f" on {', '.join(keys)}.", + f'{arm["label"]} {arm["sha"][:12]}' for arm in arm_list) + + (f" across {', '.join(servers)}" if compared == "servers" else "") + f" on {', '.join(keys)}.", "priority": 50, "target": target, "runtime": { diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index a7969e04..aa13d6bf 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -298,6 +298,33 @@ def test_every_arm_leads_one_round(self): firsts = [performance_plan.round_order(arm_list, index)[0]["label"] for index in range(3)] self.assertEqual(sorted(firsts), ["baseline", "candidate", "reference"]) + def test_without_a_baseline_a_plan_compares_servers_that_differ_only_in_flags(self): + self.assertEqual([arm["label"] for arm in performance_plan.arms(self.candidate, None, self.pin)], + ["candidate", "reference"]) + with self.assertRaises(ValueError): + performance_plan.arms(self.candidate, None, self.pin, "d" * 40) + alone = performance_plan.arms(self.candidate, None, None) + servers = ["lanes4-pool32k", "lanes4-pool32k-prefill2048"] + self.assertEqual(performance_plan.comparison(alone, servers), "servers") + self.assertEqual(performance_plan.comparison(performance_plan.arms(self.candidate, self.baseline, None), None), + "commits") + spec = performance_plan.job_spec("d" * 40, alone, ["qwen35-4b"], 3, None, "any", servers=servers) + self.assertEqual([line for line in spec["runtime"]["command"].splitlines() if "build-arm" in line], + ["just inference-performance-build-arm candidate"]) + native_plan = run_path(str(Path(__file__).resolve().parents[1] / "inference-performance.py"))["native_plan"] + plan = spec["runtime"]["env"]["SKIPPY_PERFORMANCE_PLAN"] + with patch.dict(native_plan.__globals__, capture=lambda _: "d" * 40), \ + patch.dict("os.environ", SKIPPY_PERFORMANCE_PLAN=plan): + self.assertEqual(native_plan(), json.loads(plan)) + for named in (None, ["lanes4-pool32k"], ["lanes4-pool32k", "lanes1-agentx-ctx64k"]): + with self.assertRaises(ValueError): + performance_plan.job_spec("d" * 40, alone, ["qwen35-4b"], 3, None, "any", servers=named) + twin = {**performance_plan.scenario([servers[1]])["servers"][0], "id": "test-twin"} + twin["points"] = [{**point, "id": "test-twin-" + point["id"]} for point in twin["points"]] + with patch.object(performance_plan, "read_json", return_value=with_server(twin)): + with self.assertRaises(ValueError): + performance_plan.comparison(alone, [servers[1], "test-twin"]) + def test_job_runs_every_arm_from_its_own_checkout_on_a_metal_host(self): arm_list = performance_plan.arms(self.candidate, self.baseline, self.pin) spec = performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 3, "macstudio-2l0352", "m1") From e5ba256450712f2f0e611240c1ae124e555b3624 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Mon, 30 Nov 2026 20:44:17 +1100 Subject: [PATCH 29/50] Report a server comparison against its first server A plan that compares one commit's servers had no baseline arm, so every row's Change read "New series". The report now measures each server's candidate against the first server named, at the point in the same place, and marks the first server's rows as the control. The health summary uses the same control as its reference. --- ci/INFERENCE_PERFORMANCE.md | 3 +- scripts/inference-performance.py | 7 +++- scripts/lib/performance_report.py | 39 ++++++++++++++++--- .../tests/inference_performance_contracts.py | 16 ++++++++ 4 files changed, 57 insertions(+), 8 deletions(-) diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index e211e3af..ccb7b49f 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -145,7 +145,8 @@ A plan admitted without `BASELINE` compares servers instead of commits: the candidate alone, on two or more servers named in `SERVERS` that differ in their `skippy_flags` and nothing else, such as a server and its variant or two variants of one server. Admission and the job both refuse any other set, since -a change between servers of different shapes would not be the flags'. The +a change between servers of different shapes would not be the flags'. Its +report compares each server with the first one named, point for point. The workflow always names a baseline, so admit such a plan with `just inference-performance-admit`. diff --git a/scripts/inference-performance.py b/scripts/inference-performance.py index 6e4b70e0..2e919a8d 100644 --- a/scripts/inference-performance.py +++ b/scripts/inference-performance.py @@ -30,7 +30,7 @@ from lib.performance_load import request_rate, run_point, tokenizer from lib.performance_plan import (SCENARIO, arms, branch_name, comparison, job_spec, model_context, models, nodes, pull_request_head, pull_request_number, request_tokens, scenario) -from lib.performance_report import markdown, rows, summarize +from lib.performance_report import against_control, markdown, rows, summarize REPO = "Mesh-LLM/skippy" LLAMA_REPO = "ggml-org/llama.cpp" @@ -199,7 +199,10 @@ def collect(pilot, job, plan, label, evidence): download(pilot, run_id, "traces.tar.gz", evidence / f"{label}-traces.tar.gz") host = f'{result["host"].get("gpu") or result["host"].get("chip") or "unknown device"}' \ f' ({result["host"].get("node") or "unknown node"})' - return markdown(f"Inference performance: {label}", host, summarize(result["samples"]), result) + summary = summarize(result["samples"]) + if comparison(plan["arms"], plan.get("servers")) == "servers": + against_control(summary, scenario(plan["servers"]), plan["servers"]) + return markdown(f"Inference performance: {label}", host, summary, result) def dispatch(evidence): diff --git a/scripts/lib/performance_report.py b/scripts/lib/performance_report.py index b465a554..7a4985be 100644 --- a/scripts/lib/performance_report.py +++ b/scripts/lib/performance_report.py @@ -60,21 +60,44 @@ def cell(stats, rejected): return f"{measured}; rejected n={rejected}" if rejected else measured -def described(row, delta, measured, previous): - result = classify(row["metric"], row["arms"][measured]["median"], row["arms"][previous]["median"]) +def against_control(rows, shape, servers): + """In a comparison of servers, each server's candidate against the first server named, at the point + in the same place: the servers differ only in their flags, so a change between them is the flags'.""" + places = {server["id"]: [point["id"] for point in server["points"]] for server in shape["servers"]} + control = servers[0] + candidate = {(row["model"], row["server"], row["point"], row["metric"]): row["arms"].get("candidate") + for row in rows} + for row in rows: + twin = places[control][places[row["server"]].index(row["point"])] + row["control"] = {"server": control, + "stats": candidate.get((row["model"], control, twin, row["metric"]))} + row["candidate_vs_control"] = (None if row["server"] == control + else change(row["arms"].get("candidate"), row["control"]["stats"])) + return rows + + +def described(metric, delta, measured, previous): + result = classify(metric, measured["median"], previous["median"]) overlap = "; round ranges overlap" if delta["ranges_overlap"] else "; round ranges do not overlap" return f'{delta["percent"]:+.2f}% · {HEALTH_LABELS[result]}{overlap}' def verdict(row): + arms = row["arms"] + if "control" in row: + if row["server"] == row["control"]["server"]: + return "Control" + delta = row["candidate_vs_control"] + return "New series" if delta is None else described(row["metric"], delta, arms["candidate"], + row["control"]["stats"]) delta = row["candidate_vs_baseline"] - return "New series" if delta is None else described(row, delta, "candidate", "baseline") + return "New series" if delta is None else described(row["metric"], delta, arms["candidate"], arms["baseline"]) def llama_change(row): """llama.cpp at the candidate's pin against the baseline's: moving with Skippy means llama.cpp moved.""" - delta = row["reference_vs_baseline_reference"] - return "—" if delta is None else described(row, delta, "reference", "baseline-reference") + delta, arms = row["reference_vs_baseline_reference"], row["arms"] + return "—" if delta is None else described(row["metric"], delta, arms["reference"], arms["baseline-reference"]) def report_view(host, rows, record): @@ -98,6 +121,8 @@ def report_view(host, rows, record): for label, title in ARM_TITLES.items() if label in arms]} if "baseline" in arms: metric["reference"] = {"value": arms["baseline"]["median"]} + elif row.get("candidate_vs_control"): + metric["reference"] = {"value": row["control"]["stats"]["median"]} configuration["metrics"].append(metric) run = {"id": "controlled", "source_sha": candidate["sha"], "started_at": record["started_at"], "profile": "controlled performance", "measurement_kind": "controlled", "outcome": "passed", @@ -114,6 +139,10 @@ def markdown(title, host, rows, record): "Rejected is the number of rounds in which its server failed requests at a point " "that needs more KV than its pool holds.", ""] pinned = any("baseline-reference" in row["arms"] for row in rows) + control = next((row["control"]["server"] for row in rows if "control" in row), None) + if control is not None: + lines += [f"Servers are compared with {plain(control)}, the first named: each differs from it only " + "in its Skippy flags, so Change is the flags' effect on the candidate.", ""] if pinned: lines += ["The candidate moves the llama.cpp pin, so Baseline reference is llama.cpp at the " "baseline's pin, and llama.cpp change compares the two references: a change in both " diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index aa13d6bf..f928f804 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -744,6 +744,22 @@ def sample(arm, value): self.assertIn("round ranges overlap", markdown("t", "h", close, self.record)) self.assertNotIn("llama.cpp change", markdown("t", "h", rows, self.record)) + def test_a_server_comparison_measures_each_server_against_the_first_named(self): + servers = ["lanes4-pool32k-prefill2048", "lanes4-pool32k"] + shape = performance_plan.scenario(servers) + points = {server["id"]: server["points"][0]["id"] for server in shape["servers"]} + rows = summarize([{"model": "m", "server": server, "point": points[server], "arm": "candidate", + "metrics": {"output_tok_s": value}, "rejected": None} + for server, values in ((servers[0], (100, 102, 98)), (servers[1], (120, 118, 121))) + for value in values]) + performance_report.against_control(rows, shape, servers) + control, other = sorted(rows, key=lambda row: row["server"] != servers[0]) + self.assertEqual(performance_report.verdict(control), "Control") + self.assertAlmostEqual(other["candidate_vs_control"]["percent"], 20.0) + report = markdown("t", "h", rows, self.record) + self.assertIn("+20.00% · Improved", report) + self.assertIn("compared with lanes4-pool32k-prefill2048, the first named", report) + def test_a_moved_pin_says_whether_llama_cpp_moved_too(self): def sample(arm, value): return {"model": "m", "server": "s", "point": "p", "arm": arm, "metrics": {"output_tok_s": value}, From d836811e7b00198bb64cd1acfc52884efaf7e0ce Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Mon, 30 Nov 2026 20:46:02 +1100 Subject: [PATCH 30/50] Report progress while a long harness step runs A job reported progress only between steps, so a Skippy build or a conversation replay sat at one percent for twelve to fifteen minutes and looked stuck. A step expected to take two minutes or more now runs under a ticker that reports once a minute, climbing toward the percent the step reports when it ends. A failed ticked step still names itself on stderr before the job archives what it measured. --- ci/INFERENCE_PERFORMANCE.md | 4 +++- scripts/lib/performance_plan.py | 24 +++++++++++++++---- .../tests/inference_performance_contracts.py | 22 +++++++++++------ 3 files changed, 38 insertions(+), 12 deletions(-) diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index ccb7b49f..ebc094f3 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -119,7 +119,9 @@ expected time spent to `$JIANYANG_PROGRESS_PATH`, with what just finished. The expected times are rough: fifteen minutes for a Skippy build, five for `llama-server`, and half a minute per server start plus two seconds per request, or for a conversation point two minutes to load its dataset plus its duration or -four seconds a turn. +four seconds a turn. A step expected to take two minutes or more also reports +once a minute while it runs, climbing toward the percent it will report when it +ends, so a build or a replay never sits still for a quarter of an hour. A failed step names itself on stderr and the archive still runs. The scenario covers one request at a time, four lanes with short and long diff --git a/scripts/lib/performance_plan.py b/scripts/lib/performance_plan.py index c3e79659..60640c6f 100644 --- a/scripts/lib/performance_plan.py +++ b/scripts/lib/performance_plan.py @@ -35,6 +35,15 @@ NOTE = re.compile(r"[A-Za-z0-9 ._:+-]{1,59}") PROGRESS = ("progress() { printf '%s%% %s\\n' \"$1\" \"$2\" > \"$JIANYANG_PROGRESS_PATH\"; " "echo \"PROGRESS ${JIANYANG_NODE:-?} $(date +%T) $1% $2\"; }") +# A step of at least TICK_MINUTES reports a tick a minute between its start and end, so a watcher sees +# a 15-minute build or a 12-minute replay move. A failed step names itself and exits, since the ERR trap +# would only see the function's return. +TICK_MINUTES = 2 +TICKED = ("ticked() { local start=$1 end=$2 minutes=$3 note=$4 ticker status=0; shift 4; " + "( for i in $(seq 1 \"$minutes\"); do sleep 60; " + "progress $(( start + (end - start) * i / (minutes + 1) )) \"$i min toward $note\"; done ) & ticker=$!; " + "\"$@\" || status=$?; kill \"$ticker\" 2>/dev/null || true; wait \"$ticker\" 2>/dev/null || true; " + "if [ \"$status\" -ne 0 ]; then echo \"inference performance stopped at: $*\" >&2; exit \"$status\"; fi; }") def count(value, name, minimum=1): @@ -261,10 +270,11 @@ def job_steps(arm_list, keys, rounds, servers, trace, backend): def job_command(steps): """A shell script that runs `steps` from the harness checkout and reports progress after each: - the percent of the expected time spent, never falling, and 100 only once all have run. A - failure names the command that stopped it and still archives what was measured.""" + the percent of the expected time spent, never falling, and 100 only once all have run; a long + step ticks once a minute on its way. A failure names the command that stopped it and still + archives what was measured.""" total = sum(minutes for _, _, minutes in steps) - lines = ["set -euo pipefail", PROGRESS, + lines = ["set -euo pipefail", PROGRESS, TICKED, "trap 'echo \"inference performance stopped at: $BASH_COMMAND\" >&2' ERR", "trap 'status=$?; if [ \"$status\" -ne 0 ]; then just inference-performance-step finish " ">/dev/null 2>&1 || true; fi' EXIT", @@ -274,8 +284,14 @@ def job_command(steps): note = note[:59] if not NOTE.fullmatch(note): raise ValueError(f"progress note {note!r} needs letters, digits and . _ : + - only") + start = min(99, math.floor(spent / total * 100)) spent += minutes - lines += [shlex.join(["just", *args]), f'progress {min(99, math.floor(spent / total * 100))} "{note}"'] + end = min(99, math.floor(spent / total * 100)) + run = shlex.join(["just", *args]) + if minutes >= TICK_MINUTES and end > start: + # the note leaves room for "NN min toward " within the 59 characters a note may take + run = f"ticked {start} {end} {math.floor(minutes)} {shlex.quote(note[:45])} {run}" + lines += [run, f'progress {end} "{note}"'] lines.append('progress 100 "done"') return "\n".join(lines) + "\n" diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index f928f804..8144479e 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -309,8 +309,8 @@ def test_without_a_baseline_a_plan_compares_servers_that_differ_only_in_flags(se self.assertEqual(performance_plan.comparison(performance_plan.arms(self.candidate, self.baseline, None), None), "commits") spec = performance_plan.job_spec("d" * 40, alone, ["qwen35-4b"], 3, None, "any", servers=servers) - self.assertEqual([line for line in spec["runtime"]["command"].splitlines() if "build-arm" in line], - ["just inference-performance-build-arm candidate"]) + self.assertEqual([line[line.index("just "):] for line in spec["runtime"]["command"].splitlines() + if "build-arm" in line], ["just inference-performance-build-arm candidate"]) native_plan = run_path(str(Path(__file__).resolve().parents[1] / "inference-performance.py"))["native_plan"] plan = spec["runtime"]["env"]["SKIPPY_PERFORMANCE_PLAN"] with patch.dict(native_plan.__globals__, capture=lambda _: "d" * 40), \ @@ -353,16 +353,24 @@ def test_the_job_reports_progress_after_every_step_and_ends_at_100(self): self.assertNotIn("build", spec["runtime"]["workspace"]) lines = spec["runtime"]["command"].splitlines() self.assertEqual(lines[0], "set -euo pipefail") - self.assertEqual((lines[4], lines[-1]), ('progress 0 "starting"', 'progress 100 "done"')) - steps = [line for line in lines if line.startswith("just ")] + self.assertEqual((lines[5], lines[-1]), ('progress 0 "starting"', 'progress 100 "done"')) + steps = [line for line in lines if line.startswith(("just ", "ticked "))] reports = [line for line in lines if line.startswith("progress ")][1:-1] self.assertEqual(len(steps), len(reports)) percents = [int(report.split()[1]) for report in reports] self.assertEqual(percents, sorted(percents)) self.assertLess(percents[-1], 100) - self.assertEqual(steps[1:4], [f"just inference-performance-build-arm {arm}" - for arm in ("candidate", "baseline", "reference")]) - measured = [step.split()[5] for step in steps if " measure " in step] + self.assertEqual([step[step.index("just "):] for step in steps[1:4]], + [f"just inference-performance-build-arm {arm}" + for arm in ("candidate", "baseline", "reference")]) + # a long step ticks between the percent before it and the one it reports + for step, report in zip(steps, reports): + if step.startswith("ticked "): + start, end, minutes = map(int, step.split()[1:4]) + self.assertEqual((end, minutes >= performance_plan.TICK_MINUTES), (int(report.split()[1]), True)) + self.assertLess(start, end) + self.assertTrue(steps[1].startswith("ticked ")) + measured = [step[step.index("just "):].split()[5] for step in steps if " measure " in step] per_round = len(measured) // 3 # every arm leads one round self.assertEqual([measured[index * per_round] for index in range(3)], From 8e07216900ef8929fee10b112f784fae53791490 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Mon, 30 Nov 2026 20:46:02 +1100 Subject: [PATCH 31/50] Keep each run's logs and AIPerf exports with its evidence The controller fetched only performance.json and, when traced, the traces, so a run's server logs and AIPerf's per-request exports stayed in JY, and a failed run kept nothing at all. Collecting now also keeps every server's and build's log under LABEL-logs/ and AIPerf's archive as LABEL-aiperf.tar.gz, and a failed job keeps its logs too, so its failure can be read without going back to the job. --- ci/INFERENCE_PERFORMANCE.md | 7 +++++++ scripts/inference-performance.py | 20 +++++++++++++++++++ .../tests/inference_performance_contracts.py | 16 +++++++++++++++ 3 files changed, 43 insertions(+) diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index ebc094f3..75a2d0c8 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -209,6 +209,13 @@ them as `rejected`, with null metrics, and the summary table shows `rejected` fo that arm. The server must still be running afterwards, or the job fails. A Skippy arm is held to every point. +## Logs + +The controller also keeps each run's logs beside its evidence, for a job that +failed as well as one that succeeded: every server's and build's log under +`LABEL-logs/`, and AIPerf's per-request exports as `LABEL-aiperf.tar.gz`. They +are what a failed or surprising point is read from. + ## Traces With `trace` on, each job runs the candidate once more per model and server after diff --git a/scripts/inference-performance.py b/scripts/inference-performance.py index 2e919a8d..407300db 100644 --- a/scripts/inference-performance.py +++ b/scripts/inference-performance.py @@ -162,6 +162,20 @@ def wait(pilot, identifier, evidence, deadline): raise RuntimeError(f"{identifier} did not finish before the controller deadline") +def keep_logs(pilot, run_id, label, evidence): + """Each server's log, the builds' logs and AIPerf's per-request exports, beside the measurements: + what a surprising or failed point is read from, kept with the evidence rather than only in JY.""" + listed = pilot.api("GET", f"/v1/artifacts/{run_id}")["artifacts"] + names = {key.rsplit("/", 2)[2] for key in (artifact["key"] for artifact in listed)} + logs = evidence / f"{label}-logs" + for name in sorted(names): + if name.endswith(".log") and name != "job.log": + logs.mkdir(parents=True, exist_ok=True) + download(pilot, run_id, name, logs / name) + if "aiperf.tar.gz" in names: + download(pilot, run_id, "aiperf.tar.gz", evidence / f"{label}-aiperf.tar.gz") + + def download(pilot, run_id, name, path): """An artifact that is not JSON, streamed to `path`.""" # Artifacts are namespaced by kind: raw/, log/ and trace/ files are served @@ -197,6 +211,7 @@ def collect(pilot, job, plan, label, evidence): encoding="utf-8") if plan["trace"]: download(pilot, run_id, "traces.tar.gz", evidence / f"{label}-traces.tar.gz") + keep_logs(pilot, run_id, label, evidence) host = f'{result["host"].get("gpu") or result["host"].get("chip") or "unknown device"}' \ f' ({result["host"].get("node") or "unknown node"})' summary = summarize(result["samples"]) @@ -229,6 +244,11 @@ def dispatch(evidence): for job, spec in zip(finished, plan["jobs"]): if job["status"] != "succeeded": failures.append(f'{spec["label"]}: {job["status"]}') + # a failed run's logs are what explain it; losing them must not hide the failure itself + try: + keep_logs(pilot, resource_id((job.get("runs") or [{}])[-1].get("id")), spec["label"], evidence) + except (OSError, ValueError, KeyError) as error: + print(f'{spec["label"]}: logs not kept: {error}', file=sys.stderr) continue reports.append(collect(pilot, job, plan, spec["label"], evidence)) report = off_main(plan["pull_requests"], plan.get("branches")) + "\n".join(reports) diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index 8144479e..1129e09e 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -828,6 +828,22 @@ def sample(arm, value, rejected=None): "70.0 (68.0–72.0, n=2); rejected n=1") self.assertEqual(performance_report.cell(None, 0), "—") + def test_collecting_keeps_the_runs_logs_and_aiperf_exports_with_the_evidence(self): + keep_logs = run_path(str(Path(__file__).resolve().parents[1] / "inference-performance.py"))["keep_logs"] + names = (("log", "job.log"), ("log", "build-candidate.log"), ("log", "m-r1-candidate-s.log"), + ("raw", "aiperf.tar.gz"), ("raw", "performance.json")) + pilot, fetched = Mock(), [] + pilot.api.return_value = {"artifacts": [{"key": f"p/j/r/{kind}/{name}"} for kind, name in names]} + with TemporaryDirectory() as directory: + def download(_pilot, _run, name, path): + fetched.append((name, str(path.relative_to(directory)))) + with patch.dict(keep_logs.__globals__, download=download): + keep_logs(pilot, "run_1", "spark", Path(directory)) + pilot.api.assert_called_once_with("GET", "/v1/artifacts/run_1") + self.assertEqual(fetched, [("build-candidate.log", "spark-logs/build-candidate.log"), + ("m-r1-candidate-s.log", "spark-logs/m-r1-candidate-s.log"), + ("aiperf.tar.gz", "spark-aiperf.tar.gz")]) + def test_stored_rows_carry_their_arm_point_and_host_but_not_the_trace_pass(self): shape = performance_plan.scenario() server = shape["servers"][0] From 2e38496b6bc9d3e06d52d3c0326f00fb21771701 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Mon, 30 Nov 2026 22:06:50 +1100 Subject: [PATCH 32/50] Refuse a replay a model's context cannot hold before building AgentX's shortest conversation is 44,048 tokens, so a model trained on less, such as gemma3-1b or phi-4, loaded the dataset after a fifteen- minute build and then failed with nothing to replay. Each model's pin now carries its trained_context, read from its GGUF header, and admission refuses weights whose header disagrees. A plan is checked against it before anything runs: a conversation point whose dataset's shortest conversation does not fit the lane a model is served is refused, naming the server to leave out. --- ci/INFERENCE_PERFORMANCE.md | 7 +++ ci/inference-artifacts.json | 60 ++++++++++++------- scripts/inference-performance.py | 6 +- scripts/lib/inference_inputs.py | 4 ++ scripts/lib/performance_load.py | 7 ++- scripts/lib/performance_plan.py | 14 +++++ .../tests/inference_performance_contracts.py | 15 ++++- 7 files changed, 89 insertions(+), 24 deletions(-) diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index 75a2d0c8..beebd981 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -190,6 +190,13 @@ keeps only the AgentX traces that fit it, so a model's conversation numbers compare its arms with each other, not with another model's. A generated point longer than a model's trained context fails that model's step. +Each model's pin in `inference-artifacts.json` carries that `trained_context`, and +admission refuses weights whose header says otherwise. So a plan is checked before +anything is built: a conversation point whose dataset's shortest conversation +(44,048 tokens for AgentX, whose every trace carries a coding agent's system +prompt) does not fit the lane a model is served is refused, naming the server to +leave out. gemma3-1b (32,768) and phi-4 (16,384) cannot replay AgentX. + An arm that lacks a setting, such as `--kv-pool-tokens` on a commit from before the pool existed, runs without it. Each sample records what was applied and what the arm did not support. All arms are probed before model measurements begin. diff --git a/ci/inference-artifacts.json b/ci/inference-artifacts.json index 6710a993..b323eb1b 100644 --- a/ci/inference-artifacts.json +++ b/ci/inference-artifacts.json @@ -20,7 +20,8 @@ "tokenizer.json", "tokenizer_config.json", "vocab.json" - ] + ], + "trained_context": 262144 }, "qwen35-2b": { "repo": "unsloth/Qwen3.5-2B-GGUF", @@ -43,7 +44,8 @@ "tokenizer.json", "tokenizer_config.json", "vocab.json" - ] + ], + "trained_context": 262144 }, "qwen35-4b": { "repo": "unsloth/Qwen3.5-4B-GGUF", @@ -66,7 +68,8 @@ "tokenizer.json", "tokenizer_config.json", "vocab.json" - ] + ], + "trained_context": 262144 }, "qwen35-9b": { "repo": "unsloth/Qwen3.5-9B-GGUF", @@ -89,7 +92,8 @@ "tokenizer.json", "tokenizer_config.json", "vocab.json" - ] + ], + "trained_context": 262144 }, "qwen38-27b": { "repo": "unsloth/Qwen3.8-27B-GGUF", @@ -112,7 +116,8 @@ "tokenizer.json", "tokenizer_config.json", "vocab.json" - ] + ], + "trained_context": 262144 }, "qwen3-coder-30b-a3b": { "repo": "unsloth/Qwen3-Coder-30B-A3B-Instruct-GGUF", @@ -135,7 +140,8 @@ "tokenizer.json", "tokenizer_config.json", "vocab.json" - ] + ], + "trained_context": 262144 }, "qwen36-35b-a3b": { "repo": "unsloth/Qwen3.6-35B-A3B-GGUF", @@ -158,7 +164,8 @@ "tokenizer.json", "tokenizer_config.json", "vocab.json" - ] + ], + "trained_context": 262144 }, "qwen38-flash-next": { "repo": "unsloth/Qwen3.8-Flash-Next-GGUF", @@ -196,7 +203,8 @@ "tokenizer.json", "tokenizer_config.json", "vocab.json" - ] + ], + "trained_context": 262144 }, "perf-llama-3-2-1b-q4": { "repo": "bartowski/Llama-3.2-1B-Instruct-GGUF", @@ -218,7 +226,8 @@ "special_tokens_map.json", "tokenizer.json", "tokenizer_config.json" - ] + ], + "trained_context": 131072 }, "perf-gemma3-1b-q4": { "repo": "ggml-org/gemma-3-1b-it-GGUF", @@ -241,7 +250,8 @@ "tokenizer.json", "tokenizer.model", "tokenizer_config.json" - ] + ], + "trained_context": 32768 }, "perf-gpt-oss-20b-mxfp4": { "repo": "ggml-org/gpt-oss-20b-GGUF", @@ -263,7 +273,8 @@ "special_tokens_map.json", "tokenizer.json", "tokenizer_config.json" - ] + ], + "trained_context": 131072 }, "perf-deepseek2-coder-lite-q4": { "repo": "bartowski/DeepSeek-Coder-V2-Lite-Instruct-GGUF", @@ -283,7 +294,8 @@ "config.json", "tokenizer.json", "tokenizer_config.json" - ] + ], + "trained_context": 163840 }, "perf-phi4-q4": { "repo": "unsloth/phi-4-GGUF", @@ -306,7 +318,8 @@ "tokenizer.json", "tokenizer_config.json", "vocab.json" - ] + ], + "trained_context": 16384 }, "perf-mistral-small-24b-q4": { "repo": "unsloth/Mistral-Small-3.2-24B-Instruct-2506-GGUF", @@ -328,7 +341,8 @@ "special_tokens_map.json", "tokenizer.json", "tokenizer_config.json" - ] + ], + "trained_context": 131072 }, "perf-falcon-mamba-7b-q4": { "repo": "bartowski/falcon-mamba-7b-GGUF", @@ -349,7 +363,8 @@ "special_tokens_map.json", "tokenizer.json", "tokenizer_config.json" - ] + ], + "trained_context": 1048576 }, "perf-granite-4-h-350m-q4": { "repo": "ibm-granite/granite-4.0-h-350m-GGUF", @@ -373,7 +388,8 @@ "tokenizer.json", "tokenizer_config.json", "vocab.json" - ] + ], + "trained_context": 1048576 }, "perf-falcon-h1-1-5b-q4": { "repo": "tiiuae/Falcon-H1-1.5B-Instruct-GGUF", @@ -395,7 +411,8 @@ "special_tokens_map.json", "tokenizer.json", "tokenizer_config.json" - ] + ], + "trained_context": 131072 }, "perf-jamba2-3b-q4": { "repo": "bartowski/ai21labs_AI21-Jamba2-3B-GGUF", @@ -417,7 +434,8 @@ "special_tokens_map.json", "tokenizer.json", "tokenizer_config.json" - ] + ], + "trained_context": 262144 }, "perf-lfm2-350m-q4": { "repo": "LiquidAI/LFM2-350M-GGUF", @@ -439,7 +457,8 @@ "special_tokens_map.json", "tokenizer.json", "tokenizer_config.json" - ] + ], + "trained_context": 128000 }, "perf-nemotron35-lightning-30b-a3b-q4": { "repo": "unsloth/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-GGUF", @@ -461,6 +480,7 @@ "special_tokens_map.json", "tokenizer.json", "tokenizer_config.json" - ] + ], + "trained_context": 1048576 } } diff --git a/scripts/inference-performance.py b/scripts/inference-performance.py index 407300db..8cac5d3d 100644 --- a/scripts/inference-performance.py +++ b/scripts/inference-performance.py @@ -408,7 +408,11 @@ def prepare_model(key): if available < sum(file["size"] for file in inputs["files"]) + entry["reserve_gib"] * 1024**3: raise ValueError(f"{key}: insufficient {plan['backend']} free memory for weights and reserve") model = admit_model(key, inputs) - inputs = {**inputs, "tokenizer_path": str(tokenizer(inputs)), "trained_context": trained_context(model)} + # the plan was checked against the pin, so the pin must say what the verified weights say + if trained_context(model) != inputs["trained_context"]: + raise ValueError(f'{key}: its GGUF was trained for {trained_context(model)} tokens, ' + f'its pin says {inputs["trained_context"]}') + inputs = {**inputs, "tokenizer_path": str(tokenizer(inputs))} record["models"][key] = {"repo": inputs["repo"], "revision": inputs["revision"], "files": inputs["files"], "trained_context": inputs["trained_context"]} MODELS.mkdir(parents=True, exist_ok=True) diff --git a/scripts/lib/inference_inputs.py b/scripts/lib/inference_inputs.py index 401b9f30..dc00b068 100644 --- a/scripts/lib/inference_inputs.py +++ b/scripts/lib/inference_inputs.py @@ -92,6 +92,10 @@ def fixture(key): value = fixtures[key] if not re.fullmatch(r"[0-9a-f]{40}", value["revision"]) or not value["files"]: raise ValueError("unpinned fixture") + # what the model was trained for, so a plan can refuse a point it cannot serve before any build; + # admission checks it against the GGUF + if type(value.get("trained_context")) is not int or value["trained_context"] < 1: + raise ValueError(f"{key} needs its trained_context pinned") names = set() for file in value["files"]: name = safe_relative(file["path"]).name diff --git a/scripts/lib/performance_load.py b/scripts/lib/performance_load.py index 47049d76..d7906e45 100644 --- a/scripts/lib/performance_load.py +++ b/scripts/lib/performance_load.py @@ -18,9 +18,12 @@ # instead of generated prompts. `bound` is what ends it: AgentX paces its turns from the traces' # own gaps, so it runs for a time; ShareGPT sends each turn once the last is answered, so it runs # for a number of requests. +# `smallest_tokens` is the corpus's shortest conversation at its pinned revision, input and output +# together: AIPerf replays only those that fit the context, so a model serving less has none to +# replay. AgentX's shortest carries a coding agent's system prompt; ShareGPT's turns all fit. DATASETS = { - "agentx": {"corpus": "ci/inference-corpus.json", "bound": "duration_s"}, - "sharegpt": {"corpus": "ci/inference-chat-corpus.json", "bound": "requests"}, + "agentx": {"corpus": "ci/inference-corpus.json", "bound": "duration_s", "smallest_tokens": 44048}, + "sharegpt": {"corpus": "ci/inference-chat-corpus.json", "bound": "requests", "smallest_tokens": None}, } # AgentX's scenario holds a shorter run to be no submission; a comparison is not one. AGENTX_MINIMUM_S = 900 diff --git a/scripts/lib/performance_plan.py b/scripts/lib/performance_plan.py index 60640c6f..ee3ce700 100644 --- a/scripts/lib/performance_plan.py +++ b/scripts/lib/performance_plan.py @@ -86,6 +86,18 @@ def model_context(shape, server, trained): return min(lane_context(shape, server), trained) +def conversations_fit(key, trained, shape): + """Every conversation point in `shape` must hold its dataset's shortest conversation in the + context `key` serves a lane, or AIPerf would load the dataset and find nothing to replay.""" + for server in shape["servers"]: + context = model_context(shape, server, trained) + for point in server["points"]: + smallest = (dataset(point) or {}).get("smallest_tokens") + if smallest is not None and context < smallest: + raise ValueError(f'{key} serves {context} tokens a lane, fewer than the shortest ' + f'{point["dataset"]} conversation ({smallest}): leave {server["id"]} out') + + def request_tokens(point): """What one request of generated prompts holds at its longest: prefix, prompt and output.""" return point["depth"] + point["input_tokens"] + point["output_tokens"] @@ -328,6 +340,8 @@ def job_spec(harness, arm_list, keys, rounds, node, label, *, trace=False, backe request_rate(point, backend) if entry["pin_required"] and node is None: raise ValueError(f"a {backend} plan must name exactly one node: its GPUs differ between hosts") + for key in keys: + conversations_fit(key, fixture(key)["trained_context"], shape) largest = max(sum(file["size"] for file in fixture(key)["files"]) for key in keys) if entry["selector"]: selector = {key: value for key, value in entry["selector"].items() if key != "memory"} diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index 1129e09e..9ebb467d 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -148,6 +148,18 @@ def test_a_model_is_served_no_more_context_than_it_was_trained_on(self): measure(built, "", "/m.gguf", {**inputs, "trained_context": 8000}, "m", 0, long, shape, Path(directory)) self.assertEqual(start.call_count, 1) + + def test_a_plan_refuses_a_replay_whose_shortest_conversation_the_model_cannot_hold(self): + arm_list = performance_plan.arms("a" * 40, "b" * 40, None) + agentx, sharegpt = ["lanes1-agentx-ctx64k"], ["lanes4-sharegpt"] + for key in performance_plan.read_json(performance_plan.ROOT / "ci/inference-artifacts.json"): + self.assertGreater(performance_plan.fixture(key)["trained_context"], 0) + # gemma3-1b was trained on 32,768 tokens, AgentX's shortest conversation is 44,048 + with self.assertRaisesRegex(ValueError, "fewer than the shortest agentx conversation"): + performance_plan.job_spec("d" * 40, arm_list, ["perf-gemma3-1b-q4"], 1, None, "x", servers=agentx) + performance_plan.job_spec("d" * 40, arm_list, ["perf-gemma3-1b-q4"], 1, None, "x", servers=sharegpt) + performance_plan.job_spec("d" * 40, arm_list, ["perf-falcon-h1-1-5b-q4"], 1, None, "x", servers=agentx) + def test_the_shipped_conversation_servers_run_only_when_named(self): shipped = performance_plan.read_json(performance_plan.SCENARIO)["servers"] replaying = [server["id"] for server in shipped if any("dataset" in point for point in server["points"])] @@ -221,7 +233,8 @@ def test_a_conversation_point_checks_its_pin_before_and_after_even_when_aiperf_f def test_a_replaying_plan_is_bounded_by_its_time_and_estimates_it(self): arm_list = performance_plan.arms("a" * 40, "b" * 40, None) agentx = CONVERSATIONS["points"][0] - traces = {**CONVERSATIONS, "id": "lanes1-agentx", "lanes": 1, "points": [agentx]} + # a lane long enough for AgentX's shortest conversation, as the shipped AgentX server's + traces = {**CONVERSATIONS, "id": "lanes1-agentx", "lanes": 1, "context_per_lane": 65536, "points": [agentx]} with patch.object(performance_plan, "read_json", return_value=with_server(traces)): harness = performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 3, None, "any", servers=[traces["id"]])["harness"] From 2e7b48240098928a0e4e470998503618df0704ec Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Tue, 1 Dec 2026 13:40:03 +1100 Subject: [PATCH 33/50] Record what each server allocates beyond its weights Admission checks a model's weights plus a fixed reserve, but what a server really needs beyond its weights depends on the model and the server: a 65,536-cell KV cache for falcon-h1 is 1.5 GiB, a hybrid adds its recurrent state, and the compute buffer grows with the batch. Each server's startup log states those figures exactly, so every sample now carries them: each KV cache with its cells, the recurrent state, and the largest compute buffer on the device. A later check can size a host from measurements rather than estimates. --- ci/INFERENCE_PERFORMANCE.md | 6 ++++++ scripts/inference-performance.py | 7 +++++-- scripts/lib/inference_checks.py | 20 +++++++++++++++++++ .../tests/inference_performance_contracts.py | 19 ++++++++++++++++++ 4 files changed, 50 insertions(+), 2 deletions(-) diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index beebd981..9cc66343 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -223,6 +223,12 @@ failed as well as one that succeeded: every server's and build's log under `LABEL-logs/`, and AIPerf's per-request exports as `LABEL-aiperf.tar.gz`. They are what a failed or surprising point is read from. +Each measured server's startup also reports what it allocated beyond its +weights, and every sample carries it as `memory`: each KV cache with its cells (a +sliding-window model has two), the recurrent state, and the largest compute +buffer on the device. Those are the figures a host's memory reserve is sized +from, measured rather than estimated. + ## Traces With `trace` on, each job runs the candidate once more per model and server after diff --git a/scripts/inference-performance.py b/scripts/inference-performance.py index 8cac5d3d..4cb12745 100644 --- a/scripts/inference-performance.py +++ b/scripts/inference-performance.py @@ -21,7 +21,7 @@ from lib.ci_process import cancel_on_signal, capture, command, start, stop from lib.ci_smoke import curl from lib.gguf_header import trained_context -from lib.inference_checks import ENDPOINT, offload +from lib.inference_checks import ENDPOINT, memory_figures, offload from lib.inference_inputs import admit as admit_model from lib.inference_inputs import fixture from lib.jy_qualification import ORIGIN, Pilot @@ -345,6 +345,8 @@ def measure(built, help_text, model, inputs, key, index, server, shape, output, try: ready(process, 900) offload(log, prefixes) + # what this model needs beyond its weights on this server, so a later plan can size its host + memory = memory_figures(log, prefixes) for point in server["points"]: metrics, rejected = run_point(ENDPOINT, point, coordinate, inputs["tokenizer_path"], shape["warmup_requests"], WORK / "aiperf" / name / point["id"], @@ -356,7 +358,8 @@ def measure(built, help_text, model, inputs, key, index, server, shape, output, samples.append({"model": key, "round": None if index is None else index + 1, "arm": built["label"], "server": server["id"], "point": point["id"], "applied": applied, - "unsupported": missing, "metrics": metrics, "rejected": rejected}) + "unsupported": missing, "metrics": metrics, "rejected": rejected, + "memory": memory}) finally: stop(process) return samples diff --git a/scripts/lib/inference_checks.py b/scripts/lib/inference_checks.py index 7adda1c8..07f4aab9 100644 --- a/scripts/lib/inference_checks.py +++ b/scripts/lib/inference_checks.py @@ -47,6 +47,26 @@ def offload(log, prefixes=("MTL",)): raise ValueError("server log has no positive GPU-layer offload evidence") +KV_CACHE = re.compile(r"llama_kv_cache: size = +([0-9.]+) MiB \( *([0-9]+) cells") +RECURRENT = re.compile(r"llama_memory_recurrent: size = +([0-9.]+) MiB \( *([0-9]+) cells") + + +def memory_figures(log, prefixes=("MTL",)): + """What a server allocated beyond its weights, as llama.cpp reported it at startup: each KV + cache (a sliding-window model has two), the recurrent state, and the largest compute buffer on + the device, not the host. A model without a cache or state reports no line for it.""" + compute = re.compile(rf"(?:{'|'.join(prefixes)})[0-9]+ compute buffer size = +([0-9.]+) MiB") + caches, recurrent, buffers = [], [], [] + with log.open(encoding="utf-8") as stream: + for line in stream: + for pattern, found in ((KV_CACHE, caches), (RECURRENT, recurrent)): + if match := pattern.search(line): + found.append({"bytes": round(float(match[1]) * 1024**2), "cells": int(match[2])}) + if match := compute.search(line): + buffers.append(round(float(match[1]) * 1024**2)) + return {"kv_caches": caches, "recurrent": recurrent, "compute_bytes": max(buffers, default=0)} + + def request(model, prompt, maximum, timeout, stream=False): payload = {"model": model, "messages": [{"role": "user", "content": prompt}], "temperature": 0, "seed": 42, "max_tokens": maximum, diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index 9ebb467d..a1881d5a 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -10,6 +10,7 @@ from lib import performance_arms, performance_backends, performance_plan from lib.gguf_header import trained_context +from lib.inference_checks import memory_figures from lib.performance_arms import REQUIRED, capabilities, may_reject, server_args from lib.performance_load import (DATASETS, conversation_args, measurements, profile_args, rejection, request_rate, run_point) @@ -494,6 +495,24 @@ def test_an_older_skippy_runs_without_settings_it_lacks_and_says_so(self): self.assertEqual(applied["generation_concurrency"], 4) self.assertEqual(missing, ["--speculative-strategy", "--kv-pool-tokens", "--debug"]) + def test_a_servers_log_gives_what_it_allocated_beyond_its_weights(self): + lines = ["llama_kv_cache: size = 1536.00 MiB ( 65536 cells, 24 layers, 2/1 seqs), K (f16): 768.00 MiB", + "llama_kv_cache: size = 256.00 MiB ( 4096 cells, 20 layers, 2/1 seqs), K (f16): 128.00 MiB", + "llama_memory_recurrent: size = 437.91 MiB ( 6 cells, 24 layers, 2 seqs 0 rs_seq)", + "sched_reserve: CUDA0 compute buffer size = 208.52 MiB", + "sched_reserve: CUDA_Host compute buffer size = 80.52 MiB", + "sched_reserve: CUDA0 compute buffer size = 190.00 MiB"] + with TemporaryDirectory() as directory: + log = Path(directory) / "server.log" + log.write_text("".join(json.dumps({"data": {"message": line + "\n"}, "type": "native_log"}) + "\n" + for line in lines), encoding="utf-8") + figures = memory_figures(log, ("CUDA",)) + mib = 1024 ** 2 + self.assertEqual(figures, {"kv_caches": [{"bytes": 1536 * mib, "cells": 65536}, + {"bytes": 256 * mib, "cells": 4096}], + "recurrent": [{"bytes": round(437.91 * mib), "cells": 6}], + "compute_bytes": round(208.52 * mib)}) + def test_measured_servers_run_at_debug_verbosity_for_offload_evidence(self): help_text = (" ".join(REQUIRED) + " --debug --generation-concurrency " " --speculative-strategy --kv-pool-tokens \n") From 159fcae4ff608c305281c91923b78990e9bf6d04 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Tue, 1 Dec 2026 14:11:51 +1100 Subject: [PATCH 34/50] Keep a model's trained context out of its benchmark recipe A recipe identity hashes the model's whole manifest entry. Pinning `trained_context` there, so a plan can refuse a replay the model cannot hold, therefore changed the recipe of every configuration: the audited history in `ci/inference-comparability.json` stopped matching, the contract test failed, and every series would have started again. The trained context follows from the pinned files and is checked against them at admission, so a benchmark measures nothing different for it. The recipe now hashes the manifest entry without it, which gives the audited identities again. --- scripts/lib/inference_nightly_metrics.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/scripts/lib/inference_nightly_metrics.py b/scripts/lib/inference_nightly_metrics.py index 875c0a96..f48d227c 100644 --- a/scripts/lib/inference_nightly_metrics.py +++ b/scripts/lib/inference_nightly_metrics.py @@ -21,6 +21,9 @@ SMOKE_METRICS = ("prefill_tok_s", "decode_tok_s") AGENTX_METRICS = ("output_tok_s", "ttft_p95_ms", "itl_p95_ms", "requests", "request_error_pct") METRIC_NAMES = {"pr": SMOKE_METRICS, "nightly": AGENTX_METRICS, "release": AGENTX_METRICS} +# What the manifest says about a model beside its pinned files. A plan reads these and admission checks them +# against the files, so a benchmark measures nothing different: pinning one must not start every series again. +MODEL_FACTS = ("trained_context",) def metric_value(value, *, positive=False): @@ -93,10 +96,11 @@ def benchmark_definition(profile, mode, backend="cuda"): def contract(profile, row, key): functions, files = benchmark_definition(profile, row["mode"], row.get("backend", "cuda")) + model = {field: value for field, value in fixture(key).items() if field not in MODEL_FACTS} inputs = { "recipe_version": 2, "profile": profile, "mode": row["mode"], "device": METAL_DEVICE if row.get("backend") == "metal" else "NVIDIA GB10", - "admission": "native-stage-plan-v2", "model": fixture(key), + "admission": "native-stage-plan-v2", "model": model, "harness": {name: digest(Path(name)) for name in files}, "benchmark_functions": {path: benchmark_functions(path, names) for path, names in functions.items()}, From 4d0f0dc6e25ec176fb980cd848b958d98f8f301f Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Tue, 1 Dec 2026 14:11:52 +1100 Subject: [PATCH 35/50] Let the performance workflow choose its backend and servers `admit` has read BACKEND and SERVERS since the backend table and named servers landed, but the workflow passed neither, so a dispatch or a caller could only run the default servers on Metal. It now takes `backend`, which a contract test holds to the table's entries, and `servers`, and hands both to `admit`. A caller also passes `label`, which names that call's evidence artifact. Several calls in one run would otherwise upload under one name, and the second upload would be refused. --- .github/workflows/inference-performance.yml | 27 ++++++++++++++++--- ci/INFERENCE_PERFORMANCE.md | 10 ++++--- ci/README.md | 2 +- .../tests/inference_performance_contracts.py | 9 +++++++ 4 files changed, 40 insertions(+), 8 deletions(-) diff --git a/.github/workflows/inference-performance.yml b/.github/workflows/inference-performance.yml index 5ed796e3..89a7c3c9 100644 --- a/.github/workflows/inference-performance.yml +++ b/.github/workflows/inference-performance.yml @@ -14,12 +14,21 @@ on: description: Add llama.cpp's own server at the candidate's llama_cpp/upstream.txt pin. type: boolean default: true + backend: + description: The backend every job runs on, from the table in scripts/lib/performance_backends.py. + type: choice + options: [metal, cuda, cuda-x86, rocm] + default: metal models: description: Comma-separated ci/inference-artifacts.json model ids. type: string default: qwen35-4b nodes: - description: Comma-separated Metal nodes, one job each. Empty runs one job on any Metal Mac that fits. + description: Comma-separated nodes of that backend, one job each. Empty runs one job on any host that fits, where the backend allows it. + type: string + default: '' + servers: + description: Comma-separated ci/inference-performance.json server ids. Empty runs the scenario's default servers. type: string default: '' rounds: @@ -41,18 +50,28 @@ on: reference: type: boolean default: true + backend: + type: string + default: metal models: type: string default: qwen35-4b nodes: type: string default: '' + servers: + type: string + default: '' rounds: type: number default: 3 trace: type: boolean default: false + label: + description: Names this call's evidence artifact, so several calls in one run keep theirs apart. + type: string + default: '' secrets: JIANYANG_INFERENCE_SSH_KEY: required: true @@ -82,12 +101,14 @@ jobs: CANDIDATE: ${{ inputs.candidate }} BASELINE: ${{ inputs.baseline }} REFERENCE: ${{ inputs.reference }} + BACKEND: ${{ inputs.backend }} MODELS: ${{ inputs.models }} NODES: ${{ inputs.nodes }} + SERVERS: ${{ inputs.servers }} ROUNDS: ${{ inputs.rounds }} TRACE: ${{ inputs.trace }} run: just inference-performance-admit "$EVIDENCE" - - name: Measure every arm on each Metal host + - name: Measure every arm on each host env: JIANYANG_INFERENCE_SSH_KEY: ${{ secrets.JIANYANG_INFERENCE_SSH_KEY }} run: just inference-performance-dispatch "$EVIDENCE" @@ -102,7 +123,7 @@ jobs: - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f if: always() with: - name: inference-performance-${{ github.run_id }}-${{ github.run_attempt }} + name: inference-performance-${{ inputs.label && format('{0}-', inputs.label) || '' }}${{ github.run_id }}-${{ github.run_attempt }} path: ${{ env.EVIDENCE }} if-no-files-found: error retention-days: 30 diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index 9cc66343..09398df5 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -1,7 +1,7 @@ # Inference qualification (performance) `inference-performance.yml` compares two Skippy commits, and optionally -llama.cpp's own server, on the same Metal machine. It is separate from +llama.cpp's own server, on the same machine. It is separate from qualification: qualification proves one commit works; this measures whether one commit is faster than another, so it needs every arm on one host, repeated rounds, and load that exercises batching. @@ -21,8 +21,10 @@ gh workflow run inference-performance.yml -f candidate=main \ | `candidate` | ref or SHA on main to measure, `pr:N` for the head of open pull request N, or `branch:NAME` for a branch's head; default `main` | | `baseline` | ref, SHA, `pr:N` or `branch:NAME` to compare against; passing the candidate again gives an A/A noise run | | `reference` | add llama.cpp's `llama-server` at the candidate's `llama_cpp/upstream.txt` pin; default on | +| `backend` | the backend every job runs on, one of the table's below; default `metal` | | `models` | `ci/inference-ladder.json` ids; shards are the hash-pinned files in `ci/inference-artifacts.json` | -| `nodes` | Metal nodes, one job each; empty runs one job on any Metal Mac with room for the largest model plus 16 GiB | +| `nodes` | nodes of that backend, one job each; empty runs one job on any Metal Mac or Spark with room for the largest model plus 16 GiB, and is refused for a backend that must be pinned | +| `servers` | `ci/inference-performance.json` server ids; empty runs the scenario's default servers | | `rounds` | rounds per arm, at most 9; default 3 | | `trace` | after the rounds, one diagnostic pass of the candidate with debug telemetry; default off | @@ -43,7 +45,8 @@ The table holds `metal` (any Apple M-series Mac whose Metal device is its own GP 121) and `cuda-x86` (a discrete NVIDIA GPU on Linux x86_64). The Spark's reference arm builds with `-DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=121`, configuring with the same toolkit environment `scripts/lib/cuda-toolkit.sh` resolves for Skippy's build. The -GitHub workflow still dispatches Metal only. +GitHub workflow passes its `backend` input to `admit` as `BACKEND`, and its +`servers` input as `SERVERS`. `cuda-x86` differs from the Spark in four ways, all in its table entry: @@ -293,7 +296,6 @@ group by all order by committed_at, model, point, arm; ## Limits -- Metal only for now; Sparks follow the same shape with a CUDA build. - Results live in artifacts, not yet in `jy result`. - AIPerf's prefix flags (`--prefix-prompt-length`, `--prefix-prompt-pool-size`) and `ignore_eos` handling are taken from its documentation; the first run diff --git a/ci/README.md b/ci/README.md index 56a21b8c..10cf973f 100644 --- a/ci/README.md +++ b/ci/README.md @@ -169,7 +169,7 @@ the final qualification status to pass. Manual PR and release profiles retain their own qualification contracts. `inference-performance.yml` is manual/reusable and compares protected-main commits or admitted same-repository PR heads -on one Metal host at a time; it reports into the run summary and gates nothing +on one host of a chosen backend at a time; it reports into the run summary and gates nothing (see [`INFERENCE_PERFORMANCE.md`](INFERENCE_PERFORMANCE.md)). Scheduled, manual and reusable full/candidate validation bypass path selection. diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index a1881d5a..96602343 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -1,6 +1,7 @@ """Offline checks for the performance comparison's plan, servers, parsing and report.""" import json +import re import struct import unittest from pathlib import Path @@ -660,6 +661,14 @@ def test_rocm_admission_takes_the_lesser_of_memory_and_free_vram_plus_gtt(self): path.return_value.read_text.return_value = "MemAvailable: 209715200 kB\n" # 200 GiB self.assertEqual(performance_backends.rocm_free(host), 140 * gib) + def test_the_workflow_offers_every_backend_in_the_table_and_passes_it_to_admit(self): + workflow = (Path(__file__).resolve().parents[2] + / ".github/workflows/inference-performance.yml").read_text(encoding="utf-8") + offered = re.search(r"\n backend:\n(?: .*\n)*? options: \[([^\]]+)\]", workflow)[1] + self.assertEqual(sorted(name.strip() for name in offered.split(",")), sorted(performance_backends.BACKENDS)) + for line in ("BACKEND: ${{ inputs.backend }}", "SERVERS: ${{ inputs.servers }}"): + self.assertIn(line, workflow) + class RejectionTests(unittest.TestCase): point = {"id": "c4-depth4096-pool16k", "concurrency": 4, "depth": 4096, "input_tokens": 512, From e4f1ff175ef9e57cb740f37f6984cc1500192a79 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Tue, 1 Dec 2026 14:11:52 +1100 Subject: [PATCH 36/50] Add a nightly comparison of main with the last nightly's commit A comparison ran only when someone dispatched one, so a regression on main was found when someone next thought to look. A scheduled workflow now measures main every night against the commit its last successful run measured, with llama.cpp's server at each commit's pin, by calling the performance workflow once for each lane of ci/inference-performance-nightly.json. A lane is one model on one pinned node, and a node is in one lane: two jobs on a node would queue behind each other inside one controller's deadline, and a job of several models is recorded without its place in the results' history. Every lane measures the run's own head, so the lanes and the next night's baseline agree on the commit. The first night, and a dispatch with `rebaseline`, measure main against itself, which gives the spread of two equal builds. A night on an unmoved main measures nothing and passes. A failed night leaves the baseline at the last commit that passed. --- .agents/skills/manage-ci/SKILL.md | 8 + .../inference-performance-nightly.test.cjs | 36 +++++ .../inference-performance-nightly.yml | 87 +++++++++++ ci/INFERENCE_PERFORMANCE.md | 22 +++ ci/README.md | 4 +- ci/automation.just | 8 + ci/inference-performance-nightly.json | 9 ++ scripts/inference-performance-nightly.py | 70 +++++++++ scripts/lib/performance_nightly.py | 93 ++++++++++++ .../tests/inference_performance_nightly.py | 137 ++++++++++++++++++ 10 files changed, 473 insertions(+), 1 deletion(-) create mode 100644 .github/scripts/inference-performance-nightly.test.cjs create mode 100644 .github/workflows/inference-performance-nightly.yml create mode 100644 ci/inference-performance-nightly.json create mode 100644 scripts/inference-performance-nightly.py create mode 100644 scripts/lib/performance_nightly.py create mode 100644 scripts/tests/inference_performance_nightly.py diff --git a/.agents/skills/manage-ci/SKILL.md b/.agents/skills/manage-ci/SKILL.md index 61bf3fd4..9937bd47 100644 --- a/.agents/skills/manage-ci/SKILL.md +++ b/.agents/skills/manage-ci/SKILL.md @@ -140,6 +140,14 @@ contract; no downstream product's workflow topology applies here. histories. Recipe changes start new series; audited historical equivalence is explicit and configuration/workload-bound. Never fill missing data or describe an unmeasured workload as a performance regression. +- `.github/workflows/inference-performance-nightly.yml` runs nightly and on + dispatch from protected main. It calls `inference-performance.yml` once per + lane of `ci/inference-performance-nightly.json`: one model on one pinned + node, each node in one lane. Every lane measures the run's own head against + the head of the last successful nightly, with llama.cpp's server at each + commit's pin. The first night and a `rebaseline` dispatch measure main + against itself; a night on an unmoved main measures nothing and passes. A + failed night leaves the baseline at the last commit that passed. - The protected inference results-comment job alone receives pull-requests write permission for PR comments, plus read-only contents/actions. It receives no native dispatch credential and never executes candidate code. diff --git a/.github/scripts/inference-performance-nightly.test.cjs b/.github/scripts/inference-performance-nightly.test.cjs new file mode 100644 index 00000000..f08c21c0 --- /dev/null +++ b/.github/scripts/inference-performance-nightly.test.cjs @@ -0,0 +1,36 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { readFileSync } = require('node:fs'); +const { join } = require('node:path'); + +const workflow = readFileSync(join(__dirname, '../workflows/inference-performance-nightly.yml'), 'utf8'); +const jobs = workflow.split('\njobs:\n')[1]; +const job = name => jobs.split(new RegExp(`(?:^|\\n) ${name}:\\n`))[1].split(/\n [a-z_]+:\n/)[0]; + +test('the nightly runs on a schedule and only from protected main of this repository', () => { + assert.match(workflow, /\n schedule:\n(?: #.*\n)* - cron: '\d+ \d+ \* \* \*'\n/); + assert.ok(job('plan').includes("if: github.repository == 'Mesh-LLM/skippy' && github.ref == 'refs/heads/main'")); + assert.ok(workflow.includes('cancel-in-progress: false')); +}); + +test('every lane measures the same two commits against llama.cpp and keeps its own evidence', () => { + const measure = job('measure'); + for (const line of [ + 'needs: plan', + 'matrix: ${{ fromJSON(needs.plan.outputs.matrix) }}', + 'uses: ./.github/workflows/inference-performance.yml', + 'candidate: ${{ needs.plan.outputs.candidate }}', + 'baseline: ${{ needs.plan.outputs.baseline }}', + 'reference: true', + 'backend: ${{ matrix.backend }}', + 'nodes: ${{ matrix.node }}', + 'label: ${{ matrix.id }}', + ]) assert.ok(measure.includes(line), line); +}); + +test('the verdict runs after a failed lane and reads every job it depends on', () => { + const verdict = job('verdict'); + assert.ok(verdict.includes("if: always() && needs.plan.result != 'skipped'")); + const needs = verdict.match(/needs: \[([a-z_, ]+)\]/)[1].split(', '); + for (const name of needs) assert.ok(verdict.includes(`needs.${name}.result`), name); +}); diff --git a/.github/workflows/inference-performance-nightly.yml b/.github/workflows/inference-performance-nightly.yml new file mode 100644 index 00000000..7f7b5e2c --- /dev/null +++ b/.github/workflows/inference-performance-nightly.yml @@ -0,0 +1,87 @@ +name: Inference performance (nightly) +on: + schedule: + # 04:37 in Sydney during daylight saving, after the qualification nightly has had the lab. + - cron: '37 17 * * *' + workflow_dispatch: + inputs: + rebaseline: + description: Measure main against itself, an A/A noise run, so the next nightly compares with this commit. + type: boolean + default: false +permissions: + contents: read +concurrency: + # A night holds lab machines for hours; a second run waits for it and never cancels it. + group: inference-performance-nightly + cancel-in-progress: false +jobs: + plan: + # A schedule only fires on the default branch; a dispatch from any other ref stops here. + if: github.repository == 'Mesh-LLM/skippy' && github.ref == 'refs/heads/main' + runs-on: ${{ vars.SKIPPY_DEPOT_RUNNERS_ENABLED == 'true' && 'depot-ubuntu-24.04-4' || 'ubuntu-24.04' }} + timeout-minutes: 10 + permissions: + contents: read + actions: read + outputs: + candidate: ${{ steps.plan.outputs.candidate }} + baseline: ${{ steps.plan.outputs.baseline }} + mode: ${{ steps.plan.outputs.mode }} + matrix: ${{ steps.plan.outputs.matrix }} + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 + with: + ref: ${{ github.sha }} + persist-credentials: false + - uses: ./.github/actions/setup + with: + cache: 'false' + - id: plan + name: Choose tonight's commits and lanes + env: + GH_TOKEN: ${{ github.token }} + REBASELINE: ${{ inputs.rebaseline }} + run: just inference-performance-nightly-plan + measure: + name: measure (${{ matrix.id }}) + needs: plan + if: needs.plan.outputs.mode != 'unchanged' + strategy: + fail-fast: false + matrix: ${{ fromJSON(needs.plan.outputs.matrix) }} + # Every lane measures the same two commits, so the lanes differ only in machine and model. + uses: ./.github/workflows/inference-performance.yml + with: + candidate: ${{ needs.plan.outputs.candidate }} + baseline: ${{ needs.plan.outputs.baseline }} + reference: true + backend: ${{ matrix.backend }} + models: ${{ matrix.model }} + nodes: ${{ matrix.node }} + servers: ${{ matrix.servers }} + rounds: ${{ matrix.rounds }} + trace: ${{ matrix.trace }} + label: ${{ matrix.id }} + secrets: + JIANYANG_INFERENCE_SSH_KEY: ${{ secrets.JIANYANG_INFERENCE_SSH_KEY }} + verdict: + name: Nightly performance verdict + needs: [plan, measure] + if: always() && needs.plan.result != 'skipped' + runs-on: ${{ vars.SKIPPY_DEPOT_RUNNERS_ENABLED == 'true' && 'depot-ubuntu-24.04-4' || 'ubuntu-24.04' }} + timeout-minutes: 5 + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 + with: + ref: ${{ github.sha }} + persist-credentials: false + - uses: ./.github/actions/setup + with: + cache: 'false' + - name: Settle the night's result + env: + PLAN: ${{ needs.plan.result }} + MODE: ${{ needs.plan.outputs.mode }} + MEASURE: ${{ needs.measure.result }} + run: just inference-performance-nightly-verdict diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index 09398df5..b490c38c 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -28,6 +28,28 @@ gh workflow run inference-performance.yml -f candidate=main \ | `rounds` | rounds per arm, at most 9; default 3 | | `trace` | after the rounds, one diagnostic pass of the candidate with debug telemetry; default off | +## Nightly + +`inference-performance-nightly.yml` runs this comparison every night from main, and on +dispatch. It measures the commit main is at when the run starts against the commit the last +successful nightly measured, with `llama-server` at each one's pin, by calling +`inference-performance.yml` once for each lane in `ci/inference-performance-nightly.json`. + +A lane is one model on one pinned node, and a node is in one lane: two jobs on a node would +queue behind each other inside one controller's deadline, and a job of several models is +recorded without its place in the results' history. A lane can name its `servers` and add a +`trace` pass; `rounds` is shared by all of them. + +| night | baseline | measured | +|---|---|---| +| main has moved | the last successful nightly's commit | every lane | +| the first night, or a dispatch with `rebaseline` | tonight's commit, an A/A run | every lane | +| main has not moved | none | nothing, and the night passes | + +A night that fails leaves the baseline where it was, so the next night compares with the last +commit that passed. A dispatch with `rebaseline` measures main against itself, which gives the +spread of two equal builds, and once it passes that commit is the next night's baseline. + ## Backends `admit` reads `BACKEND` (default `metal`) and refuses any value that has no entry in the diff --git a/ci/README.md b/ci/README.md index 10cf973f..5773eaa1 100644 --- a/ci/README.md +++ b/ci/README.md @@ -170,7 +170,9 @@ their own qualification contracts. `inference-performance.yml` is manual/reusable and compares protected-main commits or admitted same-repository PR heads on one host of a chosen backend at a time; it reports into the run summary and gates nothing -(see [`INFERENCE_PERFORMANCE.md`](INFERENCE_PERFORMANCE.md)). +(see [`INFERENCE_PERFORMANCE.md`](INFERENCE_PERFORMANCE.md)). `inference-performance-nightly.yml` +runs it every night for main against the commit its last successful run measured, one lane per +pinned node. Scheduled, manual and reusable full/candidate validation bypass path selection. Tagged releases and manual llama upgrades retain their explicit triggers. The diff --git a/ci/automation.just b/ci/automation.just index c0c336db..8e40580c 100644 --- a/ci/automation.just +++ b/ci/automation.just @@ -5,6 +5,7 @@ inference-contracts: @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_markdown.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_nightly.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_performance_contracts.py + @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_performance_nightly.py inference-publication-test: @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_publication.py @@ -16,6 +17,13 @@ automation-contracts: inference-contracts @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/graph_contracts.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/release_contracts.py +# The nightly comparison of main with the commit the last successful nightly measured. +inference-performance-nightly-plan: + @"{{ automation_python }}" scripts/inference-performance-nightly.py plan + +inference-performance-nightly-verdict: + @"{{ automation_python }}" scripts/inference-performance-nightly.py verdict + [positional-arguments] inference-render-report format input *options: @"{{ automation_python }}" scripts/inference-render-report.py "$@" diff --git a/ci/inference-performance-nightly.json b/ci/inference-performance-nightly.json new file mode 100644 index 00000000..89f4e7d0 --- /dev/null +++ b/ci/inference-performance-nightly.json @@ -0,0 +1,9 @@ +{ + "schema_version": 1, + "rounds": 3, + "lanes": [ + {"id": "metal-mini", "backend": "metal", "node": "macmini-g2hg9f", "model": "qwen35-9b"}, + {"id": "metal-studio", "backend": "metal", "node": "macstudio-2l0352", "model": "qwen36-35b-a3b"}, + {"id": "cuda-spark", "backend": "cuda", "node": "spark-001272", "model": "qwen35-9b"} + ] +} diff --git a/scripts/inference-performance-nightly.py b/scripts/inference-performance-nightly.py new file mode 100644 index 00000000..c4d8f11d --- /dev/null +++ b/scripts/inference-performance-nightly.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Plan the nightly performance comparison of main and settle its result.""" + +import argparse +import json +import os +import subprocess +import sys +import traceback + +from lib.ci_process import command +from lib.performance_nightly import WORKFLOW, compared, lanes, matrix, previous, verdict + +REPO = "Mesh-LLM/skippy" +HOW = {"commits": "the commit the last successful nightly measured", + "noise": "the same commit: an A/A run that measures the spread of two equal builds", + "unchanged": "the same commit: main has not moved since the last successful nightly"} + + +def github(path): + return json.loads(command(["gh", "api", path], overrides={"GH_TOKEN": os.environ["GH_TOKEN"]}, + capture_stdout=True)) + + +def plan(): + """Tonight's commit is the run's own head, so every lane and the next night's baseline agree on it.""" + candidate = os.environ["GITHUB_SHA"] + if os.environ.get("GITHUB_REF") != "refs/heads/main": + raise ValueError("the nightly measures main: run it from main") + runs = github(f"repos/{REPO}/actions/workflows/{WORKFLOW}/runs?branch=main&status=success&per_page=20") + found = previous(runs["workflow_runs"], int(os.environ["GITHUB_RUN_ID"])) + baseline, mode = compared(candidate, found, os.environ.get("REBASELINE") == "true") + lane_list = lanes() + outputs = {"candidate": candidate, "baseline": baseline, "mode": mode, + "matrix": json.dumps(matrix(lane_list), separators=(",", ":"))} + with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as stream: + stream.writelines(f"{name}={value}\n" for name, value in outputs.items()) + print(f"candidate {candidate}\nbaseline {baseline}: {HOW[mode]}") + print(f'{len(lane_list)} lane(s): {", ".join(lane["id"] for lane in lane_list)}; nothing has run yet') + + +def settle(): + results = {name: os.environ.get(name.upper()) for name in ("plan", "measure")} + passed, sentence = verdict(os.environ.get("MODE"), results) + if os.environ.get("GITHUB_STEP_SUMMARY"): + with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as stream: + stream.write(sentence + "\n") + print(sentence) + if not passed: + sys.exit(1) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + actions = parser.add_subparsers(dest="action", required=True) + actions.add_parser("plan") + actions.add_parser("verdict") + args = parser.parse_args() + if args.action == "plan": + plan() + else: + settle() + + +if __name__ == "__main__": + try: + main() + except (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError) as error: + traceback.print_exc() + sys.exit(str(error)) diff --git a/scripts/lib/performance_nightly.py b/scripts/lib/performance_nightly.py new file mode 100644 index 00000000..c78bcfbd --- /dev/null +++ b/scripts/lib/performance_nightly.py @@ -0,0 +1,93 @@ +"""Plan the nightly comparison: main against the commit the last successful nightly measured.""" + +import re + +from .ci_artifacts import read_json +from .performance_backends import BACKENDS +from .performance_plan import MAX_ROUNDS, NODE, ROOT, SHA, count, models, scenario + +NIGHTLY = ROOT / "ci/inference-performance-nightly.json" +WORKFLOW = "inference-performance-nightly.yml" +# A lane's id names its evidence artifact, so it is lower-case words joined by dashes. +LANE = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*") +LANE_FIELDS = {"id", "backend", "node", "model"} +# What a night compares. `commits`: main against the last successful nightly's commit. `noise`: main +# against itself, the first night or when asked, which measures the spread of two equal builds. +# `unchanged`: main has not moved since the last successful nightly, so nothing is measured. +MODES = ("commits", "noise", "unchanged") + + +def lanes(): + """The checked lanes: each is one model on one pinned node, and no node is in two lanes. Two jobs + on one node would queue behind each other inside a single controller's deadline, and a job of + several models is recorded without its place in the results' history.""" + value = read_json(NIGHTLY) + if (type(value) is not dict or set(value) != {"schema_version", "rounds", "lanes"} + or value["schema_version"] != 1 or type(value["lanes"]) is not list or not value["lanes"]): + raise ValueError("invalid nightly performance lanes") + rounds = count(value["rounds"], "rounds") + if rounds > MAX_ROUNDS: + raise ValueError(f"at most {MAX_ROUNDS} rounds fit the job's time budget") + ids, pinned, result = set(), set(), [] + for lane in value["lanes"]: + if type(lane) is not dict or not LANE_FIELDS <= set(lane) <= LANE_FIELDS | {"servers", "trace"}: + raise ValueError("a nightly lane names its id, backend, node and model") + name, backend, node, model = (lane[field] for field in ("id", "backend", "node", "model")) + if type(name) is not str or not LANE.fullmatch(name) or name in ids: + raise ValueError(f"nightly lane ids are distinct lower-case words joined by dashes: {name!r}") + if type(backend) is not str or backend not in BACKENDS: + raise ValueError(f"{name}: unknown backend {backend!r}; the table holds {', '.join(sorted(BACKENDS))}") + if type(node) is not str or not NODE.fullmatch(node) or node in pinned: + raise ValueError(f"{name}: a lane pins one JY node that no other lane uses") + if type(model) is not str: + raise ValueError(f"{name}: a lane measures one pinned model") + servers, trace = lane.get("servers"), lane.get("trace", False) + if servers is not None: + if type(servers) is not list or not all(type(server) is str for server in servers): + raise ValueError(f"{name}: servers is a list of scenario server ids") + scenario(servers) + if type(trace) is not bool: + raise ValueError(f"{name}: trace must be true or false") + ids.add(name) + pinned.add(node) + result.append({"id": name, "backend": backend, "node": node, "model": models([model])[0], + "servers": servers, "trace": trace, "rounds": rounds}) + return result + + +def matrix(lane_list): + """The lanes as the strategy matrix of the workflow's measuring job, one call of the + performance workflow each.""" + return {"include": [{**lane, "servers": ",".join(lane["servers"] or [])} for lane in lane_list]} + + +def previous(runs, current): + """The commit the last successful nightly measured: its head on main. `runs` is GitHub's list + of this workflow's runs, newest first; `current` is the run asking.""" + for run in runs: + if (run.get("id") != current and run.get("conclusion") == "success" + and run.get("head_branch") == "main" and run.get("event") in {"schedule", "workflow_dispatch"} + and SHA.fullmatch(run.get("head_sha") or "")): + return run["head_sha"] + return None + + +def compared(candidate, found, rebaseline): + """(baseline, mode) for tonight's `candidate`, given the commit `found` by `previous`.""" + if not SHA.fullmatch(candidate): + raise ValueError("the nightly measures an immutable 40-digit commit") + if rebaseline or found is None: + return candidate, "noise" + return found, "unchanged" if found == candidate else "commits" + + +def verdict(mode, results): + """(passed, sentence) for the night, from each workflow job's result by name. A night that + measured nothing because main has not moved passes; any lane that did not finish fails it.""" + if results.get("plan") != "success" or mode not in MODES: + return False, "The nightly plan did not succeed." + if mode == "unchanged": + return True, "main has not moved since the last successful nightly, so nothing was measured." + if results.get("measure") != "success": + return False, "A lane did not finish measuring." + return True, "Every lane finished measuring." diff --git a/scripts/tests/inference_performance_nightly.py b/scripts/tests/inference_performance_nightly.py new file mode 100644 index 00000000..70ab88af --- /dev/null +++ b/scripts/tests/inference_performance_nightly.py @@ -0,0 +1,137 @@ +"""Offline checks for the nightly performance comparison's lanes, baseline and verdict.""" + +import json +import unittest +from pathlib import Path +from runpy import run_path +from tempfile import TemporaryDirectory +from unittest.mock import patch + +from lib import performance_nightly, performance_plan +from lib.performance_nightly import compared, lanes, matrix, previous, verdict + +SCRIPT = str(Path(__file__).resolve().parents[1] / "inference-performance-nightly.py") +CANDIDATE, BASELINE, PIN = "a" * 40, "b" * 40, "c" * 40 + + +def shipped(): + return performance_plan.read_json(performance_nightly.NIGHTLY) + + +class LaneTests(unittest.TestCase): + def broken(self, change): + value = shipped() + change(value) + with patch.object(performance_nightly, "read_json", return_value=value): + with self.assertRaises(ValueError): + lanes() + + def test_every_shipped_lane_plans_a_job_on_its_pinned_node(self): + arm_list = performance_plan.arms(CANDIDATE, BASELINE, PIN) + for lane in lanes(): + spec = performance_plan.job_spec("d" * 40, arm_list, [lane["model"]], lane["rounds"], lane["node"], + lane["id"], trace=lane["trace"], backend=lane["backend"], + servers=lane["servers"]) + self.assertEqual(spec["target"]["nodes"], [lane["node"]]) + + def test_a_lane_is_one_pinned_model_on_a_node_of_its_own(self): + def second(field, value): + return lambda config: config["lanes"][1].update({field: value}) + + first = shipped()["lanes"][0] + for change in (second("id", first["id"]), second("node", first["node"]), second("id", "Metal Mini"), + second("backend", "space-heater"), second("model", "no-such-model"), + second("model", ["qwen35-4b", "qwen35-9b"]), second("node", "two nodes"), + second("servers", []), second("servers", ["no-such-server"]), second("servers", "lanes4"), + second("trace", "true"), second("rounds", 3), + lambda config: config["lanes"][0].pop("node"), + lambda config: config.update(rounds=performance_plan.MAX_ROUNDS + 1), + lambda config: config.update(rounds="3"), + lambda config: config.update(lanes=[]), + lambda config: config.update(schema_version=2)): + self.broken(change) + + def test_a_lane_may_name_its_servers_and_a_trace_pass(self): + value = shipped() + value["lanes"][0].update(servers=["lanes4", "lanes4-pool32k"], trace=True) + with patch.object(performance_nightly, "read_json", return_value=value): + first = lanes()[0] + self.assertEqual((first["servers"], first["trace"]), (["lanes4", "lanes4-pool32k"], True)) + row = matrix([first])["include"][0] + self.assertEqual((row["servers"], row["trace"], row["rounds"]), ("lanes4,lanes4-pool32k", True, value["rounds"])) + + def test_the_matrix_gives_the_workflow_one_call_per_lane(self): + rows = matrix(lanes())["include"] + self.assertEqual([row["id"] for row in rows], [lane["id"] for lane in shipped()["lanes"]]) + for row in rows: + self.assertEqual(set(row), {"id", "backend", "node", "model", "servers", "trace", "rounds"}) + self.assertEqual((row["servers"], row["trace"]), ("", False)) + json.dumps(rows) + + +class BaselineTests(unittest.TestCase): + def run_record(self, **overrides): + return {"id": 7, "conclusion": "success", "head_branch": "main", "event": "schedule", + "head_sha": BASELINE, **overrides} + + def test_the_baseline_is_the_last_successful_nightlys_commit_on_main(self): + newer = self.run_record(id=9, head_sha=PIN) + self.assertEqual(previous([newer, self.run_record()], 11), PIN) + self.assertEqual(previous([newer, self.run_record()], 9), BASELINE) + self.assertEqual(previous([self.run_record(event="workflow_dispatch")], 11), BASELINE) + for skipped in ({"conclusion": "failure"}, {"conclusion": None}, {"head_branch": "feature"}, + {"event": "pull_request"}, {"head_sha": "abc"}, {"head_sha": None}): + self.assertIsNone(previous([self.run_record(**skipped)], 11)) + self.assertIsNone(previous([], 11)) + + def test_a_night_compares_commits_or_measures_noise_or_measures_nothing(self): + self.assertEqual(compared(CANDIDATE, BASELINE, False), (BASELINE, "commits")) + self.assertEqual(compared(CANDIDATE, CANDIDATE, False), (CANDIDATE, "unchanged")) + self.assertEqual(compared(CANDIDATE, None, False), (CANDIDATE, "noise")) + for found in (BASELINE, CANDIDATE, None): + self.assertEqual(compared(CANDIDATE, found, True), (CANDIDATE, "noise")) + with self.assertRaises(ValueError): + compared("main", BASELINE, False) + + def test_plan_hands_the_workflow_its_commits_and_lanes(self): + plan = run_path(SCRIPT)["plan"] + asked = [] + + def github(path): + asked.append(path) + return {"workflow_runs": [self.run_record()]} + + with TemporaryDirectory() as directory: + output = Path(directory) / "output" + environment = {"GITHUB_SHA": CANDIDATE, "GITHUB_REF": "refs/heads/main", "GITHUB_RUN_ID": "11", + "GITHUB_OUTPUT": str(output)} + with patch.dict(plan.__globals__, github=github), patch.dict("os.environ", environment): + plan() + written = dict(line.split("=", 1) for line in output.read_text(encoding="utf-8").splitlines()) + with patch.dict("os.environ", GITHUB_REF="refs/heads/feature"): + with self.assertRaisesRegex(ValueError, "main"): + plan() + self.assertEqual(asked[0], "repos/Mesh-LLM/skippy/actions/workflows/inference-performance-nightly.yml/runs" + "?branch=main&status=success&per_page=20") + self.assertEqual((written["candidate"], written["baseline"], written["mode"]), + (CANDIDATE, BASELINE, "commits")) + self.assertEqual(json.loads(written["matrix"]), matrix(lanes())) + + +class VerdictTests(unittest.TestCase): + def test_a_night_passes_only_when_every_lane_measured_or_main_has_not_moved(self): + def passed(mode, **results): + return verdict(mode, results)[0] + + self.assertTrue(passed("commits", plan="success", measure="success")) + self.assertTrue(passed("noise", plan="success", measure="success")) + self.assertTrue(passed("unchanged", plan="success", measure="skipped")) + for mode, plan, measure in (("commits", "failure", "success"), ("", "success", "success"), + ("commits", "success", "failure"), ("commits", "success", "cancelled"), + ("noise", "success", "skipped"), ("commits", "success", "")): + self.assertFalse(passed(mode, plan=plan, measure=measure), (mode, plan, measure)) + self.assertFalse(passed("commits", plan="success")) + + +if __name__ == "__main__": + unittest.main() From ed5beabd893c33e98a85afa7b1a168556b63ceaf Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Tue, 1 Dec 2026 14:11:52 +1100 Subject: [PATCH 37/50] Report where Skippy regressed since the last nightly Each lane's summary showed its own comparison, but nothing said whether a finished job was a measurement, or gathered the night into one answer. The report job now checks each job's evidence against its plan: the pinned node, every arm at every point each round, no arm without a setting, the output length asked for, no missing metric, and rejections only from llama-server where its pool cannot hold the point. It then compares the two commits cell by cell. A cell is regressed when tonight's median is worse by more than the shared 1% tolerance and none of its rounds reaches the baseline's. A regression is llama.cpp's when the pin moved and llama-server lost as much at that cell; otherwise it is Skippy's. A cell an arm did not measure is never a regression, and on an A/A night every difference is spread. The log goes to the run summary and a 90-day artifact. The verdict job fails the night for an unfinished lane, evidence that did not hold or a regression in Skippy, so the baseline stays at the last commit that passed. --- .agents/skills/manage-ci/SKILL.md | 8 +- .../inference-performance-nightly.test.cjs | 8 + .../inference-performance-nightly.yml | 48 +++- ci/INFERENCE_PERFORMANCE.md | 18 ++ ci/automation.just | 4 + scripts/inference-performance-nightly.py | 53 +++- scripts/lib/performance_audit.py | 47 ++++ scripts/lib/performance_nightly.py | 174 +++++++++++- .../tests/inference_performance_nightly.py | 261 +++++++++++++++++- 9 files changed, 593 insertions(+), 28 deletions(-) create mode 100644 scripts/lib/performance_audit.py diff --git a/.agents/skills/manage-ci/SKILL.md b/.agents/skills/manage-ci/SKILL.md index 9937bd47..9ab5cb69 100644 --- a/.agents/skills/manage-ci/SKILL.md +++ b/.agents/skills/manage-ci/SKILL.md @@ -147,7 +147,13 @@ contract; no downstream product's workflow topology applies here. the head of the last successful nightly, with llama.cpp's server at each commit's pin. The first night and a `rebaseline` dispatch measure main against itself; a night on an unmoved main measures nothing and passes. A - failed night leaves the baseline at the last commit that passed. + failed night leaves the baseline at the last commit that passed. Its report + job holds no credentials: it checks each job's evidence against its plan + and compares the commits cell by cell at the shared 1% tolerance. The night + fails for an unfinished lane, evidence that did not hold, or a Skippy + regression whose rounds do not overlap the baseline's; a regression + llama.cpp's own server shares after a pin move is reported as llama.cpp's. + Never report an unmeasured cell as a regression. - The protected inference results-comment job alone receives pull-requests write permission for PR comments, plus read-only contents/actions. It receives no native dispatch credential and never executes candidate code. diff --git a/.github/scripts/inference-performance-nightly.test.cjs b/.github/scripts/inference-performance-nightly.test.cjs index f08c21c0..322cf620 100644 --- a/.github/scripts/inference-performance-nightly.test.cjs +++ b/.github/scripts/inference-performance-nightly.test.cjs @@ -28,6 +28,14 @@ test('every lane measures the same two commits against llama.cpp and keeps its o ]) assert.ok(measure.includes(line), line); }); +test('the report runs after a failed lane, over the evidence of every attempt, and holds no credentials', () => { + const report = job('report'); + assert.ok(report.includes( + "if: always() && !cancelled() && needs.plan.result == 'success' && needs.plan.outputs.mode != 'unchanged'")); + assert.ok(report.includes('pattern: inference-performance-*-${{ github.run_id }}-*')); + assert.ok(!report.includes('secrets.')); +}); + test('the verdict runs after a failed lane and reads every job it depends on', () => { const verdict = job('verdict'); assert.ok(verdict.includes("if: always() && needs.plan.result != 'skipped'")); diff --git a/.github/workflows/inference-performance-nightly.yml b/.github/workflows/inference-performance-nightly.yml index 7f7b5e2c..b4870a25 100644 --- a/.github/workflows/inference-performance-nightly.yml +++ b/.github/workflows/inference-performance-nightly.yml @@ -65,9 +65,52 @@ jobs: label: ${{ matrix.id }} secrets: JIANYANG_INFERENCE_SSH_KEY: ${{ secrets.JIANYANG_INFERENCE_SSH_KEY }} + report: + name: Check the evidence and compare with the last nightly + needs: [plan, measure] + # After a failed lane too: the lanes that finished are still checked and compared. + if: always() && !cancelled() && needs.plan.result == 'success' && needs.plan.outputs.mode != 'unchanged' + runs-on: ${{ vars.SKIPPY_DEPOT_RUNNERS_ENABLED == 'true' && 'depot-ubuntu-24.04-4' || 'ubuntu-24.04' }} + timeout-minutes: 15 + permissions: + contents: read + actions: read + outputs: + regressions: ${{ steps.report.outputs.regressions }} + unverified: ${{ steps.report.outputs.unverified }} + env: + EVIDENCE: target/ci-evidence/inference-performance-nightly + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 + with: + ref: ${{ github.sha }} + persist-credentials: false + - uses: ./.github/actions/setup + with: + cache: 'false' + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c + continue-on-error: true + with: + # A rerun of the lanes that failed keeps what earlier attempts uploaded for the others. + pattern: inference-performance-*-${{ github.run_id }}-* + path: ${{ env.EVIDENCE }} + - id: report + name: Check each lane's evidence and find where Skippy regressed + env: + CANDIDATE: ${{ needs.plan.outputs.candidate }} + BASELINE: ${{ needs.plan.outputs.baseline }} + MODE: ${{ needs.plan.outputs.mode }} + run: just inference-performance-nightly-report "$EVIDENCE" + - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f + if: always() + with: + name: nightly-inference-performance-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ env.EVIDENCE }}/nightly + if-no-files-found: error + retention-days: 90 verdict: name: Nightly performance verdict - needs: [plan, measure] + needs: [plan, measure, report] if: always() && needs.plan.result != 'skipped' runs-on: ${{ vars.SKIPPY_DEPOT_RUNNERS_ENABLED == 'true' && 'depot-ubuntu-24.04-4' || 'ubuntu-24.04' }} timeout-minutes: 5 @@ -84,4 +127,7 @@ jobs: PLAN: ${{ needs.plan.result }} MODE: ${{ needs.plan.outputs.mode }} MEASURE: ${{ needs.measure.result }} + REPORT: ${{ needs.report.result }} + REGRESSIONS: ${{ needs.report.outputs.regressions }} + UNVERIFIED: ${{ needs.report.outputs.unverified }} run: just inference-performance-nightly-verdict diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index b490c38c..dc94c604 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -50,6 +50,24 @@ A night that fails leaves the baseline where it was, so the next night compares commit that passed. A dispatch with `rebaseline` measures main against itself, which gives the spread of two equal builds, and once it passes that commit is the next night's baseline. +After the lanes, the `report` job checks each job's evidence against its plan and compares the +two commits cell by cell: each model, point and headline metric. The checks are what makes a +finished job a measurement: it ran on the pinned node, every arm measured every point each +round, no arm ran without a setting, every request wrote the output length asked for, no +metric is missing, and only `llama-server` rejected requests, only where its pool could not +hold them. + +A cell is regressed when tonight's median is worse than the baseline's by more than the shared +1% tolerance and none of its rounds reaches the baseline's; improved is the same the other +way. Past the tolerance with overlapping rounds counts as neither. A regression is llama.cpp's +when the pin moved and `llama-server` lost as much at that cell, to within the tolerance; +otherwise it is Skippy's. A cell an arm did not measure is never a regression. + +The night's log is the run summary and the `nightly-inference-performance-RUN-ATTEMPT` +artifact, kept 90 days: `nightly.md`, and `nightly.json` with every lane's checks and cells. The +`verdict` job then fails the run when a lane did not finish, a lane's checks did not hold, or +Skippy regressed in any cell. An accepted regression is cleared with a `rebaseline` dispatch. + ## Backends `admit` reads `BACKEND` (default `metal`) and refuses any value that has no entry in the diff --git a/ci/automation.just b/ci/automation.just index 8e40580c..4dbee7a1 100644 --- a/ci/automation.just +++ b/ci/automation.just @@ -21,6 +21,10 @@ automation-contracts: inference-contracts inference-performance-nightly-plan: @"{{ automation_python }}" scripts/inference-performance-nightly.py plan +[positional-arguments] +inference-performance-nightly-report evidence: + @"{{ automation_python }}" scripts/inference-performance-nightly.py report "$@" + inference-performance-nightly-verdict: @"{{ automation_python }}" scripts/inference-performance-nightly.py verdict diff --git a/scripts/inference-performance-nightly.py b/scripts/inference-performance-nightly.py index c4d8f11d..32c63be6 100644 --- a/scripts/inference-performance-nightly.py +++ b/scripts/inference-performance-nightly.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Plan the nightly performance comparison of main and settle its result.""" +"""Plan the nightly performance comparison of main, report where Skippy regressed and settle its result.""" import argparse import json @@ -7,9 +7,12 @@ import subprocess import sys import traceback +from pathlib import Path +from lib.ci_artifacts import write_json from lib.ci_process import command -from lib.performance_nightly import WORKFLOW, compared, lanes, matrix, previous, verdict +from lib.performance_nightly import (WORKFLOW, compared, evidence, lane_report, lanes, markdown, matrix, night, + previous, verdict) REPO = "Mesh-LLM/skippy" HOW = {"commits": "the commit the last successful nightly measured", @@ -39,13 +42,46 @@ def plan(): print(f'{len(lane_list)} lane(s): {", ".join(lane["id"] for lane in lane_list)}; nothing has run yet') -def settle(): - results = {name: os.environ.get(name.upper()) for name in ("plan", "measure")} - passed, sentence = verdict(os.environ.get("MODE"), results) +def summarized(text): if os.environ.get("GITHUB_STEP_SUMMARY"): with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as stream: - stream.write(sentence + "\n") - print(sentence) + stream.write(text) + print(text, end="") + + +def report(root): + """Check each lane's evidence and compare tonight's commit with the baseline, cell by cell. + It writes the night's record and log under `root`/nightly and passes whatever it finds: the + verdict job fails the night, so a regression is still kept with its evidence.""" + candidate, baseline, mode = (os.environ[name] for name in ("CANDIDATE", "BASELINE", "MODE")) + if mode not in ("commits", "noise"): + raise ValueError("a night that measured nothing has nothing to report") + lane_list = lanes() + found = evidence(root, lane_list, os.environ["GITHUB_RUN_ID"]) + result = night(candidate, baseline, mode, + [lane_report(lane, found.get(lane["id"]), candidate, baseline, mode) for lane in lane_list]) + output = root / "nightly" + output.mkdir(parents=True, exist_ok=True) + write_json(output / "nightly.json", result) + text = markdown(result) + (output / "nightly.md").write_text(text, encoding="utf-8") + if os.environ.get("GITHUB_OUTPUT"): + with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as stream: + stream.writelines(f'{name}={result["totals"][name]}\n' for name in ("regressions", "unverified")) + summarized(text) + + +def counts(): + """The report's counts as the workflow hands them on, or None when the report wrote none.""" + values = {name: os.environ.get(name.upper(), "") for name in ("regressions", "unverified")} + return {name: int(value) for name, value in values.items()} if all( + value.isdigit() for value in values.values()) else None + + +def settle(): + results = {name: os.environ.get(name.upper()) for name in ("plan", "measure", "report")} + passed, sentence = verdict(os.environ.get("MODE"), results, counts()) + summarized(sentence + "\n") if not passed: sys.exit(1) @@ -54,10 +90,13 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) actions = parser.add_subparsers(dest="action", required=True) actions.add_parser("plan") + actions.add_parser("report").add_argument("evidence", type=Path) actions.add_parser("verdict") args = parser.parse_args() if args.action == "plan": plan() + elif args.action == "report": + report(args.evidence) else: settle() diff --git a/scripts/lib/performance_audit.py b/scripts/lib/performance_audit.py new file mode 100644 index 00000000..ca4aba5d --- /dev/null +++ b/scripts/lib/performance_audit.py @@ -0,0 +1,47 @@ +"""Check that a finished performance job is the measurement its plan admitted.""" + +from .performance_arms import may_reject +from .performance_plan import scenario + + +def audit(plan, record, node): + """What keeps `record` from being the measurement `plan` admitted, one sentence each; none + when it held. A job that succeeded can still have run an arm without a setting, cut its + output short or lost a metric, and its cells are then not like for like.""" + shape = scenario(plan.get("servers")) + points = {(server["id"], point["id"]): (server, point) + for server in shape["servers"] for point in server["points"]} + kinds = {arm["label"]: arm["kind"] for arm in plan["arms"]} + samples = record["samples"] + cells = len(points) * len(plan["models"]) + expected = cells * len(plan["arms"]) * plan["rounds"] + ran_on = (record.get("host") or {}).get("node") + # a dict keeps each sentence once, in the order found: the rounds repeat the same fault + found = {} + if node is not None and ran_on != node: + found[f"it ran on {ran_on}, not the pinned {node}"] = None + if len(samples) != expected: + found[f"{len(samples)} measured samples, not the {expected} its arms, points and rounds make"] = None + traced = len((record.get("diagnostic") or {}).get("samples") or []) + if plan["trace"] and traced != cells: + found[f"{traced} traced samples, not one for each of its {cells} points"] = None + for sample in samples: + where = f'{sample["arm"]} at {sample["point"]}' + known = points.get((sample["server"], sample["point"])) + if known is None or sample["arm"] not in kinds or sample["model"] not in plan["models"]: + found[f"{where} is not a cell of the plan"] = None + continue + server, point = known + for flag in sample["unsupported"]: + found[f'{sample["arm"]} ran without {flag}'] = None + if sample["rejected"] is not None: + if not may_reject({"kind": kinds[sample["arm"]]}, server, point): + found[f"{where} failed requests its pool could hold"] = None + continue + metrics = sample["metrics"] + if any(value is None for value in metrics.values()): + found[f"{where} is missing a metric"] = None + if "output_tokens" in point and metrics.get("output_tokens_mean") != point["output_tokens"]: + found[f'{where} wrote {metrics.get("output_tokens_mean")} tokens a request, ' + f'not the {point["output_tokens"]} asked for'] = None + return list(found) diff --git a/scripts/lib/performance_nightly.py b/scripts/lib/performance_nightly.py index c78bcfbd..9efe0df0 100644 --- a/scripts/lib/performance_nightly.py +++ b/scripts/lib/performance_nightly.py @@ -1,10 +1,18 @@ -"""Plan the nightly comparison: main against the commit the last successful nightly measured.""" +"""Plan the nightly comparison of main with the commit the last successful nightly measured, and +say where Skippy regressed between them.""" import re from .ci_artifacts import read_json +from .inference_baselines import TOLERANCE, classify +from .inference_charts import METRICS as TITLES +from .inference_markdown import plain, sha, table +from .performance_audit import audit from .performance_backends import BACKENDS from .performance_plan import MAX_ROUNDS, NODE, ROOT, SHA, count, models, scenario +from .performance_report import HEADLINE, llama_change, summarize +from .performance_report import cell as rounds_text +from .performance_report import verdict as described NIGHTLY = ROOT / "ci/inference-performance-nightly.json" WORKFLOW = "inference-performance-nightly.yml" @@ -81,13 +89,169 @@ def compared(candidate, found, rebaseline): return found, "unchanged" if found == candidate else "commits" -def verdict(mode, results): - """(passed, sentence) for the night, from each workflow job's result by name. A night that - measured nothing because main has not moved passes; any lane that did not finish fails it.""" +def evidence(root, lane_list, run): + """Each lane's evidence directory under `root`, from the newest attempt that uploaded one: a + rerun of the lanes that failed keeps the earlier attempt's artifacts for those that passed.""" + found = {} + for lane in lane_list: + prefix = f'inference-performance-{lane["id"]}-{run}-' + attempts = [(int(path.name[len(prefix):]), path) for path in (root.iterdir() if root.is_dir() else ()) + if path.is_dir() and path.name.startswith(prefix) and path.name[len(prefix):].isdigit()] + if attempts: + found[lane["id"]] = max(attempts)[1] + return found + + +def worse(metric, percent): + """A change as percent worse: throughput that fell and latency that rose both come out positive.""" + return -percent if HEADLINE[metric] == "higher" else percent + + +def cells(record, mode): + """Every headline cell that tonight's commit and the baseline both measured, with its state. + + `regressed`: the candidate is worse by more than the shared tolerance and none of its rounds + reaches the baseline's. `improved` is the same the other way. `uncertain`: past the tolerance + with overlapping rounds, which counts as neither. `within`: inside the tolerance. On a noise + night both arms are one commit, so every cell is `noise`, whatever it measured. + + A regression is llama.cpp's when the pin moved and `llama-server` lost as much at that cell, + to within the tolerance; otherwise it is Skippy's. A cell an arm did not measure is left + out: an unmeasured cell is never reported as a regression.""" + result = [] + for row in summarize(record["samples"]): + delta = row["candidate_vs_baseline"] + if row["metric"] not in HEADLINE or delta is None: + continue + metric, arms = row["metric"], row["arms"] + moved = classify(metric, arms["candidate"]["median"], arms["baseline"]["median"]) + if mode == "noise": + state = "noise" + elif moved == "passed": + state = "within" + else: + state = "uncertain" if delta["ranges_overlap"] else moved + llama, owner = row["reference_vs_baseline_reference"], None + if state == "regressed": + inherited = (llama is not None and not llama["ranges_overlap"] + and classify(metric, arms["reference"]["median"], + arms["baseline-reference"]["median"]) == "regressed" + and worse(metric, delta["percent"]) - worse(metric, llama["percent"]) + <= float(TOLERANCE) * 100) + owner = "llama.cpp" if inherited else "skippy" + result.append({"model": row["model"], "server": row["server"], "point": row["point"], "metric": metric, + "state": state, "owner": owner, "percent": delta["percent"], + "ranges_overlap": delta["ranges_overlap"], + "llama_percent": None if llama is None else llama["percent"], + "arms": arms, "rejected": row["rejected"], + "change": described(row), "llama_change": llama_change(row)}) + return result + + +def lane_report(lane, directory, candidate, baseline, mode): + """One lane's job: what its evidence checks found, and how tonight's commit compares in + each cell. A lane without a finished job has a check that says so and no cells.""" + report = {**{field: lane[field] for field in ("id", "backend", "node", "model")}, + "job": None, "host": None, "cells": []} + if directory is None or not (directory / "plan.json").is_file(): + return {**report, "checks": ["its job was not planned, or its evidence was not uploaded"]} + plan = read_json(directory / "plan.json") + ledger = read_json(directory / "jobs.json") if (directory / "jobs.json").is_file() else [] + report["job"] = ledger[0] if ledger else None + measured = directory / f'{plan["jobs"][0]["label"]}-performance.json' + if not measured.is_file(): + return {**report, "checks": ["its job did not finish, so there is nothing to compare"]} + record = read_json(measured) + commits = {arm["label"]: arm["sha"] for arm in plan["arms"]} + checks = audit(plan, record, lane["node"]) + if (commits.get("candidate"), commits.get("baseline"), plan["models"]) != (candidate, baseline, [lane["model"]]): + checks.insert(0, "its plan is not tonight's commits and this lane's model") + host = record.get("host") or {} + return {**report, "host": host.get("gpu") or host.get("chip"), "checks": checks, "cells": cells(record, mode)} + + +def night(candidate, baseline, mode, lane_reports): + """The night's record: every lane, and the counts its verdict and its log are made from.""" + every = [found for lane in lane_reports for found in lane["cells"]] + + def having(state, owner=None): + return sum(1 for found in every if found["state"] == state and owner in (None, found["owner"])) + + totals = {"lanes": len(lane_reports), "unverified": sum(1 for lane in lane_reports if lane["checks"]), + "cells": len(every), "regressions": having("regressed", "skippy"), + "llama_regressions": having("regressed", "llama.cpp"), "improvements": having("improved"), + "uncertain": having("uncertain")} + return {"schema_version": 1, "candidate": candidate, "baseline": baseline, "mode": mode, + "lanes": lane_reports, "totals": totals} + + +def changed(report, state, headers, columns): + """A table of the cells in `state`, largest change first, or nothing when there are none.""" + pairs = sorted(((lane, found) for lane in report["lanes"] for found in lane["cells"] if found["state"] == state), + key=lambda pair: -abs(pair[1]["percent"])) + if not pairs: + return [] + return table(["Lane", "Host", "Model", "Point", "Metric", "Previous", "Tonight", *headers], + [[plain(lane["id"]), plain(lane["host"] or "unknown"), plain(found["model"]), plain(found["point"]), + TITLES[found["metric"]][0], + rounds_text(found["arms"]["baseline"], found["rejected"].get("baseline", 0)), + rounds_text(found["arms"]["candidate"], found["rejected"].get("candidate", 0)), + *(column(found) for column in columns)] for lane, found in pairs]) + + +def markdown(report): + """The night's log: what was compared, where Skippy regressed and improved, and whether each + lane's evidence held. It names no service outside this repository, since it is public.""" + totals, candidate = report["totals"], sha(report["candidate"]) + lines = ["# Nightly inference performance", ""] + if report["mode"] == "noise": + lines += [f"{candidate} against itself: an A/A run. Both arms are one commit, so what differs below is " + "the spread of two equal builds on each machine, not a change.", ""] + else: + lines += [f'{candidate} against {sha(report["baseline"])}, the commit the last successful nightly ' + "measured, each beside `llama-server` at its own llama.cpp pin.", "", + f'**{totals["regressions"]} regressions in Skippy**, {totals["llama_regressions"]} in llama.cpp, ' + f'{totals["improvements"]} improvements, and {totals["uncertain"]} past the tolerance with ' + f'overlapping rounds, across {totals["cells"]} cells on {totals["lanes"]} lanes.', "", + f"A cell is regressed or improved when its medians differ by more than {float(TOLERANCE):.0%} and " + "no round of one arm reaches the other's. A regression is llama.cpp's when the pin moved and " + "`llama-server` lost as much at that cell.", ""] + regressions = changed(report, "regressed", ["Change", "llama.cpp change", "Whose"], + [lambda found: found["change"], lambda found: found["llama_change"], + lambda found: "llama.cpp" if found["owner"] == "llama.cpp" else "Skippy"]) + if regressions: + lines += ["## Regressions", "", "Median (min–max, n) over the rounds.", "", *regressions, ""] + improvements = changed(report, "improved", ["Change"], [lambda found: found["change"]]) + if improvements: + lines += ["## Improvements", "", *improvements, ""] + if report["mode"] == "noise": + spread = changed(report, "noise", ["Difference"], [lambda found: f'{found["percent"]:+.2f}%']) + lines += ["## Spread of two equal builds", "", *(spread or ["No cell was measured by both arms."]), ""] + lines += ["## Evidence", "", "A lane's cells are like for like only when its checks held.", "", + *table(["Lane", "Node", "Model", "Job", "Checks"], + [[plain(lane["id"]), plain(lane["node"]), plain(lane["model"]), plain(lane["job"] or "none"), + plain("; ".join(lane["checks"])) if lane["checks"] else "held"] + for lane in report["lanes"]])] + return "\n".join(lines) + "\n" + + +def verdict(mode, results, totals=None): + """(passed, sentence) for the night, from each workflow job's result by name and the report's + counts. A night that measured nothing because main has not moved passes. A lane that did not + finish, evidence that did not hold and a regression in Skippy each fail it, so the baseline + stays at the last commit that passed.""" if results.get("plan") != "success" or mode not in MODES: return False, "The nightly plan did not succeed." if mode == "unchanged": return True, "main has not moved since the last successful nightly, so nothing was measured." if results.get("measure") != "success": return False, "A lane did not finish measuring." - return True, "Every lane finished measuring." + if results.get("report") != "success" or totals is None: + return False, "The night's evidence was not checked and compared." + if totals["unverified"]: + return False, f'The evidence checks did not hold on {totals["unverified"]} lane(s).' + if totals["regressions"]: + return False, f'Skippy regressed at {totals["regressions"]} cell(s) since the last successful nightly.' + if mode == "noise": + return True, "The A/A run finished; the next nightly compares with this commit." + return True, "No regression in Skippy since the last successful nightly." diff --git a/scripts/tests/inference_performance_nightly.py b/scripts/tests/inference_performance_nightly.py index 70ab88af..80765920 100644 --- a/scripts/tests/inference_performance_nightly.py +++ b/scripts/tests/inference_performance_nightly.py @@ -1,4 +1,4 @@ -"""Offline checks for the nightly performance comparison's lanes, baseline and verdict.""" +"""Offline checks for the nightly performance comparison's lanes, baseline, evidence, regressions and verdict.""" import json import unittest @@ -8,16 +8,54 @@ from unittest.mock import patch from lib import performance_nightly, performance_plan -from lib.performance_nightly import compared, lanes, matrix, previous, verdict +from lib.performance_arms import may_reject +from lib.performance_audit import audit +from lib.performance_nightly import (cells, compared, evidence, lane_report, lanes, markdown, matrix, night, + previous, verdict) SCRIPT = str(Path(__file__).resolve().parents[1] / "inference-performance-nightly.py") CANDIDATE, BASELINE, PIN = "a" * 40, "b" * 40, "c" * 40 +LANE = {"id": "metal-studio", "backend": "metal", "node": "n1", "model": "qwen35-4b", "servers": None, + "trace": False, "rounds": 3} def shipped(): return performance_plan.read_json(performance_nightly.NIGHTLY) +def admitted(servers=None, trace=False, baseline_reference=None): + """A plan as `admit` writes it, for one model on the node n1.""" + return {"arms": performance_plan.arms(CANDIDATE, BASELINE, PIN, baseline_reference), "models": ["qwen35-4b"], + "rounds": 3, "trace": trace, "servers": servers, "jobs": [{"label": "n1"}]} + + +def measured(plan, rate=None): + """A record in which every arm measured every point each round, as its plan admitted: `rate` + gives an arm's output tokens a second, and llama-server rejects what its pool cannot hold.""" + shape = performance_plan.scenario(plan.get("servers")) + points = [(server, point) for server in shape["servers"] for point in server["points"]] + samples = [] + for index in range(plan["rounds"]): + for arm in plan["arms"]: + for server, point in points: + rejected = ({"requests": point["requests"], "failed": point["requests"], "cut_short": 0, "errors": []} + if may_reject(arm, server, point) else None) + metrics = {"output_tok_s": (rate or {}).get(arm["label"], 100.0) + index, "ttft_ms_p50": 50.0 + index, + "itl_ms_p50": 10.0 + index, "output_tokens_mean": point["output_tokens"]} + samples.append({"model": plan["models"][0], "round": index + 1, "arm": arm["label"], + "server": server["id"], "point": point["id"], "applied": {}, "unsupported": [], + "metrics": dict.fromkeys(metrics) if rejected else metrics, "rejected": rejected}) + record = {"host": {"node": "n1", "chip": "Apple M3 Ultra"}, "samples": samples} + if plan["trace"]: + record["diagnostic"] = {"samples": [{"point": point["id"]} for _, point in points]} + return record + + +def rounds(arm, values, metric="output_tok_s"): + return [{"model": "m", "server": "s", "point": "p", "arm": arm, "metrics": {metric: value}, "rejected": None} + for value in values] + + class LaneTests(unittest.TestCase): def broken(self, change): value = shipped() @@ -118,19 +156,214 @@ def github(path): self.assertEqual(json.loads(written["matrix"]), matrix(lanes())) +class AuditTests(unittest.TestCase): + def test_a_job_that_measured_what_its_plan_admitted_holds(self): + for plan in (admitted(), admitted(trace=True), admitted(servers=["lanes4", "lanes4-pool32k"]), + admitted(baseline_reference="d" * 40)): + self.assertEqual(audit(plan, measured(plan), "n1"), []) + + def test_each_fault_is_named_once_however_many_rounds_repeat_it(self): + def faults(change, node="n1", plan=admitted()): + record = measured(plan) + change(record) + return audit(plan, record, node) + + def every(record, arm, point): + return [sample for sample in record["samples"] if (sample["arm"], sample["point"]) == (arm, point)] + + def lacking(record): + for sample in every(record, "baseline", "c4-short"): + sample["unsupported"] = ["--kv-pool-tokens"] + + def short(record): + for sample in every(record, "candidate", "c4-long-output"): + sample["metrics"]["output_tokens_mean"] = 1900.5 + + def unreported(record): + every(record, "candidate", "c16-depth0")[0]["metrics"]["itl_ms_p50"] = None + + def refused(arm, point): + def change(record): + every(record, arm, point)[0]["rejected"] = {"requests": 8, "failed": 8, "cut_short": 0, "errors": []} + return change + + self.assertEqual(faults(lambda record: None, node="n2"), ["it ran on n1, not the pinned n2"]) + self.assertEqual(faults(lambda record: record["samples"].pop()), + ["62 measured samples, not the 63 its arms, points and rounds make"]) + self.assertEqual(faults(lacking), ["baseline ran without --kv-pool-tokens"]) + self.assertEqual(faults(short), + ["candidate at c4-long-output wrote 1900.5 tokens a request, not the 2048 asked for"]) + self.assertEqual(faults(unreported), ["candidate at c16-depth0 is missing a metric"]) + self.assertEqual(faults(refused("candidate", "c16-depth4096")), + ["candidate at c16-depth4096 failed requests its pool could hold"]) + self.assertEqual(faults(refused("reference", "single-short")), + ["reference at single-short failed requests its pool could hold"]) + self.assertEqual(faults(lambda record: every(record, "candidate", "c4-short")[0].update(point="elsewhere")), + ["candidate at elsewhere is not a cell of the plan"]) + self.assertEqual(faults(lambda record: record.pop("diagnostic"), plan=admitted(trace=True)), + ["0 traced samples, not one for each of its 7 points"]) + + +class RegressionTests(unittest.TestCase): + slower = rounds("baseline", (100, 101, 99)) + rounds("candidate", (90, 91, 89)) + + def only(self, samples, mode="commits"): + found, = cells({"samples": samples}, mode) + return found + + def test_a_cell_moves_only_past_the_tolerance_with_its_rounds_apart(self): + slower = self.only(self.slower) + self.assertEqual((slower["state"], slower["owner"]), ("regressed", "skippy")) + self.assertAlmostEqual(slower["percent"], -10.0) + faster = self.only(rounds("baseline", (100, 101, 99)) + rounds("candidate", (110, 111, 109))) + self.assertEqual((faster["state"], faster["owner"]), ("improved", None)) + later = self.only(rounds("baseline", (100, 101, 99), "ttft_ms_p50") + + rounds("candidate", (110, 111, 109), "ttft_ms_p50")) + self.assertEqual((later["state"], later["owner"]), ("regressed", "skippy")) + level = self.only(rounds("baseline", (100, 101, 99)) + rounds("candidate", (100.5, 101.5, 99.5))) + self.assertEqual(level["state"], "within") + mixed = self.only(rounds("baseline", (90, 100, 110)) + rounds("candidate", (88, 95, 109))) + self.assertEqual((mixed["state"], mixed["owner"]), ("uncertain", None)) + + def test_two_arms_of_one_commit_measure_noise_and_never_a_regression(self): + found = self.only(self.slower, "noise") + self.assertEqual((found["state"], found["owner"]), ("noise", None)) + + def test_a_regression_is_llama_cpps_when_the_pin_moved_and_llama_server_lost_as_much(self): + old_pin = rounds("baseline-reference", (200, 201, 199)) + inherited = self.only(self.slower + old_pin + rounds("reference", (180, 181, 179))) + self.assertEqual((inherited["state"], inherited["owner"]), ("regressed", "llama.cpp")) + self.assertAlmostEqual(inherited["llama_percent"], -10.0) + mostly_ours = self.only(self.slower + old_pin + rounds("reference", (194, 195, 193))) + self.assertEqual(mostly_ours["owner"], "skippy") + same_pin = self.only(self.slower + rounds("reference", (180, 181, 179))) + self.assertEqual((same_pin["owner"], same_pin["llama_percent"]), ("skippy", None)) + + def test_a_cell_an_arm_did_not_measure_and_a_metric_outside_the_headline_are_left_out(self): + self.assertEqual(cells({"samples": rounds("candidate", (90, 91, 89))}, "commits"), []) + rejected = [{**sample, "metrics": {"output_tok_s": None}, "rejected": {"requests": 8}} + for sample in rounds("baseline", (100, 101, 99))] + self.assertEqual(cells({"samples": rejected + rounds("candidate", (90, 91, 89))}, "commits"), []) + self.assertEqual(cells({"samples": rounds("baseline", (9, 9, 9), "request_per_s") + + rounds("candidate", (1, 1, 1), "request_per_s")}, "commits"), []) + + +class NightTests(unittest.TestCase): + def write(self, directory, plan, record=None): + directory.mkdir(parents=True) + (directory / "plan.json").write_text(json.dumps(plan), encoding="utf-8") + (directory / "jobs.json").write_text(json.dumps(["job_1"]), encoding="utf-8") + if record is not None: + (directory / "n1-performance.json").write_text(json.dumps(record), encoding="utf-8") + + def test_each_lane_reads_the_newest_attempt_that_uploaded_its_evidence(self): + with TemporaryDirectory() as directory: + root = Path(directory) + for name in ("inference-performance-metal-studio-77-1", "inference-performance-metal-studio-77-2", + "inference-performance-metal-studio-78-9", "inference-performance-metal-77-3", + "nightly-inference-performance-77-1"): + (root / name).mkdir() + found = evidence(root, [LANE, {**LANE, "id": "cuda-spark"}], "77") + self.assertEqual({lane: path.name for lane, path in found.items()}, + {"metal-studio": "inference-performance-metal-studio-77-2"}) + self.assertEqual(evidence(root / "missing", [LANE], "77"), {}) + + def test_a_night_counts_skippys_regressions_and_names_the_lanes_that_did_not_hold(self): + plan = admitted() + with TemporaryDirectory() as directory: + root = Path(directory) + absent = lane_report(LANE, None, CANDIDATE, BASELINE, "commits") + self.assertEqual((absent["checks"], absent["cells"]), + (["its job was not planned, or its evidence was not uploaded"], [])) + self.write(root / "unfinished", plan) + unfinished = lane_report({**LANE, "id": "cuda-spark"}, root / "unfinished", CANDIDATE, BASELINE, "commits") + self.assertEqual((unfinished["job"], unfinished["cells"]), ("job_1", [])) + self.assertIn("did not finish", unfinished["checks"][0]) + self.write(root / "held", plan, measured(plan, rate={"candidate": 80.0})) + held = lane_report(LANE, root / "held", CANDIDATE, BASELINE, "commits") + other = lane_report(LANE, root / "held", "e" * 40, BASELINE, "commits") + quiet = lane_report(LANE, root / "held", CANDIDATE, BASELINE, "noise") + self.assertEqual((held["checks"], held["host"], held["job"]), ([], "Apple M3 Ultra", "job_1")) + # seven points, each with throughput, time to first token and time between tokens + self.assertEqual(len(held["cells"]), 21) + self.assertEqual({found["state"] for found in held["cells"] if found["metric"] == "output_tok_s"}, + {"regressed"}) + self.assertEqual({found["state"] for found in held["cells"] if found["metric"] != "output_tok_s"}, {"within"}) + self.assertEqual(other["checks"], ["its plan is not tonight's commits and this lane's model"]) + + report = night(CANDIDATE, BASELINE, "commits", [held, unfinished]) + self.assertEqual(report["totals"], {"lanes": 2, "unverified": 1, "cells": 21, "regressions": 7, + "llama_regressions": 0, "improvements": 0, "uncertain": 0}) + json.dumps(report) + text = markdown(report) + for expected in ("**7 regressions in Skippy**", "## Regressions", + "| metal-studio | Apple M3 Ultra | qwen35-4b | c16-depth0 | Output throughput |", + "Regressed; round ranges do not overlap", "| Skippy |", "## Evidence", "| held |", + "did not finish"): + self.assertIn(expected, text) + for absent_text in ("http", "## Improvements", "## Spread"): + self.assertNotIn(absent_text, text) + + noise = night(CANDIDATE, CANDIDATE, "noise", [quiet]) + self.assertEqual((noise["totals"]["regressions"], noise["totals"]["cells"]), (0, 21)) + text = markdown(noise) + for expected in ("an A/A run", "## Spread of two equal builds", "-19.80%"): + self.assertIn(expected, text) + self.assertNotIn("## Regressions", text) + + def test_report_writes_the_nights_record_log_and_counts(self): + report = run_path(SCRIPT)["report"] + plan = admitted() + with TemporaryDirectory() as directory: + root, output = Path(directory) / "evidence", Path(directory) / "output" + self.write(root / "inference-performance-metal-studio-11-1", plan, + measured(plan, rate={"candidate": 80.0})) + environment = {"CANDIDATE": CANDIDATE, "BASELINE": BASELINE, "MODE": "commits", "GITHUB_RUN_ID": "11", + "GITHUB_OUTPUT": str(output), "GITHUB_STEP_SUMMARY": ""} + with patch.dict(report.__globals__, lanes=lambda: [LANE]), patch.dict("os.environ", environment): + report(root) + with patch.dict("os.environ", MODE="unchanged"): + with self.assertRaises(ValueError): + report(root) + written = json.loads((root / "nightly/nightly.json").read_text(encoding="utf-8")) + log = (root / "nightly/nightly.md").read_text(encoding="utf-8") + counts = output.read_text(encoding="utf-8").splitlines() + self.assertEqual((written["candidate"], written["baseline"], written["mode"]), (CANDIDATE, BASELINE, "commits")) + self.assertEqual(written["totals"]["regressions"], 7) + self.assertIn("## Regressions", log) + self.assertEqual(counts, ["regressions=7", "unverified=0"]) + + class VerdictTests(unittest.TestCase): - def test_a_night_passes_only_when_every_lane_measured_or_main_has_not_moved(self): - def passed(mode, **results): - return verdict(mode, results)[0] - - self.assertTrue(passed("commits", plan="success", measure="success")) - self.assertTrue(passed("noise", plan="success", measure="success")) - self.assertTrue(passed("unchanged", plan="success", measure="skipped")) - for mode, plan, measure in (("commits", "failure", "success"), ("", "success", "success"), - ("commits", "success", "failure"), ("commits", "success", "cancelled"), - ("noise", "success", "skipped"), ("commits", "success", "")): - self.assertFalse(passed(mode, plan=plan, measure=measure), (mode, plan, measure)) - self.assertFalse(passed("commits", plan="success")) + clean = {"regressions": 0, "unverified": 0} + + def test_a_night_passes_only_when_every_lane_held_and_skippy_did_not_regress(self): + def passed(mode, totals=None, **results): + return verdict(mode, results, totals)[0] + + finished = {"plan": "success", "measure": "success", "report": "success"} + self.assertTrue(passed("commits", self.clean, **finished)) + self.assertTrue(passed("noise", self.clean, **finished)) + self.assertTrue(passed("unchanged", plan="success", measure="skipped", report="skipped")) + for mode, change in (("commits", {"plan": "failure"}), ("", {}), ("commits", {"measure": "failure"}), + ("commits", {"measure": "cancelled"}), ("noise", {"measure": "skipped"}), + ("commits", {"report": "failure"}), ("commits", {"report": "skipped"})): + self.assertFalse(passed(mode, self.clean, **{**finished, **change}), (mode, change)) + self.assertFalse(passed("commits", None, **finished)) + self.assertFalse(passed("commits", {**self.clean, "regressions": 1}, **finished)) + self.assertFalse(passed("commits", {**self.clean, "unverified": 1}, **finished)) + self.assertIn("2 cell(s)", verdict("commits", finished, {**self.clean, "regressions": 2})[1]) + + def test_the_verdict_step_fails_the_run_unless_the_report_handed_on_clean_counts(self): + settle = run_path(SCRIPT)["settle"] + environment = {"PLAN": "success", "MODE": "commits", "MEASURE": "success", "REPORT": "success", + "REGRESSIONS": "0", "UNVERIFIED": "0", "GITHUB_STEP_SUMMARY": ""} + with patch.dict("os.environ", environment): + settle() + for change in ({"REGRESSIONS": "2"}, {"UNVERIFIED": "1"}, {"REGRESSIONS": ""}, {"REPORT": "failure"}): + with patch.dict("os.environ", change): + with self.assertRaises(SystemExit): + settle() if __name__ == "__main__": From 89a9773c2c1c98a4c3ac1a650be8594692586407 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Tue, 1 Dec 2026 14:11:53 +1100 Subject: [PATCH 38/50] Record each night's jobs and verdict in MLflow The night's results lived in artifacts that expire, and comparing nights meant downloading them. A record job now writes each lane's job and the night's verdict to an MLflow experiment, where they can be charted over commits. A job is a job run with a top-level run per arm and that arm's per-round detail beneath it, verified when its evidence checks held. Tonight's commit is `main`: the current run of its machine type and model, and a point on their trend. The commit it was compared with is `baseline` and llama.cpp at an older pin `baseline-reference`, so two commits of one line never share a role, and neither is ever current or on a trend. The night is a run with the report's counts, each cell as a ratio of the baseline, the log as its description and the record attached. Only the record job holds the tracking credentials, in its own environment, and it runs no measured code. This repository's logs are public, so it prints neither the server nor the experiment and masks the server's name. Recording is required for the night to pass. --- .agents/skills/manage-ci/SKILL.md | 6 +- .../inference-performance-nightly.test.cjs | 14 + .../inference-performance-nightly.yml | 58 ++- ci/INFERENCE_PERFORMANCE.md | 34 +- ci/automation.just | 4 + ci/inference-record-requirements.txt | 2 + scripts/inference-performance-nightly.py | 2 +- scripts/inference-performance-record.py | 157 ++++++++ scripts/lib/performance_nightly.py | 6 +- scripts/lib/performance_record.py | 375 ++++++++++++++++++ .../tests/inference_performance_nightly.py | 304 +++++++++++++- 11 files changed, 941 insertions(+), 21 deletions(-) create mode 100644 ci/inference-record-requirements.txt create mode 100644 scripts/inference-performance-record.py create mode 100644 scripts/lib/performance_record.py diff --git a/.agents/skills/manage-ci/SKILL.md b/.agents/skills/manage-ci/SKILL.md index 9ab5cb69..72d6563f 100644 --- a/.agents/skills/manage-ci/SKILL.md +++ b/.agents/skills/manage-ci/SKILL.md @@ -153,7 +153,11 @@ contract; no downstream product's workflow topology applies here. fails for an unfinished lane, evidence that did not hold, or a Skippy regression whose rounds do not overlap the baseline's; a regression llama.cpp's own server shares after a pin move is reported as llama.cpp's. - Never report an unmeasured cell as a regression. + Never report an unmeasured cell as a regression. Its record job alone holds + the MLflow tracking credentials, in the `inference-records` environment, and + runs no candidate or measured code. Recording is required for the night's + success. This repository's logs are public: never print the tracking + server, the experiment or a run's address. - The protected inference results-comment job alone receives pull-requests write permission for PR comments, plus read-only contents/actions. It receives no native dispatch credential and never executes candidate code. diff --git a/.github/scripts/inference-performance-nightly.test.cjs b/.github/scripts/inference-performance-nightly.test.cjs index 322cf620..10cace1c 100644 --- a/.github/scripts/inference-performance-nightly.test.cjs +++ b/.github/scripts/inference-performance-nightly.test.cjs @@ -36,6 +36,20 @@ test('the report runs after a failed lane, over the evidence of every attempt, a assert.ok(!report.includes('secrets.')); }); +test('only the recording job holds the tracking credentials, in its own environment', () => { + const record = job('record'); + assert.ok(record.includes('environment: inference-records')); + assert.ok(record.includes("if: always() && !cancelled() && needs.report.result == 'success'")); + for (const name of ['TRACKING_URI', 'TRACKING_USERNAME', 'TRACKING_PASSWORD', 'EXPERIMENT']) { + assert.ok(record.includes(`secrets.SKIPPY_MLFLOW_${name}`), name); + } + assert.ok(record.includes('::add-mask::')); + assert.ok(!record.includes('JIANYANG_INFERENCE_SSH_KEY')); + for (const name of ['plan', 'measure', 'report', 'verdict']) { + assert.ok(!job(name).includes('MLFLOW'), name); + } +}); + test('the verdict runs after a failed lane and reads every job it depends on', () => { const verdict = job('verdict'); assert.ok(verdict.includes("if: always() && needs.plan.result != 'skipped'")); diff --git a/.github/workflows/inference-performance-nightly.yml b/.github/workflows/inference-performance-nightly.yml index b4870a25..a3369cc9 100644 --- a/.github/workflows/inference-performance-nightly.yml +++ b/.github/workflows/inference-performance-nightly.yml @@ -1,8 +1,9 @@ name: Inference performance (nightly) on: schedule: - # 04:37 in Sydney during daylight saving, after the qualification nightly has had the lab. - - cron: '37 17 * * *' + # 22:07 in Sydney during daylight saving: after the working day, and ahead of the 14:00 UTC + # nightlies and the 17:00 UTC release, which then queue behind a lane instead of delaying it. + - cron: '7 11 * * *' workflow_dispatch: inputs: rebaseline: @@ -108,9 +109,59 @@ jobs: path: ${{ env.EVIDENCE }}/nightly if-no-files-found: error retention-days: 90 + record: + name: Record the night in MLflow + needs: [plan, measure, report] + # After a failed lane or a regression too: what was measured is recorded with its verdict. + if: always() && !cancelled() && needs.report.result == 'success' + # The only job that holds the tracking server's credentials; it runs no measured code. + environment: inference-records + runs-on: ${{ vars.SKIPPY_DEPOT_RUNNERS_ENABLED == 'true' && 'depot-ubuntu-24.04-4' || 'ubuntu-24.04' }} + timeout-minutes: 30 + permissions: + contents: read + actions: read + env: + EVIDENCE: target/ci-evidence/inference-performance-nightly + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 + with: + ref: ${{ github.sha }} + persist-credentials: false + - uses: ./.github/actions/setup + with: + cache: 'false' + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c + # A night on which no lane uploaded evidence still records its verdict. + continue-on-error: true + with: + pattern: inference-performance-*-${{ github.run_id }}-* + path: ${{ env.EVIDENCE }} + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c + with: + name: nightly-inference-performance-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ env.EVIDENCE }}/nightly + - name: Prepare the recording client + run: | + python3 -m venv "$RUNNER_TEMP/inference-record" + "$RUNNER_TEMP/inference-record/bin/python" -m pip install --requirement ci/inference-record-requirements.txt + - name: Record every job and the night's verdict + env: + MLFLOW_TRACKING_URI: ${{ secrets.SKIPPY_MLFLOW_TRACKING_URI }} + MLFLOW_TRACKING_USERNAME: ${{ secrets.SKIPPY_MLFLOW_TRACKING_USERNAME }} + MLFLOW_TRACKING_PASSWORD: ${{ secrets.SKIPPY_MLFLOW_TRACKING_PASSWORD }} + MLFLOW_EXPERIMENT_NAME: ${{ secrets.SKIPPY_MLFLOW_EXPERIMENT }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + # This log is public: a secret is masked as written, so the server's bare name is masked too. + host=${MLFLOW_TRACKING_URI#*://} + host=${host%%/*} + if [[ -n "$host" ]]; then echo "::add-mask::$host"; fi + SKIPPY_PYTHON="$RUNNER_TEMP/inference-record/bin/python" \ + just inference-performance-record "$EVIDENCE" verdict: name: Nightly performance verdict - needs: [plan, measure, report] + needs: [plan, measure, report, record] if: always() && needs.plan.result != 'skipped' runs-on: ${{ vars.SKIPPY_DEPOT_RUNNERS_ENABLED == 'true' && 'depot-ubuntu-24.04-4' || 'ubuntu-24.04' }} timeout-minutes: 5 @@ -128,6 +179,7 @@ jobs: MODE: ${{ needs.plan.outputs.mode }} MEASURE: ${{ needs.measure.result }} REPORT: ${{ needs.report.result }} + RECORD: ${{ needs.record.result }} REGRESSIONS: ${{ needs.report.outputs.regressions }} UNVERIFIED: ${{ needs.report.outputs.unverified }} run: just inference-performance-nightly-verdict diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index dc94c604..0e72cadb 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -64,9 +64,37 @@ when the pin moved and `llama-server` lost as much at that cell, to within the t otherwise it is Skippy's. A cell an arm did not measure is never a regression. The night's log is the run summary and the `nightly-inference-performance-RUN-ATTEMPT` -artifact, kept 90 days: `nightly.md`, and `nightly.json` with every lane's checks and cells. The -`verdict` job then fails the run when a lane did not finish, a lane's checks did not hold, or -Skippy regressed in any cell. An accepted regression is cleared with a `rebaseline` dispatch. +artifact, kept 90 days: `nightly.md`, and `nightly.json` with every lane's checks and cells. + +The `record` job then records the night in MLflow. It is the only job that holds the tracking +credentials, the `inference-records` environment's `SKIPPY_MLFLOW_TRACKING_URI`, +`SKIPPY_MLFLOW_TRACKING_USERNAME`, `SKIPPY_MLFLOW_TRACKING_PASSWORD` and +`SKIPPY_MLFLOW_EXPERIMENT` secrets, and it runs no measured code. It uses the client pinned in +`ci/inference-record-requirements.txt`. This repository's logs are public, so it prints +neither the server nor the experiment nor a run's address, and masks the server's name. + +- Each lane's job is a job run with a top-level run per arm and that arm's per-round detail + beneath it: verified when its checks held, awaiting audit otherwise. Every arm's run carries + `params.machine_type` and `params.model`, the tag `arm.role`, and its medians as + `/`; a Skippy arm also carries each as a ratio of `llama-server`'s in the same + job, `_vs_llama/`. +- Tonight's commit has the role `main`: it becomes the current run of its machine type and + model, and adds a point to their trend at the time of its commit. So does `llama-server` at + its pin, as `reference`. +- The commit it was compared with is `baseline`, or `noise` when it is tonight's own commit + on an A/A night, and `llama-server` at an older pin is `baseline-reference`. None of them + is ever current or on a trend, so two commits of one line never share a role. +- The night is a run tagged `eval.phase = nightly`, with the report's counts, each compared + cell as `vs_previous/LANE/FIELD/POINT` (above 1 is better, so latencies are inverted; + `spread/...` on an A/A night), the log as its description and `nightly.json` attached. + +A job already recorded is left as it is, so rerunning the `record` job records only what is +missing. A run that an earlier attempt left unfinished stops the recording until it has been +looked at. A traced lane's spans stay in its evidence artifact; they are not recorded yet. + +The `verdict` job then fails the run when a lane did not finish, a lane's checks did not hold, +Skippy regressed in any cell, or the night was not recorded. An accepted regression is cleared +with a `rebaseline` dispatch. ## Backends diff --git a/ci/automation.just b/ci/automation.just index 4dbee7a1..b73a5aba 100644 --- a/ci/automation.just +++ b/ci/automation.just @@ -25,6 +25,10 @@ inference-performance-nightly-plan: inference-performance-nightly-report evidence: @"{{ automation_python }}" scripts/inference-performance-nightly.py report "$@" +[positional-arguments] +inference-performance-record evidence: + @"{{ automation_python }}" scripts/inference-performance-record.py "$@" + inference-performance-nightly-verdict: @"{{ automation_python }}" scripts/inference-performance-nightly.py verdict diff --git a/ci/inference-record-requirements.txt b/ci/inference-record-requirements.txt new file mode 100644 index 00000000..a8929f2a --- /dev/null +++ b/ci/inference-record-requirements.txt @@ -0,0 +1,2 @@ +# The tracking server's own MLflow version: a client ahead of it can send what the server refuses. +mlflow==3.17.1 diff --git a/scripts/inference-performance-nightly.py b/scripts/inference-performance-nightly.py index 32c63be6..e3dc0e42 100644 --- a/scripts/inference-performance-nightly.py +++ b/scripts/inference-performance-nightly.py @@ -79,7 +79,7 @@ def counts(): def settle(): - results = {name: os.environ.get(name.upper()) for name in ("plan", "measure", "report")} + results = {name: os.environ.get(name.upper()) for name in ("plan", "measure", "report", "record")} passed, sentence = verdict(os.environ.get("MODE"), results, counts()) summarized(sentence + "\n") if not passed: diff --git a/scripts/inference-performance-record.py b/scripts/inference-performance-record.py new file mode 100644 index 00000000..3741b357 --- /dev/null +++ b/scripts/inference-performance-record.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python3 +"""Record a night's performance jobs and its verdict in MLflow. + +Credentials come from MLFLOW_TRACKING_URI, MLFLOW_TRACKING_USERNAME and MLFLOW_TRACKING_PASSWORD, +and the experiment's name from MLFLOW_EXPERIMENT_NAME. This repository's logs are public, so +nothing here prints the server, the experiment or a run's address, and an error is printed +without them. +""" + +import argparse +import os +import sys +import tempfile +import traceback +from pathlib import Path +from urllib.parse import urlsplit + +from lib.ci_artifacts import read_json +from lib.performance_nightly import evidence, lanes +from lib.performance_record import Run, record_job, record_night, sha256 + +REQUIRED = ("MLFLOW_TRACKING_URI", "MLFLOW_TRACKING_USERNAME", "MLFLOW_TRACKING_PASSWORD", + "MLFLOW_EXPERIMENT_NAME") +# MLflow takes at most 100 parameters or tags and 1,000 entries in one batch. +SMALL_BATCH, METRIC_BATCH = 100, 900 + + +def batches(items, size): + return [items[index:index + size] for index in range(0, len(items), size)] + + +def where(params, tags, without): + """An MLflow run filter: these parameters and tags, and none of the tags in `without`.""" + def quoted(value): + if type(value) is not str or "'" in value: + raise ValueError("a search value is text without a quote") + return f"'{value}'" + + return " and ".join([*(f"params.{name} = {quoted(value)}" for name, value in params.items()), + *(f"tags.`{name}` = {quoted(value)}" for name, value in tags.items()), + *(f"tags.`{name}` != {quoted(value)}" for name, value in (without or {}).items())]) + + +class Experiment: + """One MLflow experiment, as the calls the recorder makes.""" + + def __init__(self): + missing = [name for name in REQUIRED if not os.environ.get(name)] + if missing: + raise ValueError(f'not set: {", ".join(missing)}') + # a server that does not answer fails the recording; it never hangs the job + os.environ.setdefault("MLFLOW_HTTP_REQUEST_TIMEOUT", "60") + os.environ.setdefault("MLFLOW_HTTP_REQUEST_MAX_RETRIES", "2") + import mlflow + from mlflow.entities import Metric, Param, RunTag + from mlflow.tracking import MlflowClient + self.artifacts, self.entities = mlflow.artifacts, (Metric, Param, RunTag) + self.client = MlflowClient() + found = self.client.get_experiment_by_name(os.environ["MLFLOW_EXPERIMENT_NAME"]) + if found is None: + raise ValueError("the experiment does not exist, or this account cannot see it") + self.experiment = found.experiment_id + + @staticmethod + def run(found): + return Run(found.info.run_id, found.info.status, dict(found.data.tags), dict(found.data.params), + dict(found.data.metrics)) + + def find(self, key): + runs = self.client.search_runs([self.experiment], filter_string=where({}, {"eval.key": key}, None), + max_results=2) + return self.run(runs[0]) if runs else None + + def get(self, run_id): + return self.run(self.client.get_run(run_id)) + + def search(self, params, tags, without=None): + return [self.run(found) for found in self.client.search_runs( + [self.experiment], filter_string=where(params, tags, without), max_results=500)] + + def create(self, name, tags): + return self.client.create_run(self.experiment, run_name=name, tags=tags).info.run_id + + def log(self, run_id, metrics=(), params=None, tags=None): + metric, param, tag = self.entities + for chunk in batches([param(name, value) for name, value in (params or {}).items()], SMALL_BATCH): + self.client.log_batch(run_id, params=chunk) + for chunk in batches([tag(name, value) for name, value in (tags or {}).items()], SMALL_BATCH): + self.client.log_batch(run_id, tags=chunk) + for chunk in batches([metric(*entry) for entry in metrics], METRIC_BATCH): + self.client.log_batch(run_id, metrics=chunk) + + def finish(self, run_id): + self.client.set_terminated(run_id, "FINISHED") + + def attach(self, run_id, path): + if path.is_dir(): + self.client.log_artifacts(run_id, str(path), artifact_path=path.name) + else: + self.client.log_artifact(run_id, str(path)) + + def artifact_sha256(self, run_id, name): + with tempfile.TemporaryDirectory() as scratch: + return sha256(self.artifacts.download_artifacts(run_id=run_id, artifact_path=name, dst_path=scratch)) + + def link(self, run_id): + return f'{os.environ["MLFLOW_TRACKING_URI"].rstrip("/")}/#/experiments/{self.experiment}/runs/{run_id}' + + +def record(root): + """Every lane's finished job, then the night. A job whose evidence checks held is recorded as + verified; any other stays awaiting audit. A job already recorded is left as it is, so a + rerun records only what is missing.""" + report = read_json(root / "nightly/nightly.json") + log = (root / "nightly/nightly.md").read_text(encoding="utf-8") + run = {"url": os.environ["RUN_URL"], "id": os.environ["GITHUB_RUN_ID"], + "attempt": os.environ["GITHUB_RUN_ATTEMPT"]} + found = evidence(root, lanes(), run["id"]) + tracking = Experiment() + jobs = {} + for lane in report["lanes"]: + directory = found.get(lane["id"]) + label = (read_json(directory / "plan.json")["jobs"][0]["label"] + if directory is not None and lane["job"] is not None else None) + if label is None or not (directory / f"{label}-rows.jsonl").is_file(): + print(f'{lane["id"]}: no finished job to record') + continue + standing = "unaudited" if lane["checks"] else "verified" + ids = record_job(tracking, directory, label, lane["job"], standing, + extra={"eval.trigger": "nightly", "ci.run": run["url"]}) + jobs[lane["id"]] = ids["job"] + print(f'{lane["id"]}: {lane["job"]} recorded as {standing}, {len(ids["arms"])} arms') + record_night(tracking, report, log, [root / "nightly/nightly.json", root / "nightly/nightly.md"], run, jobs) + print("the night is recorded") + + +def redacted(text): + """`text` without the tracking server, its experiment or its account, for a public log.""" + uri = os.environ.get("MLFLOW_TRACKING_URI", "") + for private in (uri.rstrip("/"), urlsplit(uri).hostname, os.environ.get("MLFLOW_EXPERIMENT_NAME"), + os.environ.get("MLFLOW_TRACKING_USERNAME")): + if private: + text = text.replace(private, "[withheld]") + return text + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("evidence", type=Path) + record(parser.parse_args().evidence) + + +if __name__ == "__main__": + try: + main() + except Exception as error: # MLflow and its HTTP client raise types of their own + sys.exit(redacted("".join(traceback.format_exception(error)))) diff --git a/scripts/lib/performance_nightly.py b/scripts/lib/performance_nightly.py index 9efe0df0..d49fe871 100644 --- a/scripts/lib/performance_nightly.py +++ b/scripts/lib/performance_nightly.py @@ -238,8 +238,8 @@ def markdown(report): def verdict(mode, results, totals=None): """(passed, sentence) for the night, from each workflow job's result by name and the report's counts. A night that measured nothing because main has not moved passes. A lane that did not - finish, evidence that did not hold and a regression in Skippy each fail it, so the baseline - stays at the last commit that passed.""" + finish, evidence that did not hold, a regression in Skippy and a night left unrecorded each + fail it, so the baseline stays at the last commit that passed and was recorded.""" if results.get("plan") != "success" or mode not in MODES: return False, "The nightly plan did not succeed." if mode == "unchanged": @@ -252,6 +252,8 @@ def verdict(mode, results, totals=None): return False, f'The evidence checks did not hold on {totals["unverified"]} lane(s).' if totals["regressions"]: return False, f'Skippy regressed at {totals["regressions"]} cell(s) since the last successful nightly.' + if results.get("record") != "success": + return False, "The night was measured but not recorded." if mode == "noise": return True, "The A/A run finished; the next nightly compares with this commit." return True, "No regression in Skippy since the last successful nightly." diff --git a/scripts/lib/performance_record.py b/scripts/lib/performance_record.py new file mode 100644 index 00000000..fac61f03 --- /dev/null +++ b/scripts/lib/performance_record.py @@ -0,0 +1,375 @@ +"""Record a performance job and a night's verdict in an MLflow experiment, and read them back. + +The view the runs make: every arm's run carries `params.machine_type` and `params.model`, the tag +`arm.role`, and `view.current` on the newest run of its machine type, model and role. Headline +metrics are named `/`, the same on every kind of run, so one chart compares them. + +`tracking` is the experiment, as nine calls. `find(key)` returns the `Run` whose `eval.key` tag is +`key`, or None; `get(run_id)` a `Run`; `search(params, tags, without=None)` the `Run`s with those +parameters and tags and none of the tags in `without`. `create(name, tags)` returns a new run's id. +`log(run_id, metrics=(), params=None, tags=None)` takes metrics as (key, value, time in ms, step); +`finish(run_id)` ends a run; `attach(run_id, path)` stores a file or a directory under its name; +`artifact_sha256(run_id, name)` hashes a stored file; `link(run_id)` is the run's address. The +script that owns the MLflow client supplies it; tests supply one in memory. +""" + +import hashlib +import json +import math +import statistics +import time +from collections import defaultdict +from dataclasses import dataclass +from datetime import datetime +from pathlib import Path + +from .performance_load import METRICS +from .performance_report import HEADLINE + +PROGRAM = "inference-baselines" +HOST_FIELDS = ("node", "backend", "gpu", "chip", "os", "os_version", "macos", "kernel", "driver_version", + "toolkit_version", "metal_working_set_bytes") +STANDINGS = {"verified": "verified", "unaudited": "completed, awaiting audit", "diagnostic": "diagnostic"} +# The roles whose newest run is the view's current one, and those that gain a point on a trend. +CURRENT = ("main", "reference", "branch") +TRENDED = ("main", "reference") +ON_MAIN = (True, "true", "True") +# MLflow keeps a run's description as a tag, and a tag holds a few thousand characters at most. +NOTE_LIMIT = 4500 + + +@dataclass(frozen=True) +class Run: + """A recorded run as the recorder reads it back.""" + run_id: str + status: str + tags: dict + params: dict + metrics: dict + + +def sha256(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def short(sha): + return (sha or "")[:12] + + +def numeric(value): + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def epoch_ms(text): + try: + return int(datetime.fromisoformat(str(text).replace("Z", "+00:00")).timestamp() * 1000) + except ValueError: + return None + + +def machine_type(row): + backend = row.get("backend") or ("metal" if row.get("chip") else "unknown") + return f'{backend}:{row.get("gpu") or row.get("chip") or "unknown"}' + + +def start_run(tracking, key, name, description, tags, parent=None): + """A new run's id, or None when `key` is already recorded. A run left unfinished by an earlier + attempt stops the recording: it is inspected, never written over.""" + found = tracking.find(key) + if found is not None: + if found.status == "FINISHED": + return None + raise RuntimeError(f"{name} exists as {found.run_id} with status {found.status}; " + "inspect it before recording again") + every = {"eval.key": key, "eval.program": PROGRAM, "mlflow.note.content": description, **tags} + if parent: + every["mlflow.parentRunId"] = parent + return tracking.create(name, every) + + +def read_back(tracking, run_id, artifact, expected): + """The run as the server holds it must be finished, with the metrics just written and, for + `artifact`, the same bytes.""" + run = tracking.get(run_id) + wrong = [key for key, value in expected.items() if run.metrics.get(key) != value] + if run.status != "FINISHED" or wrong: + raise RuntimeError(f"read-back of {run_id} failed: status {run.status}, metrics differing: {wrong[:5]}") + if artifact is not None and tracking.artifact_sha256(run_id, Path(artifact).name) != sha256(artifact): + raise RuntimeError(f"artifact {Path(artifact).name} on {run_id} differs from the local copy") + + +def role_of(rows, candidate, line): + """An arm's role in the view, from its first row. + + The candidate is the tracked line, `main`, when it is on main or the job measured the named + `line`; otherwise it is a `branch`. `reference` is llama.cpp at the candidate's pin. Another + Skippy arm at the candidate's commit is its A/A copy, `noise`. Beside a candidate that is the + tracked line, the other commit is the `baseline` it is compared with and llama.cpp at that + commit's pin is `baseline-reference`: neither is ever current or on a trend, so two commits + of one line never share a role. Beside a branch, the arm on main is `main`, as it always was.""" + first = rows[0] + if first["kind"] == "llama-server": + return "baseline-reference" if first["arm"] == "baseline-reference" else "reference" + tracked = bool(line) or candidate.get("on_main") in ON_MAIN + if first["arm"] == "candidate": + return "main" if tracked else "branch" + if first["sha"] == candidate["sha"]: + return "noise" + if tracked: + return "baseline" + return "main" if first.get("on_main") in ON_MAIN else "branch" + + +def role_label(role, rows, line): + first, tracked = rows[0], f'Skippy {line or "main"}' + if role == "branch": + return f'Skippy PR #{first.get("pull_request") or "?"}' + if role == "baseline": + own = first.get("branch") or ("main" if first.get("on_main") in ON_MAIN + else f'PR #{first.get("pull_request") or "?"}') + return f"Skippy {own} (baseline)" + return {"reference": "llama-server", "baseline-reference": "llama-server (baseline pin)", "main": tracked, + "noise": f"{tracked} (A/A copy)"}[role] + + +def cell_metrics(rows, now): + """Every measured field per round under detail/, as (key, value, time, step), and each cell's + median, minimum and maximum.""" + per_round, series = [], defaultdict(list) + for row in rows: + for field in METRICS: + if numeric(row.get(field)): + key = f'detail/{row["server"]}/{row["point"]}/{field}' + series[key].append(row[field]) + per_round.append((key, float(row[field]), now, int(row["round"]))) + medians = {} + for key, values in series.items(): + medians[f"{key}/median"] = float(statistics.median(values)) + medians[f"{key}/min"] = float(min(values)) + medians[f"{key}/max"] = float(max(values)) + return per_round, medians + + +def headline(medians, yardstick=None): + """The view's metrics, named / so a chart view puts each field in its own section + and every kind of run lands in the same chart. With `yardstick`, llama-server's medians in the + same job, a Skippy arm also carries its median as a ratio of llama-server's.""" + result = {} + for key, value in medians.items(): + parts = key.split("/") + if len(parts) != 5 or parts[4] != "median" or parts[3] not in HEADLINE: + continue + result[f"{parts[3]}/{parts[2]}"] = value + reference = (yardstick or {}).get(key) + if reference: + result[f"{parts[3]}_vs_llama/{parts[2]}"] = value / reference + return result + + +def promote(tracking, run_id, machine, model, role, when_ms, pull_request=""): + """Mark this run the current one of its machine type, model and role, unless a newer one already is.""" + params = {"machine_type": machine, "model": model} + if role == "branch": + params["pull_request"] = pull_request + others = [run for run in tracking.search(params, {"arm.role": role, "view.current": "true"}) + if run.run_id != run_id] + newer = [run for run in others if int(run.tags.get("view.when_ms", "0")) > when_ms] + tracking.log(run_id, tags={"view.when_ms": str(when_ms), "view.current": "false" if newer else "true"}) + for run in [] if newer else others: + tracking.log(run.run_id, tags={"view.current": "false"}) + + +def append_trend(tracking, machine, model, role, label, job_id, sha, when_ms, values): + """One long-lived run per machine type, model and role, gaining a point per job at its commit's time.""" + key = f"trend:{machine}:{model}:{role}" + found = tracking.find(key) + if found is not None and f"trend.job.{job_id}" in found.tags: + return + if found is None: + run_id = tracking.create(f"trend · {label} · {model} · {machine}", { + "eval.key": key, "eval.program": PROGRAM, "eval.phase": "trend", "arm.role": role, "view.trend": "true", + "mlflow.note.content": f"{label} for {model} on {machine}: one point per recorded job, placed at the " + "time of the Skippy commit it measured. Plot a metric against time to see " + "progress."}) + tracking.log(run_id, params={"machine_type": machine, "model": model}) + else: + run_id = found.run_id + tracking.log(run_id, metrics=[(name, float(value), when_ms, when_ms // 1000) for name, value in values.items()], + tags={f"trend.job.{job_id}": sha}) + tracking.finish(run_id) + + +def link_ceiling(tracking, machine, model): + """Each current run's throughput as a fraction of the current ceiling for its machine type and model.""" + params, current = {"machine_type": machine, "model": model}, {"view.current": "true"} + ceilings = tracking.search(params, {**current, "arm.role": "ceiling"}) + if not ceilings: + return + ceiling, now = ceilings[0].metrics, int(time.time() * 1000) + for run in tracking.search(params, current, without={"arm.role": "ceiling"}): + tracking.log(run.run_id, metrics=[ + (key.replace("output_tok_s/", "output_tok_s_of_ceiling/"), run.metrics[key] / value, now, 0) + for key, value in ceiling.items() + if key.startswith("output_tok_s/") and value and run.metrics.get(key)]) + + +def recorded(tracking, job_id, arms): + """The runs an earlier recording of this job made, by the keys it gave them.""" + found = {arm: tracking.find(f"job:{job_id}:{arm}") for arm in arms} + return {"job": tracking.find(f"job:{job_id}").run_id, + "arms": {arm: run.run_id for arm, run in found.items() if run is not None}} + + +def record_job(tracking, evidence, label, job_id, standing, line=None, extra=None): + """One job's rows as a job run, a top-level run per arm and each arm's per-round detail beneath it; + returns their ids as {"job": id, "arms": {arm: id}}. `label` names the job's files in `evidence`, + and `extra` is tags for every run. A job already recorded is left as it is. + + A diagnostic job reruns part of the scenario to look inside it: it is recorded but stays out of + the view's current and trend runs, which a partial job would otherwise replace.""" + evidence, extra = Path(evidence), extra or {} + rows_file = evidence / f"{label}-rows.jsonl" + rows = [json.loads(text) for text in rows_file.read_text(encoding="utf-8").splitlines() if text.strip()] + if not rows: + raise ValueError(f"{rows_file} has no rows") + first = rows[0] + by_arm = defaultdict(list) + for row in rows: + by_arm[row["arm"]].append(row) + models = sorted({row["model"] for row in rows}) + node = first.get("node") or "unknown" + device = first.get("gpu") or first.get("chip") or "unknown" + state, diagnostic = STANDINGS[standing], standing == "diagnostic" + phase = "diagnostic" if diagnostic else "campaign" + parent = start_run( + tracking, f"job:{job_id}", f'{", ".join(models)} · {device} · {node} · {job_id}', + f'JY job {job_id}: Skippy against llama.cpp\'s llama-server on {device} ({node}), models {", ".join(models)}. ' + "Each arm is a top-level run tagged eval.job_run with this run's id; metrics are per server/point, logged " + "per round, with median, min and max. " + "Skippy arms also carry their median as a ratio of llama-server's in the same job and cell (vs_llama).", + {"eval.phase": phase, "eval.execution_state": "completed", "eval.verification_state": state, + "jy.job_id": job_id, "hardware.node": node, "hardware.device": device, **extra}) + if parent is None: + return recorded(tracking, job_id, by_arm) + now = int(time.time() * 1000) + machine = machine_type(first) + tracking.log(parent, params={ + **{f"host.{field}": str(first[field]) for field in HOST_FIELDS if first.get(field) is not None}, + "harness": first["harness"], "scenario_sha256": first["scenario_sha256"], "models": ",".join(models), + "machine_type": machine, + "model_revisions": ",".join(sorted({f'{row["model"]}@{row["model_revision"]}' for row in rows}))}) + for name in (f"{label}-performance.json", rows_file.name, "plan.json", "summary.md", f"{job_id}-job.json", + f"{label}-aiperf.tar.gz", f"{label}-logs"): + if (evidence / name).exists(): + tracking.attach(parent, evidence / name) + + model = models[0] if len(models) == 1 else None + viewed = model is not None and not diagnostic + candidate = by_arm.get("candidate", rows)[0] + if line and candidate.get("branch") and candidate["branch"] != line: + raise ValueError(f'the tracked line is {line} but the candidate was measured from branch {candidate["branch"]}') + line = line or candidate.get("branch") + when_ms = epoch_ms(candidate.get("committed_at")) or epoch_ms(first.get("started_at")) or now + computed = {arm: cell_metrics(arm_rows, now) for arm, arm_rows in by_arm.items()} + arms = {} + for arm, arm_rows in sorted(by_arm.items()): + per_round, medians = computed[arm] + head = arm_rows[0] + if diagnostic and head["kind"] == "skippy": + role, title = "diagnostic", f'Skippy {head.get("branch") or short(head["sha"])}' + else: + role = role_of(arm_rows, candidate, line) + title = role_label(role, arm_rows, line) + # a baseline is measured against llama.cpp at its own pin when the job ran it, else at the candidate's + beside = "baseline-reference" if role == "baseline" and "baseline-reference" in computed else "reference" + view = headline(medians, computed.get(beside, (None, {}))[1] if head["kind"] == "skippy" else None) + child = start_run( + tracking, f"job:{job_id}:{arm}", f'{title} · {", ".join(models)} · {short(head["sha"])}', + f'Arm {arm} of JY job {job_id}: {head["kind"]} at {head["sha"]}, on {device} ({node}). ' + "Headline metrics are / medians; detail/ holds every field per round.", + {"eval.phase": phase, "eval.execution_state": "completed", "eval.verification_state": state, + "jy.job_id": job_id, "hardware.node": node, "hardware.device": device, "arm.kind": head["kind"], + "arm.label": arm, "arm.role": role, "eval.job_run": parent, **extra}) + if child is None: + arms[arm] = tracking.find(f"job:{job_id}:{arm}").run_id + continue + arms[arm] = child + params = {"sha": head["sha"], "kind": head["kind"], "binary_sha256": head.get("binary_sha256") or "", + "on_main": str(head.get("on_main")), "pull_request": str(head.get("pull_request") or ""), + "machine_type": machine, "model": ",".join(models), "skippy_line": line or "main"} + tracking.log(child, metrics=[(key, value, now, 0) for key, value in view.items()], params=params) + # Per-round detail sits one level down, so the chart view of the headline runs is not hundreds of charts. + detail = start_run(tracking, f"job:{job_id}:{arm}:detail", f'detail · {title} · {short(head["sha"])}', + f"Every measured field of arm {arm} in JY job {job_id}, per round (step), with median, " + "minimum and maximum.", {"eval.phase": phase, "jy.job_id": job_id, "arm.label": arm}, + child) + if detail is not None: + tracking.log(detail, metrics=per_round + [(key, value, now, 0) for key, value in medians.items()], + params=params) + tracking.finish(detail) + read_back(tracking, detail, None, dict(list(medians.items())[:20])) + tracking.finish(child) + read_back(tracking, child, None, dict(list(view.items())[:20])) + if viewed and role in CURRENT: + promote(tracking, child, machine, model, role, when_ms, params["pull_request"]) + if viewed and role in TRENDED: + append_trend(tracking, machine, model, role, title, job_id, head["sha"], when_ms, view) + if viewed: + link_ceiling(tracking, machine, model) + tracking.finish(parent) + read_back(tracking, parent, rows_file, {}) + return {"job": parent, "arms": arms} + + +def night_metrics(report, now): + """The night's counts, and each compared cell as `vs_previous///`: tonight's + commit as a ratio of the baseline that reads above 1 when Skippy is better, so latencies are + inverted. On a noise night the two arms are one commit and the same ratio is `spread/...`.""" + family = "spread" if report["mode"] == "noise" else "vs_previous" + metrics = [(name, float(value), now, 0) for name, value in report["totals"].items()] + for lane in report["lanes"]: + for found in lane["cells"]: + baseline, candidate = found["arms"]["baseline"]["median"], found["arms"]["candidate"]["median"] + ratio = candidate / baseline if HEADLINE[found["metric"]] == "higher" else baseline / candidate + metrics.append((f'{family}/{lane["id"]}/{found["metric"]}/{found["point"]}', ratio, now, 0)) + return metrics + + +def night_note(log, links): + """The night's description: its log, then its recorded jobs. A log longer than a description + can hold is cut at a line, and says the whole of it is attached.""" + tail = "\n## Recorded jobs\n\n" + "\n".join(links) + "\n" if links else "" + if len(log) + len(tail) <= NOTE_LIMIT: + return log + tail + cut = "\nThe rest of this log is in the attached nightly.md.\n" + head = log[:max(0, NOTE_LIMIT - len(tail) - len(cut))] + return head[:head.rfind("\n") + 1] + cut + tail + + +def record_night(tracking, report, log, files, run, jobs): + """The night's verdict as a run of its own: its counts and cells as metrics, its log as the + description, and the record and the whole log attached. `run` is the workflow run's url, id + and attempt; `jobs` maps a lane to its job run, which the description links.""" + totals, noise = report["totals"], report["mode"] == "noise" + outcome = "noise" if noise else "regressed" if totals["regressions"] else "clean" + against = "itself" if noise else short(report["baseline"]) + note = night_note(log, [f"- {lane}: {tracking.link(run_id)}" for lane, run_id in sorted(jobs.items())]) + night = start_run( + tracking, f'nightly:{run["id"]}:{run["attempt"]}', f'nightly · Skippy main {short(report["candidate"])} ' + f"against {against}", note, + {"eval.phase": "nightly", "eval.execution_state": "completed", + "eval.verification_state": "requires review" if totals["unverified"] else "verified", + "eval.trigger": "nightly", "nightly.outcome": outcome, "nightly.candidate": report["candidate"], + "nightly.baseline": report["baseline"], "ci.run": run["url"]}) + if night is None: + return tracking.find(f'nightly:{run["id"]}:{run["attempt"]}').run_id + now = int(time.time() * 1000) + metrics = night_metrics(report, now) + tracking.log(night, metrics=metrics, params={ + "candidate": report["candidate"], "baseline": report["baseline"], "mode": report["mode"], + "lanes": ",".join(lane["id"] for lane in report["lanes"])}) + for path in files: + tracking.attach(night, path) + tracking.finish(night) + read_back(tracking, night, files[0], {name: value for name, value, _, _ in metrics[:20]}) + return night diff --git a/scripts/tests/inference_performance_nightly.py b/scripts/tests/inference_performance_nightly.py index 80765920..99e2dcd9 100644 --- a/scripts/tests/inference_performance_nightly.py +++ b/scripts/tests/inference_performance_nightly.py @@ -1,4 +1,5 @@ -"""Offline checks for the nightly performance comparison's lanes, baseline, evidence, regressions and verdict.""" +"""Offline checks for the nightly performance comparison's lanes, baseline, evidence, regressions, verdict +and recording.""" import json import unittest @@ -7,13 +8,16 @@ from tempfile import TemporaryDirectory from unittest.mock import patch -from lib import performance_nightly, performance_plan +from lib import performance_nightly, performance_plan, performance_report from lib.performance_arms import may_reject from lib.performance_audit import audit from lib.performance_nightly import (cells, compared, evidence, lane_report, lanes, markdown, matrix, night, previous, verdict) +from lib.performance_record import NOTE_LIMIT, Run, night_note, record_job, record_night, sha256 SCRIPT = str(Path(__file__).resolve().parents[1] / "inference-performance-nightly.py") +RECORDER = str(Path(__file__).resolve().parents[1] / "inference-performance-record.py") +MACHINE = "metal:Apple M3 Ultra" CANDIDATE, BASELINE, PIN = "a" * 40, "b" * 40, "c" * 40 LANE = {"id": "metal-studio", "backend": "metal", "node": "n1", "model": "qwen35-4b", "servers": None, "trace": False, "rounds": 3} @@ -23,9 +27,9 @@ def shipped(): return performance_plan.read_json(performance_nightly.NIGHTLY) -def admitted(servers=None, trace=False, baseline_reference=None): +def admitted(servers=None, trace=False, baseline_reference=None, baseline=BASELINE): """A plan as `admit` writes it, for one model on the node n1.""" - return {"arms": performance_plan.arms(CANDIDATE, BASELINE, PIN, baseline_reference), "models": ["qwen35-4b"], + return {"arms": performance_plan.arms(CANDIDATE, baseline, PIN, baseline_reference), "models": ["qwen35-4b"], "rounds": 3, "trace": trace, "servers": servers, "jobs": [{"label": "n1"}]} @@ -45,7 +49,10 @@ def measured(plan, rate=None): samples.append({"model": plan["models"][0], "round": index + 1, "arm": arm["label"], "server": server["id"], "point": point["id"], "applied": {}, "unsupported": [], "metrics": dict.fromkeys(metrics) if rejected else metrics, "rejected": rejected}) - record = {"host": {"node": "n1", "chip": "Apple M3 Ultra"}, "samples": samples} + record = {"harness": "d" * 40, "scenario_sha256": "e" * 64, "started_at": "2026-11-30T12:00:00+00:00", + "host": {"node": "n1", "chip": "Apple M3 Ultra", "backend": "metal"}, + "arms": [{**arm, "binary_sha256": "f" * 64} for arm in plan["arms"]], + "models": {plan["models"][0]: {"revision": "r1", "trained_context": 262144}}, "samples": samples} if plan["trace"]: record["diagnostic"] = {"samples": [{"point": point["id"]} for _, point in points]} return record @@ -334,20 +341,294 @@ def test_report_writes_the_nights_record_log_and_counts(self): self.assertEqual(counts, ["regressions=7", "unverified=0"]) +class Memory: + """An experiment in memory, as the calls the recorder makes.""" + + def __init__(self): + self.runs, self.files = {}, {} + + def run(self, run_id): + held = self.runs[run_id] + return Run(run_id, held["status"], dict(held["tags"]), dict(held["params"]), dict(held["metrics"])) + + def find(self, key): + return next((self.run(run_id) for run_id, held in self.runs.items() if held["tags"].get("eval.key") == key), + None) + + def get(self, run_id): + return self.run(run_id) + + def search(self, params, tags, without=None): + return [self.run(run_id) for run_id, held in self.runs.items() + if all(held["params"].get(name) == value for name, value in params.items()) + and all(held["tags"].get(name) == value for name, value in tags.items()) + and all(held["tags"].get(name) != value for name, value in (without or {}).items())] + + def create(self, name, tags): + run_id = f"run{len(self.runs) + 1}" + self.runs[run_id] = {"name": name, "status": "RUNNING", "tags": dict(tags), "params": {}, "metrics": {}} + return run_id + + def log(self, run_id, metrics=(), params=None, tags=None): + held = self.runs[run_id] + held["params"].update(params or {}) + held["tags"].update(tags or {}) + held["metrics"].update({key: value for key, value, _, _ in metrics}) + + def finish(self, run_id): + self.runs[run_id]["status"] = "FINISHED" + + def attach(self, run_id, path): + self.files[(run_id, path.name)] = sha256(path) if path.is_file() else "a directory" + + def artifact_sha256(self, run_id, name): + return self.files[(run_id, name)] + + def link(self, run_id): + return f"link:{run_id}" + + def keyed(self): + """Every run by the key it was recorded under.""" + return {held["tags"]["eval.key"]: held for held in self.runs.values()} + + +def write_job(directory, plan, record, pull_requests=None, branches=None): + """A job's evidence as the controller collects it, under the label n1 and the id job_1.""" + committed = {arm["sha"]: "2026-11-30T10:00:00Z" for arm in plan["arms"]} + rows = performance_report.rows(record, performance_plan.scenario(plan.get("servers")), committed, "job_1", + pull_requests or {}, branches) + (directory / "n1-rows.jsonl").write_text("".join(json.dumps(row, sort_keys=True) + "\n" for row in rows), + encoding="utf-8") + (directory / "n1-performance.json").write_text(json.dumps(record), encoding="utf-8") + (directory / "plan.json").write_text(json.dumps(plan), encoding="utf-8") + (directory / "n1-logs").mkdir() + (directory / "n1-logs/build-candidate.log").write_text("built\n", encoding="utf-8") + + +class RecordTests(unittest.TestCase): + rate = {"candidate": 80.0, "baseline": 100.0, "reference": 160.0, "baseline-reference": 200.0} + cell = "output_tok_s/c4-short" + beside_llama = "output_tok_s_vs_llama/c4-short" + + def recorded(self, plan, standing="verified", **arms): + """The experiment after one job is recorded twice, its runs by key, and the ids it returned.""" + tracking = Memory() + with TemporaryDirectory() as directory: + write_job(Path(directory), plan, measured(plan, rate=self.rate), **arms) + ids = record_job(tracking, Path(directory), "n1", "job_1", standing, extra={"eval.trigger": "nightly"}) + count = len(tracking.runs) + self.assertEqual(record_job(tracking, Path(directory), "n1", "job_1", standing), ids) + self.assertEqual(len(tracking.runs), count) + return tracking, tracking.keyed(), ids + + def test_a_nights_job_records_tonights_commit_as_main_and_the_last_nights_as_its_baseline(self): + tracking, runs, ids = self.recorded(admitted()) + labels = ("candidate", "baseline", "reference") + arm = {label: runs[f"job:job_1:{label}"] for label in labels} + self.assertEqual(sorted(runs), sorted( + ["job:job_1", f"trend:{MACHINE}:qwen35-4b:main", f"trend:{MACHINE}:qwen35-4b:reference"] + + [f"job:job_1:{label}{part}" for label in labels for part in ("", ":detail")])) + self.assertEqual([arm[label]["tags"]["arm.role"] for label in labels], ["main", "baseline", "reference"]) + self.assertEqual([arm[label]["name"] for label in labels], + ["Skippy main · qwen35-4b · " + "a" * 12, "Skippy main (baseline) · qwen35-4b · " + "b" * 12, + "llama-server · qwen35-4b · " + "c" * 12]) + self.assertEqual([arm[label]["tags"].get("view.current") for label in labels], ["true", None, "true"]) + self.assertEqual({held["status"] for held in runs.values()}, {"FINISHED"}) + self.assertEqual(ids, {"job": tracking.find("job:job_1").run_id, + "arms": {label: tracking.find(f"job:job_1:{label}").run_id for label in labels}}) + + self.assertEqual((arm["candidate"]["metrics"][self.cell], arm["reference"]["metrics"][self.cell]), (81.0, 161.0)) + self.assertAlmostEqual(arm["candidate"]["metrics"][self.beside_llama], 81 / 161) + self.assertAlmostEqual(arm["baseline"]["metrics"][self.beside_llama], 101 / 161) + self.assertNotIn(self.beside_llama, arm["reference"]["metrics"]) + # llama-server rejects this point, so it has no figure there and Skippy none beside it + self.assertEqual(arm["candidate"]["metrics"]["output_tok_s/c16-depth4096"], 81.0) + self.assertNotIn("output_tok_s/c16-depth4096", arm["reference"]["metrics"]) + self.assertNotIn("output_tok_s_vs_llama/c16-depth4096", arm["candidate"]["metrics"]) + self.assertEqual(runs["job:job_1:candidate:detail"]["tags"]["mlflow.parentRunId"], ids["arms"]["candidate"]) + self.assertEqual(runs["job:job_1:candidate:detail"]["metrics"]["detail/lanes4/c4-short/output_tok_s/max"], 82.0) + + trend = runs[f"trend:{MACHINE}:qwen35-4b:main"] + self.assertEqual((trend["name"], trend["tags"]["trend.job.job_1"], trend["metrics"][self.cell]), + (f"trend · Skippy main · qwen35-4b · {MACHINE}", CANDIDATE, 81.0)) + self.assertEqual(runs[f"trend:{MACHINE}:qwen35-4b:reference"]["metrics"][self.cell], 161.0) + + job = runs["job:job_1"] + self.assertEqual((job["tags"]["eval.phase"], job["tags"]["eval.verification_state"], job["tags"]["eval.trigger"], + job["params"]["machine_type"], job["params"]["models"]), + ("campaign", "verified", "nightly", MACHINE, "qwen35-4b")) + self.assertEqual(arm["candidate"]["tags"]["eval.job_run"], ids["job"]) + self.assertEqual({name for run_id, name in tracking.files if run_id == ids["job"]}, + {"n1-performance.json", "n1-rows.jsonl", "plan.json", "n1-logs"}) + + def test_a_moved_pin_measures_each_commit_beside_llama_cpp_at_its_own_pin(self): + _, runs, _ = self.recorded(admitted(baseline_reference="d" * 40)) + old = runs["job:job_1:baseline-reference"] + self.assertEqual((old["tags"]["arm.role"], old["name"]), + ("baseline-reference", "llama-server (baseline pin) · qwen35-4b · " + "d" * 12)) + self.assertNotIn("view.current", old["tags"]) + self.assertAlmostEqual(runs["job:job_1:candidate"]["metrics"][self.beside_llama], 81 / 161) + self.assertAlmostEqual(runs["job:job_1:baseline"]["metrics"][self.beside_llama], 101 / 201) + self.assertEqual(runs[f"trend:{MACHINE}:qwen35-4b:reference"]["metrics"][self.cell], 161.0) + + def test_a_copy_of_tonights_commit_is_noise_and_never_current(self): + _, runs, _ = self.recorded(admitted(baseline=CANDIDATE)) + copy = runs["job:job_1:baseline"] + self.assertEqual((copy["tags"]["arm.role"], copy["name"]), + ("noise", "Skippy main (A/A copy) · qwen35-4b · " + "a" * 12)) + self.assertNotIn("view.current", copy["tags"]) + self.assertEqual(runs[f"trend:{MACHINE}:qwen35-4b:main"]["metrics"][self.cell], 81.0) + + def test_a_tracked_branch_is_the_line_and_main_beside_it_is_its_baseline(self): + _, runs, _ = self.recorded(admitted(), branches={"candidate": "gen-ai-semconv"}) + line, beside = runs["job:job_1:candidate"], runs["job:job_1:baseline"] + self.assertEqual((line["tags"]["arm.role"], line["name"], line["params"]["skippy_line"]), + ("main", "Skippy gen-ai-semconv · qwen35-4b · " + "a" * 12, "gen-ai-semconv")) + self.assertEqual((beside["tags"]["arm.role"], beside["name"]), + ("baseline", "Skippy main (baseline) · qwen35-4b · " + "b" * 12)) + # the trend follows the tracked line, not the commit it was compared with + self.assertEqual(runs[f"trend:{MACHINE}:qwen35-4b:main"]["metrics"][self.cell], 81.0) + + def test_beside_a_pull_request_main_keeps_its_own_role(self): + _, runs, _ = self.recorded(admitted(), pull_requests={"candidate": 130}) + head, main = runs["job:job_1:candidate"], runs["job:job_1:baseline"] + self.assertEqual((head["tags"]["arm.role"], head["name"], head["tags"]["view.current"]), + ("branch", "Skippy PR #130 · qwen35-4b · " + "a" * 12, "true")) + self.assertEqual((main["tags"]["arm.role"], main["name"], main["tags"]["view.current"]), + ("main", "Skippy main · qwen35-4b · " + "b" * 12, "true")) + self.assertEqual(runs[f"trend:{MACHINE}:qwen35-4b:main"]["metrics"][self.cell], 101.0) + + def test_an_unchecked_job_awaits_audit_and_a_diagnostic_one_stays_out_of_the_view(self): + _, runs, _ = self.recorded(admitted(), standing="unaudited") + self.assertEqual(runs["job:job_1"]["tags"]["eval.verification_state"], "completed, awaiting audit") + _, runs, _ = self.recorded(admitted(), standing="diagnostic") + self.assertEqual((runs["job:job_1"]["tags"]["eval.phase"], runs["job:job_1:candidate"]["tags"]["arm.role"]), + ("diagnostic", "diagnostic")) + self.assertEqual([key for key in runs if key.startswith("trend:")], []) + self.assertEqual([key for key, held in runs.items() if "view.current" in held["tags"]], []) + + def test_a_run_left_unfinished_stops_the_recording(self): + tracking, plan = Memory(), admitted() + tracking.create("left over", {"eval.key": "job:job_1"}) + with TemporaryDirectory() as directory: + write_job(Path(directory), plan, measured(plan)) + with self.assertRaisesRegex(RuntimeError, "inspect it"): + record_job(tracking, Path(directory), "n1", "job_1", "verified") + + def night_of(self, mode, baseline): + result = measured(admitted(), rate=self.rate) + lane = {**{field: LANE[field] for field in ("id", "backend", "node", "model")}, "job": "job_1", + "host": "Apple M3 Ultra", "checks": [], "cells": cells(result, mode)} + return night(CANDIDATE, baseline, mode, [lane]) + + def test_the_night_is_a_run_with_its_counts_cells_log_and_record(self): + tracking, report = Memory(), self.night_of("commits", BASELINE) + run = {"url": "https://github.example/runs/11", "id": "11", "attempt": "1"} + with TemporaryDirectory() as directory: + files = [Path(directory) / "nightly.json", Path(directory) / "nightly.md"] + files[0].write_text(json.dumps(report), encoding="utf-8") + files[1].write_text(markdown(report), encoding="utf-8") + first = record_night(tracking, report, markdown(report), files, run, {"metal-studio": "run9"}) + self.assertEqual(record_night(tracking, report, markdown(report), files, run, {}), first) + quiet = self.night_of("noise", CANDIDATE) + record_night(tracking, quiet, markdown(quiet), files, {**run, "attempt": "2"}, {}) + runs = tracking.keyed() + held = runs["nightly:11:1"] + self.assertEqual((held["name"], held["status"]), + ("nightly · Skippy main " + "a" * 12 + " against " + "b" * 12, "FINISHED")) + self.assertEqual([held["tags"][name] for name in ("eval.phase", "nightly.outcome", "eval.verification_state", + "nightly.candidate", "nightly.baseline", "ci.run")], + ["nightly", "regressed", "verified", CANDIDATE, BASELINE, run["url"]]) + self.assertEqual((held["metrics"]["regressions"], held["metrics"]["cells"]), (7.0, 21.0)) + self.assertAlmostEqual(held["metrics"]["vs_previous/metal-studio/output_tok_s/c4-short"], 81 / 101) + self.assertEqual(held["metrics"]["vs_previous/metal-studio/ttft_ms_p50/c4-short"], 1.0) + for expected in ("## Regressions", "## Recorded jobs", "- metal-studio: link:run9"): + self.assertIn(expected, held["tags"]["mlflow.note.content"]) + self.assertEqual({name for run_id, name in tracking.files if run_id == first}, {"nightly.json", "nightly.md"}) + noise = runs["nightly:11:2"] + self.assertEqual((noise["name"], noise["tags"]["nightly.outcome"]), + ("nightly · Skippy main " + "a" * 12 + " against itself", "noise")) + self.assertIn("spread/metal-studio/output_tok_s/c4-short", noise["metrics"]) + self.assertEqual([key for key in noise["metrics"] if key.startswith("vs_previous/")], []) + + def test_a_log_longer_than_a_description_holds_is_cut_at_a_line_and_keeps_its_jobs(self): + self.assertEqual(night_note("short\n", []), "short\n") + long = "".join(f"| row {index} |\n" for index in range(2000)) + note = night_note(long, ["- metal-studio: link:run9"]) + self.assertLessEqual(len(note), NOTE_LIMIT) + self.assertTrue(note.startswith("| row 0 |\n| row 1 |\n")) + self.assertTrue(note.endswith("|\n\nThe rest of this log is in the attached nightly.md.\n" + "\n## Recorded jobs\n\n- metal-studio: link:run9\n")) + + +class RecorderTests(unittest.TestCase): + def test_record_marks_a_job_verified_only_when_its_checks_held(self): + record, plan = run_path(RECORDER)["record"], admitted() + result = measured(plan, rate={"candidate": 80.0}) + environment = {"RUN_URL": "https://github.example/runs/11", "GITHUB_RUN_ID": "11", "GITHUB_RUN_ATTEMPT": "1"} + for checks, state in (([], "verified"), + (["baseline ran without --kv-pool-tokens"], "completed, awaiting audit")): + tracking = Memory() + lane = {**{field: LANE[field] for field in ("id", "backend", "node", "model")}, "job": "job_1", + "host": "Apple M3 Ultra", "checks": checks, "cells": cells(result, "commits")} + unfinished = {**lane, "id": "cuda-spark", "job": None, "host": None, "cells": [], + "checks": ["its job did not finish, so there is nothing to compare"]} + report = night(CANDIDATE, BASELINE, "commits", [lane, unfinished]) + with TemporaryDirectory() as directory: + root = Path(directory) + (root / "inference-performance-metal-studio-11-1").mkdir() + write_job(root / "inference-performance-metal-studio-11-1", plan, result) + (root / "nightly").mkdir() + (root / "nightly/nightly.json").write_text(json.dumps(report), encoding="utf-8") + (root / "nightly/nightly.md").write_text(markdown(report), encoding="utf-8") + both = [LANE, {**LANE, "id": "cuda-spark", "node": "n2"}] + with patch.dict(record.__globals__, Experiment=lambda: tracking, lanes=lambda: both), \ + patch.dict("os.environ", environment): + record(root) + runs = tracking.keyed() + self.assertEqual((runs["job:job_1"]["tags"]["eval.verification_state"], runs["job:job_1"]["tags"]["ci.run"]), + (state, environment["RUN_URL"])) + note = runs["nightly:11:1"]["tags"]["mlflow.note.content"] + self.assertIn(f'- metal-studio: link:{tracking.find("job:job_1").run_id}', note) + self.assertNotIn("- cuda-spark: link:", note) + + def test_a_search_names_its_parameters_and_tags_and_refuses_a_quote(self): + where = run_path(RECORDER)["where"] + self.assertEqual(where({"machine_type": MACHINE}, {"arm.role": "main"}, {"arm.role": "ceiling"}), + f"params.machine_type = '{MACHINE}' and tags.`arm.role` = 'main' " + "and tags.`arm.role` != 'ceiling'") + self.assertEqual(where({}, {"eval.key": "job:job_1"}, None), "tags.`eval.key` = 'job:job_1'") + for value in ("it's", 4): + with self.assertRaises(ValueError): + where({"model": value}, {}, None) + + def test_an_error_is_printed_without_the_server_its_experiment_or_its_account(self): + redacted = run_path(RECORDER)["redacted"] + environment = {"MLFLOW_TRACKING_URI": "https://tracking.example.test/", + "MLFLOW_EXPERIMENT_NAME": "Some experiment", "MLFLOW_TRACKING_USERNAME": "someone@example.test"} + with patch.dict("os.environ", environment): + text = redacted("GET https://tracking.example.test/api failed (host='tracking.example.test'), " + "in Some experiment, as someone@example.test") + for private in ("tracking.example.test", "Some experiment", "someone@"): + self.assertNotIn(private, text) + self.assertIn("[withheld]", text) + + class VerdictTests(unittest.TestCase): clean = {"regressions": 0, "unverified": 0} - def test_a_night_passes_only_when_every_lane_held_and_skippy_did_not_regress(self): + def test_a_night_passes_only_when_every_lane_held_skippy_did_not_regress_and_it_was_recorded(self): def passed(mode, totals=None, **results): return verdict(mode, results, totals)[0] - finished = {"plan": "success", "measure": "success", "report": "success"} + finished = {"plan": "success", "measure": "success", "report": "success", "record": "success"} self.assertTrue(passed("commits", self.clean, **finished)) self.assertTrue(passed("noise", self.clean, **finished)) - self.assertTrue(passed("unchanged", plan="success", measure="skipped", report="skipped")) + self.assertTrue(passed("unchanged", plan="success", measure="skipped", report="skipped", record="skipped")) for mode, change in (("commits", {"plan": "failure"}), ("", {}), ("commits", {"measure": "failure"}), ("commits", {"measure": "cancelled"}), ("noise", {"measure": "skipped"}), - ("commits", {"report": "failure"}), ("commits", {"report": "skipped"})): + ("commits", {"report": "failure"}), ("commits", {"report": "skipped"}), + ("commits", {"record": "failure"}), ("noise", {"record": "skipped"})): self.assertFalse(passed(mode, self.clean, **{**finished, **change}), (mode, change)) self.assertFalse(passed("commits", None, **finished)) self.assertFalse(passed("commits", {**self.clean, "regressions": 1}, **finished)) @@ -357,10 +638,11 @@ def passed(mode, totals=None, **results): def test_the_verdict_step_fails_the_run_unless_the_report_handed_on_clean_counts(self): settle = run_path(SCRIPT)["settle"] environment = {"PLAN": "success", "MODE": "commits", "MEASURE": "success", "REPORT": "success", - "REGRESSIONS": "0", "UNVERIFIED": "0", "GITHUB_STEP_SUMMARY": ""} + "RECORD": "success", "REGRESSIONS": "0", "UNVERIFIED": "0", "GITHUB_STEP_SUMMARY": ""} with patch.dict("os.environ", environment): settle() - for change in ({"REGRESSIONS": "2"}, {"UNVERIFIED": "1"}, {"REGRESSIONS": ""}, {"REPORT": "failure"}): + for change in ({"REGRESSIONS": "2"}, {"UNVERIFIED": "1"}, {"REGRESSIONS": ""}, {"REPORT": "failure"}, + {"RECORD": "failure"}): with patch.dict("os.environ", change): with self.assertRaises(SystemExit): settle() From 4666b659e7e2d700d61a52c83bc1bc37274c2068 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Tue, 1 Dec 2026 14:11:53 +1100 Subject: [PATCH 39/50] Measure each recorded arm against llama.cpp at its own pin When a job runs llama.cpp at two pins, a Skippy arm's ratio of llama-server belongs beside the pin that arm was built on. The recorder chose by role, so only an arm with the role `baseline` was set beside the baseline's pin. Main beside a pull request that moves the pin keeps the role `main`, and a diagnostic job gives every Skippy arm the role `diagnostic`: both were measured against llama.cpp at the candidate's pin, and for main that ratio went onto its trend. The recorder now chooses by arm, so the baseline arm is set beside `baseline-reference` whenever the job ran one. A night's own jobs record as before: there the baseline arm has the role `baseline`. --- ci/INFERENCE_PERFORMANCE.md | 3 ++- scripts/lib/performance_record.py | 5 +++-- scripts/tests/inference_performance_nightly.py | 15 +++++++++++++++ 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index 0e72cadb..7a3a339a 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -77,7 +77,8 @@ neither the server nor the experiment nor a run's address, and masks the server' beneath it: verified when its checks held, awaiting audit otherwise. Every arm's run carries `params.machine_type` and `params.model`, the tag `arm.role`, and its medians as `/`; a Skippy arm also carries each as a ratio of `llama-server`'s in the same - job, `_vs_llama/`. + job, `_vs_llama/`. When a job runs `llama-server` at two pins, each Skippy arm + is set beside the one at its own. - Tonight's commit has the role `main`: it becomes the current run of its machine type and model, and adds a point to their trend at the time of its commit. So does `llama-server` at its pin, as `reference`. diff --git a/scripts/lib/performance_record.py b/scripts/lib/performance_record.py index fac61f03..d8911c9e 100644 --- a/scripts/lib/performance_record.py +++ b/scripts/lib/performance_record.py @@ -280,8 +280,9 @@ def record_job(tracking, evidence, label, job_id, standing, line=None, extra=Non else: role = role_of(arm_rows, candidate, line) title = role_label(role, arm_rows, line) - # a baseline is measured against llama.cpp at its own pin when the job ran it, else at the candidate's - beside = "baseline-reference" if role == "baseline" and "baseline-reference" in computed else "reference" + # The baseline arm is measured against llama.cpp at its own pin when the job ran it, whatever its role: + # it is `main` beside a pull request, and a pull request's pin must not move main's trend. + beside = "baseline-reference" if arm == "baseline" and "baseline-reference" in computed else "reference" view = headline(medians, computed.get(beside, (None, {}))[1] if head["kind"] == "skippy" else None) child = start_run( tracking, f"job:{job_id}:{arm}", f'{title} · {", ".join(models)} · {short(head["sha"])}', diff --git a/scripts/tests/inference_performance_nightly.py b/scripts/tests/inference_performance_nightly.py index 99e2dcd9..214036d4 100644 --- a/scripts/tests/inference_performance_nightly.py +++ b/scripts/tests/inference_performance_nightly.py @@ -498,6 +498,21 @@ def test_beside_a_pull_request_main_keeps_its_own_role(self): ("main", "Skippy main · qwen35-4b · " + "b" * 12, "true")) self.assertEqual(runs[f"trend:{MACHINE}:qwen35-4b:main"]["metrics"][self.cell], 101.0) + def test_a_moved_pin_measures_the_baseline_arm_at_its_own_pin_whatever_its_role(self): + moved = admitted(baseline_reference="d" * 40) + _, runs, _ = self.recorded(moved, pull_requests={"candidate": 130}) + head, main = runs["job:job_1:candidate"], runs["job:job_1:baseline"] + self.assertEqual((head["tags"]["arm.role"], main["tags"]["arm.role"]), ("branch", "main")) + self.assertAlmostEqual(head["metrics"][self.beside_llama], 81 / 161) + self.assertAlmostEqual(main["metrics"][self.beside_llama], 101 / 201) + # the pull request's pin does not reach main's trend + self.assertAlmostEqual(runs[f"trend:{MACHINE}:qwen35-4b:main"]["metrics"][self.beside_llama], 101 / 201) + + _, runs, _ = self.recorded(moved, standing="diagnostic") + self.assertEqual(runs["job:job_1:baseline"]["tags"]["arm.role"], "diagnostic") + self.assertAlmostEqual(runs["job:job_1:baseline"]["metrics"][self.beside_llama], 101 / 201) + self.assertAlmostEqual(runs["job:job_1:candidate"]["metrics"][self.beside_llama], 81 / 161) + def test_an_unchecked_job_awaits_audit_and_a_diagnostic_one_stays_out_of_the_view(self): _, runs, _ = self.recorded(admitted(), standing="unaudited") self.assertEqual(runs["job:job_1"]["tags"]["eval.verification_state"], "completed, awaiting audit") From 27e047756ee52ad84d2178fa82d7fb61f4aa6a5d Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Tue, 1 Dec 2026 14:11:53 +1100 Subject: [PATCH 40/50] Keep run links out of the recording job's public log The recording script promised to print neither the tracking server nor a run's address, and kept that promise only for its own lines and its errors. The MLflow client prints a link to every run it ends, so a night's log would have carried the experiment and each run's address beside the masked server name. A smoke run against a real server showed it. The client's own switch for those links is now set, and everything the process writes passes through the redaction on its way out, whoever writes it: a connection warning names the server, and a later client may print what this one does not. A run's address is withheld along with the server, the experiment and the account. --- ci/INFERENCE_PERFORMANCE.md | 4 +- scripts/inference-performance-record.py | 41 +++++++++++++++---- .../tests/inference_performance_nightly.py | 16 ++++++++ 3 files changed, 53 insertions(+), 8 deletions(-) diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index 7a3a339a..7c3c06eb 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -71,7 +71,9 @@ credentials, the `inference-records` environment's `SKIPPY_MLFLOW_TRACKING_URI`, `SKIPPY_MLFLOW_TRACKING_USERNAME`, `SKIPPY_MLFLOW_TRACKING_PASSWORD` and `SKIPPY_MLFLOW_EXPERIMENT` secrets, and it runs no measured code. It uses the client pinned in `ci/inference-record-requirements.txt`. This repository's logs are public, so it prints -neither the server nor the experiment nor a run's address, and masks the server's name. +neither the server nor the experiment nor a run's address, and masks the server's name. The +MLflow client would print a link to every run it ends: that is switched off, and whatever the +client or the script writes is redacted on its way to the log. - Each lane's job is a job run with a top-level run per arm and that arm's per-round detail beneath it: verified when its checks held, awaiting audit otherwise. Every arm's run carries diff --git a/scripts/inference-performance-record.py b/scripts/inference-performance-record.py index 3741b357..8f954df2 100644 --- a/scripts/inference-performance-record.py +++ b/scripts/inference-performance-record.py @@ -3,12 +3,13 @@ Credentials come from MLFLOW_TRACKING_URI, MLFLOW_TRACKING_USERNAME and MLFLOW_TRACKING_PASSWORD, and the experiment's name from MLFLOW_EXPERIMENT_NAME. This repository's logs are public, so -nothing here prints the server, the experiment or a run's address, and an error is printed -without them. +nothing this process writes names the server, the experiment or a run's address: the client's +own run links are switched off, and whatever it or this script writes is redacted on its way out. """ import argparse import os +import re import sys import tempfile import traceback @@ -23,6 +24,8 @@ "MLFLOW_EXPERIMENT_NAME") # MLflow takes at most 100 parameters or tags and 1,000 entries in one batch. SMALL_BATCH, METRIC_BATCH = 100, 900 +# The part of a run's or an experiment's address that survives when the server's name is withheld. +ADDRESS = re.compile(r"#/experiments/[^\s'\"]*") def batches(items, size): @@ -41,6 +44,15 @@ def quoted(value): *(f"tags.`{name}` != {quoted(value)}" for name, value in (without or {}).items())]) +def client_settings(): + """What the MLflow client reads from the environment, set before the client is made.""" + # a server that does not answer fails the recording; it never hangs the job + os.environ.setdefault("MLFLOW_HTTP_REQUEST_TIMEOUT", "60") + os.environ.setdefault("MLFLOW_HTTP_REQUEST_MAX_RETRIES", "2") + # the client prints the address of every run it ends, and this log is public + os.environ["MLFLOW_SUPPRESS_PRINTING_URL_TO_STDOUT"] = "true" + + class Experiment: """One MLflow experiment, as the calls the recorder makes.""" @@ -48,9 +60,7 @@ def __init__(self): missing = [name for name in REQUIRED if not os.environ.get(name)] if missing: raise ValueError(f'not set: {", ".join(missing)}') - # a server that does not answer fails the recording; it never hangs the job - os.environ.setdefault("MLFLOW_HTTP_REQUEST_TIMEOUT", "60") - os.environ.setdefault("MLFLOW_HTTP_REQUEST_MAX_RETRIES", "2") + client_settings() import mlflow from mlflow.entities import Metric, Param, RunTag from mlflow.tracking import MlflowClient @@ -135,13 +145,29 @@ def record(root): def redacted(text): - """`text` without the tracking server, its experiment or its account, for a public log.""" + """`text` without the tracking server, its experiment, its account or a run's address, for a + public log.""" uri = os.environ.get("MLFLOW_TRACKING_URI", "") for private in (uri.rstrip("/"), urlsplit(uri).hostname, os.environ.get("MLFLOW_EXPERIMENT_NAME"), os.environ.get("MLFLOW_TRACKING_USERNAME")): if private: text = text.replace(private, "[withheld]") - return text + return ADDRESS.sub("[withheld]", text) + + +class Public: + """A stream of the public log. The client library writes to it as well as this script, a + warning about a failed connection names the server, and a later client may print what this + one does not: so everything written is redacted here, whoever writes it.""" + + def __init__(self, stream): + self.stream = stream + + def write(self, text): + return self.stream.write(redacted(text)) + + def __getattr__(self, name): + return getattr(self.stream, name) def main(): @@ -151,6 +177,7 @@ def main(): if __name__ == "__main__": + sys.stdout, sys.stderr = Public(sys.stdout), Public(sys.stderr) try: main() except Exception as error: # MLflow and its HTTP client raise types of their own diff --git a/scripts/tests/inference_performance_nightly.py b/scripts/tests/inference_performance_nightly.py index 214036d4..48b0e207 100644 --- a/scripts/tests/inference_performance_nightly.py +++ b/scripts/tests/inference_performance_nightly.py @@ -1,7 +1,9 @@ """Offline checks for the nightly performance comparison's lanes, baseline, evidence, regressions, verdict and recording.""" +import io import json +import os import unittest from pathlib import Path from runpy import run_path @@ -628,6 +630,20 @@ def test_an_error_is_printed_without_the_server_its_experiment_or_its_account(se self.assertNotIn(private, text) self.assertIn("[withheld]", text) + def test_what_the_client_writes_reaches_the_public_log_without_the_server_or_a_runs_address(self): + recorder = run_path(RECORDER) + environment = {"MLFLOW_TRACKING_URI": "https://tracking.example.test", "MLFLOW_TRACKING_USERNAME": "someone"} + log = io.StringIO() + with patch.dict("os.environ", environment): + recorder["client_settings"]() + # the client's own switch for the link it prints when a run ends + self.assertEqual(os.environ["MLFLOW_SUPPRESS_PRINTING_URL_TO_STDOUT"], "true") + public = recorder["Public"](log) + print("View run nightly at: https://tracking.example.test/#/experiments/40/runs/0123abcd", file=public) + print("Connection to tracking.example.test timed out", file=public) + self.assertEqual(log.getvalue(), "View run nightly at: [withheld]/[withheld]\n" + "Connection to [withheld] timed out\n") + class VerdictTests(unittest.TestCase): clean = {"regressions": 0, "unverified": 0} From e310d18da01673b2b3542d3acbf79579d12dbaea Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Tue, 1 Dec 2026 14:11:53 +1100 Subject: [PATCH 41/50] Measure the nightly on an x86 CUDA host as well The nightly covered Metal and the GB10's CUDA, so a change that slowed Skippy only on a discrete NVIDIA card would pass. A fourth lane now runs the same comparison on lab-a33338, an x86 host with an RTX 5080, using the cuda-x86 backend. It measures qwen35-4b, the model that host has already been measured with: those jobs held their checks, with llama-server rejecting only the two points its pool cannot hold, as it does on the other lanes. --- ci/inference-performance-nightly.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ci/inference-performance-nightly.json b/ci/inference-performance-nightly.json index 89f4e7d0..ac0fa873 100644 --- a/ci/inference-performance-nightly.json +++ b/ci/inference-performance-nightly.json @@ -4,6 +4,7 @@ "lanes": [ {"id": "metal-mini", "backend": "metal", "node": "macmini-g2hg9f", "model": "qwen35-9b"}, {"id": "metal-studio", "backend": "metal", "node": "macstudio-2l0352", "model": "qwen36-35b-a3b"}, - {"id": "cuda-spark", "backend": "cuda", "node": "spark-001272", "model": "qwen35-9b"} + {"id": "cuda-spark", "backend": "cuda", "node": "spark-001272", "model": "qwen35-9b"}, + {"id": "cuda-x86", "backend": "cuda-x86", "node": "lab-a33338", "model": "qwen35-4b"} ] } From 24d956b412410e42ffc90c59bc287f82ea1fa6c5 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Tue, 1 Dec 2026 16:20:32 +1100 Subject: [PATCH 42/50] Fix the ROCm memory figures and read GPU memory at each admission rocm_memory() unpacked each of its four counts as if it were a list, so every ROCm job stopped with a TypeError before measuring anything. Its preflight also accepted amd-smi alone, though only rocm-smi is read. Both discrete backends admitted every model against the GPU memory free when the job started. A later model was let in on memory that had since been taken, or refused memory that had since been freed. x86 CUDA now reads GPU 0's free memory, and ROCm its VRAM and GTT, at each admission; the figures at the start stay in the host facts as evidence. --- scripts/lib/performance_backends.py | 28 +++++++++----- .../tests/inference_performance_contracts.py | 37 +++++++++++++------ 2 files changed, 44 insertions(+), 21 deletions(-) diff --git a/scripts/lib/performance_backends.py b/scripts/lib/performance_backends.py index a75a7796..99cf3c31 100644 --- a/scripts/lib/performance_backends.py +++ b/scripts/lib/performance_backends.py @@ -112,9 +112,18 @@ def cuda_x86_facts(): "gpu_processes": processes or None} +def gpu0_free(): + free_mib = capture(["nvidia-smi", "--query-gpu=memory.free", "--format=csv,noheader,nounits", + "-i", "0"]).strip() + if not free_mib.isdigit(): + raise ValueError(f"nvidia-smi reported no free memory for GPU 0: {free_mib!r}") + return int(free_mib) * 1024**2 + + def cuda_x86_free(host): - """The weights must fit GPU 0's own free VRAM, and Skippy may also hold KV in host RAM.""" - return min(host["gpu_memory_free_bytes"], cuda_free(host)) + """The weights must fit GPU 0's own free VRAM, and Skippy may also hold KV in host RAM. Both are + read at each model's admission: what the job saw at its start is evidence, not what is free now.""" + return min(gpu0_free(), cuda_free(host)) def rocm_agent(): @@ -152,8 +161,8 @@ def rocm_reference_cmake(): def rocm_tool_check(): capture(["rocminfo"]) - if not shutil.which("rocm-smi") and not shutil.which("amd-smi"): - raise ValueError("the rocm backend requires rocm-smi or amd-smi for its memory figures") + if not shutil.which("rocm-smi"): + raise ValueError("the rocm backend requires rocm-smi for its memory figures") def _try_capture(args): @@ -177,8 +186,8 @@ def field(*words): return int(lines[1].split(",")[index].strip()) raise ValueError(f"rocm-smi columns for {words} not found in {header}") - return (*field("vram", "total"), *field("vram", "used"), *field("gtt", "total"), - *field("gtt", "used"), len(lines) - 1) + return (field("vram", "total"), field("vram", "used"), field("gtt", "total"), field("gtt", "used"), + len(lines) - 1) def rocm_facts(): @@ -203,9 +212,10 @@ def rocm_facts(): def rocm_free(host): """Unified AMD memory: the GPU allocates from its carve-out (VRAM) plus GTT, and the - kernel caps GTT, so both pools and MemAvailable bound what a model gets.""" - return min(cuda_free(host), (host["vram_total_bytes"] - host["vram_used_bytes"]) - + (host["gtt_total_bytes"] - host["gtt_used_bytes"])) + kernel caps GTT, so both pools and MemAvailable bound what a model gets. All three are + read at each model's admission.""" + vram_total, vram_used, gtt_total, gtt_used, _ = rocm_memory() + return min(cuda_free(host), (vram_total - vram_used) + (gtt_total - gtt_used)) # The unified reserve, shared system memory for everything beside the weights. diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index 9a0a193f..ff6ac8fe 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -658,11 +658,14 @@ def test_the_cuda_x86_entry_builds_for_the_hosts_own_architecture(self): def test_cuda_x86_admission_takes_the_lesser_of_gpu0_free_vram_and_host_memory(self): meminfo = "MemAvailable: 2097152 kB\n" - for free_vram, expected in ((10 * 1024**3, 2 * 1024**3), (1 * 1024**3, 1 * 1024**3)): - with patch("lib.performance_backends.Path") as path: + # what was free at the job's start is not what each model is admitted against + started = {"gpu_memory_free_bytes": 12 * 1024**3} + for free_mib, expected in (("10240", 2 * 1024**3), ("1024", 1 * 1024**3)): + with patch("lib.performance_backends.Path") as path, \ + patch("lib.performance_backends.capture", return_value=free_mib + "\n") as capture: path.return_value.read_text.return_value = meminfo - self.assertEqual(performance_backends.cuda_x86_free( - {"gpu_memory_free_bytes": free_vram}), expected) + self.assertEqual(performance_backends.cuda_x86_free(started), expected) + self.assertIn("--query-gpu=memory.free", capture.call_args[0][0]) def test_the_rocm_entry_builds_both_arms_for_the_pinned_gfx_target(self): calls = [] @@ -683,14 +686,24 @@ def test_the_rocm_entry_builds_both_arms_for_the_pinned_gfx_target(self): def test_rocm_admission_takes_the_lesser_of_memory_and_free_vram_plus_gtt(self): gib = 1024**3 - host = {"vram_total_bytes": 90 * gib, "vram_used_bytes": 10 * gib, - "gtt_total_bytes": 80 * gib, "gtt_used_bytes": 20 * gib} - with patch("lib.performance_backends.Path") as path: - path.return_value.read_text.return_value = "MemAvailable: 104857600 kB\n" # 100 GiB - self.assertEqual(performance_backends.rocm_free(host), 100 * gib) - with patch("lib.performance_backends.Path") as path: - path.return_value.read_text.return_value = "MemAvailable: 209715200 kB\n" # 200 GiB - self.assertEqual(performance_backends.rocm_free(host), 140 * gib) + # rocm-smi's CSV, read now rather than at the job's start: 80 GiB of VRAM and 60 of GTT are free + csv = ("device,VRAM Total Memory (B),VRAM Total Used Memory (B),GTT Total Memory (B)," + f"GTT Total Used Memory (B)\ncard0,{90 * gib},{10 * gib},{80 * gib},{20 * gib}\n") + started = {"vram_total_bytes": 90 * gib, "vram_used_bytes": 85 * gib, + "gtt_total_bytes": 80 * gib, "gtt_used_bytes": 75 * gib} + with patch("lib.performance_backends.capture", return_value=csv): + self.assertEqual(performance_backends.rocm_memory(), (90 * gib, 10 * gib, 80 * gib, 20 * gib, 1)) + for meminfo, expected in (("MemAvailable: 104857600 kB\n", 100 * gib), + ("MemAvailable: 209715200 kB\n", 140 * gib)): + with patch("lib.performance_backends.Path") as path: + path.return_value.read_text.return_value = meminfo + self.assertEqual(performance_backends.rocm_free(started), expected) + + def test_the_rocm_preflight_requires_the_memory_tool_the_job_reads(self): + with patch("lib.performance_backends.capture"), \ + patch("lib.performance_backends.shutil.which", side_effect=lambda tool: tool == "amd-smi"): + with self.assertRaisesRegex(ValueError, "rocm-smi"): + performance_backends.rocm_tool_check() def test_the_workflow_offers_every_backend_in_the_table_and_passes_it_to_admit(self): workflow = (Path(__file__).resolve().parents[2] From 522aada6edf702fcd7549a21e30d4b9cf9eabbac Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Tue, 1 Dec 2026 16:20:52 +1100 Subject: [PATCH 43/50] Fail a point on request errors that are not a full KV pool Where llama-server may refuse requests because its pool cannot hold them all, any error among the measured requests was taken for that refusal. An unrelated failure, a 503 or a dropped connection, was then recorded as the server's answer instead of failing the point. Only llama-server's "Context size has been exceeded", and the empty stream AIPerf records when that error arrives mid-stream, now count as a rejection: every rejection recorded in the lab so far was one of the two but a single dropped connection. Any other error raises, as it does at every other point. --- scripts/lib/performance_load.py | 12 +++++++++++- scripts/tests/inference_performance_contracts.py | 13 +++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/scripts/lib/performance_load.py b/scripts/lib/performance_load.py index d7906e45..be711367 100644 --- a/scripts/lib/performance_load.py +++ b/scripts/lib/performance_load.py @@ -129,13 +129,19 @@ def measurements(export): for name, (metric, statistic) in METRICS.items()} +# How llama-server's answer reads when the requests in flight need more KV than its pool holds: a 500 +# naming the context or, mid-stream, an error event AIPerf records as a response without content. +POOL_FULL = ("Context size has been exceeded", "No responses with actual content were received") + + def rejection(directory, requests): """What the server failed among the measured requests, from AIPerf's per-request export. AIPerf records an error for a request the server answers with one. A stream that ends on an error event it counts as served and leaves without an output length: that request is cut short here. None when nothing failed, and None unless the export accounts for every - measured request, so a load run that broke off is never taken for the server's answer. + measured request, so a load run that broke off is never taken for the server's answer. Any + other error is a fault, at this point as at every other: it raises. """ exports = list(directory.rglob("profile_export.jsonl")) if len(exports) != 1: @@ -149,6 +155,10 @@ def rejection(directory, requests): and "output_sequence_length" not in (record.get("metrics") or {})) if len(measured) != requests or not (failed or cut_short): return None + unexplained = [error for error in failed if not any(text in error for text in POOL_FULL)] + if unexplained: + raise ValueError(f"{sum(failed[error] for error in unexplained)} of {requests} requests failed " + f"with errors that are not a full KV pool, such as {json.loads(unexplained[0])}") return {"requests": requests, "failed": sum(failed.values()), "cut_short": cut_short, "errors": [{"error_details": json.loads(error), "count": count} for error, count in sorted(failed.items())]} diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index ff6ac8fe..4128dc18 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -753,6 +753,19 @@ def test_rejection_counts_failed_and_cut_short_requests_among_the_measured_ones( self.write(directory, served=4) self.assertIsNone(rejection(Path(directory), 4)) + def test_only_a_full_pool_counts_as_a_rejection_and_any_other_error_fails_the_point(self): + from tempfile import TemporaryDirectory + empty_stream = {"code": None, "type": "InvalidInferenceResultError", + "message": "Invalid inference result: No responses with actual content were received"} + unrelated = {"code": 503, "type": "Service Unavailable", "message": "Loading model"} + with TemporaryDirectory() as directory: + self.write(directory, failed=[self.refused, empty_stream], served=2) + self.assertEqual(rejection(Path(directory), 4)["failed"], 2) + with TemporaryDirectory() as directory: + self.write(directory, failed=[self.refused, unrelated], served=2) + with self.assertRaisesRegex(ValueError, "1 of 4 requests failed with errors that are not a full KV pool"): + rejection(Path(directory), 4) + def test_a_point_the_server_may_reject_keeps_what_it_rejected_in_place_of_metrics(self): from subprocess import CalledProcessError from tempfile import TemporaryDirectory From 26042550e60998fba4dfa382ba8b0f28d15e9f5e Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Tue, 1 Dec 2026 16:21:50 +1100 Subject: [PATCH 44/50] Compare variant flags as the launcher passes them Servers compared with each other must differ in their Skippy flags. The check compared the flags' JSON, so `2048` and `"2048"`, which the launcher passes as the same argument, counted as different settings and two identical servers were admitted as a comparison. --- scripts/lib/performance_plan.py | 4 +++- scripts/tests/inference_performance_contracts.py | 8 +++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/scripts/lib/performance_plan.py b/scripts/lib/performance_plan.py index 69ea63cf..48baef3b 100644 --- a/scripts/lib/performance_plan.py +++ b/scripts/lib/performance_plan.py @@ -238,7 +238,9 @@ def setup(server): [{key: value for key, value in point.items() if key != "id"} for point in server["points"]]) first, *rest = shape["servers"] - flags = [json.dumps(server.get("skippy_flags", {}), sort_keys=True) for server in shape["servers"]] + # As the launcher passes them: 2048 and "2048" are one setting. + flags = [json.dumps({name: str(value) for name, value in server.get("skippy_flags", {}).items()}, + sort_keys=True) for server in shape["servers"]] if any(setup(server) != setup(first) for server in rest) or len(set(flags)) != len(flags): raise ValueError("servers compared with each other must differ in their skippy_flags and nothing else") return "servers" diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index 4128dc18..69501337 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -359,9 +359,11 @@ def test_without_a_baseline_a_plan_compares_servers_that_differ_only_in_flags(se performance_plan.job_spec("d" * 40, alone, ["qwen35-4b"], 3, None, "any", servers=named) twin = {**performance_plan.scenario([servers[1]])["servers"][0], "id": "test-twin"} twin["points"] = [{**point, "id": "test-twin-" + point["id"]} for point in twin["points"]] - with patch.object(performance_plan, "read_json", return_value=with_server(twin)): - with self.assertRaises(ValueError): - performance_plan.comparison(alone, [servers[1], "test-twin"]) + # the same flags, and the same flags written as strings, are one setting to the launcher + for flags in (twin["skippy_flags"], {name: str(value) for name, value in twin["skippy_flags"].items()}): + with patch.object(performance_plan, "read_json", return_value=with_server({**twin, "skippy_flags": flags})): + with self.assertRaises(ValueError): + performance_plan.comparison(alone, [servers[1], "test-twin"]) def test_job_runs_every_arm_from_its_own_checkout_on_a_metal_host(self): arm_list = performance_plan.arms(self.candidate, self.baseline, self.pin) From 6be1b33ed88dfdc65d21905e3a3bdcb6262d0624 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Tue, 1 Dec 2026 16:21:50 +1100 Subject: [PATCH 45/50] Refuse a campaign whose timed points outlast the job A replayed conversation runs for its whole duration, so a plan with many rounds, arms or timed servers could need more time than the job's five hours. It was admitted, ran until JY stopped it, and left no comparable evidence. The plan now adds up the timed points, including the trace pass, and refuses one that cannot fit, saying what to reduce. --- scripts/lib/performance_plan.py | 9 ++++++++- scripts/tests/inference_performance_contracts.py | 8 ++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/scripts/lib/performance_plan.py b/scripts/lib/performance_plan.py index 48baef3b..1c3e475c 100644 --- a/scripts/lib/performance_plan.py +++ b/scripts/lib/performance_plan.py @@ -21,6 +21,8 @@ COMPONENT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]{0,63}") NODE = re.compile(r"[A-Za-z0-9._-]{1,64}") MAX_ROUNDS = 9 +# What JY gives one job, before its grace period. +JOB_SECONDS = 18000 POINT_FIELDS = {"id", "concurrency", "depth", "input_tokens", "output_tokens", "requests"} SERVER_FIELDS = {"id", "lanes", "pool_tokens", "points"} # A conversation point's run is long enough to replay whole conversations, and ends well @@ -374,6 +376,11 @@ def job_spec(harness, arm_list, keys, rounds, node, label, *, trace=False, backe "ref": f"ci/inference-performance.json@{harness}", "sha256": digest(SCENARIO)} bounds = {"request_count": sum(point.get("requests", 0) for point in points) * runs, "duration_s": sum(point.get("duration_s", 0) for point in points) * runs} + # Timed points run for their whole duration, so they alone show a campaign the job cannot finish. + timed = bounds["duration_s"] + (sum(point.get("duration_s", 0) for point in points) * len(keys) if trace else 0) + if timed > JOB_SECONDS: + raise ValueError(f"the timed points alone run {timed} s, past the job's {JOB_SECONDS} s: " + "run fewer rounds, arms, models or timed servers") return { "name": f"skippy-inference-performance-{label}", "description": entry["description"] + " of " + ", ".join( @@ -398,5 +405,5 @@ def job_spec(harness, arm_list, keys, rounds, node, label, *, trace=False, backe # JY needs at least one; a bound no point uses stays out rather than reading zero. **{name: value for name, value in bounds.items() if value}, }, - "budget": {"max_usd": 0, "max_duration_s": 18000, "grace_s": 300}, + "budget": {"max_usd": 0, "max_duration_s": JOB_SECONDS, "grace_s": 300}, } diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index 69501337..a8b8f037 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -365,6 +365,14 @@ def test_without_a_baseline_a_plan_compares_servers_that_differ_only_in_flags(se with self.assertRaises(ValueError): performance_plan.comparison(alone, [servers[1], "test-twin"]) + def test_a_campaign_whose_timed_points_outlast_the_job_is_refused(self): + arm_list = performance_plan.arms(self.candidate, self.baseline, self.pin) + timed = ["lanes1-agentx-ctx64k", "lanes1-agentx-ctx64k-admission-grid"] + spec = performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 3, None, "any", servers=timed) + self.assertEqual(spec["budget"]["max_duration_s"], performance_plan.JOB_SECONDS) + with self.assertRaisesRegex(ValueError, "fewer rounds, arms, models or timed servers"): + performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 9, None, "any", servers=timed) + def test_job_runs_every_arm_from_its_own_checkout_on_a_metal_host(self): arm_list = performance_plan.arms(self.candidate, self.baseline, self.pin) spec = performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 3, "macstudio-2l0352", "m1") From 1f86056f4c9701e4a25801619033044fb70ec5a1 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Tue, 1 Dec 2026 16:22:32 +1100 Subject: [PATCH 46/50] Chart a server comparison's control beside each variant Without a baseline, each variant is measured against the first named server, and its verdict says so. Its chart drew the comparison arms in place of the reference bar, and those were only the variant's own candidate and llama-server, so a +20% verdict sat beside a chart without the control it was 20% above. The control's median now leads the variant's bars. --- scripts/lib/performance_report.py | 7 ++++--- scripts/tests/inference_performance_contracts.py | 2 ++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/scripts/lib/performance_report.py b/scripts/lib/performance_report.py index 8382e523..a3f2fc05 100644 --- a/scripts/lib/performance_report.py +++ b/scripts/lib/performance_report.py @@ -125,14 +125,15 @@ def report_view(host, rows, record): "outcome": "passed", "metrics": [], }) arms = row["arms"] + compared = [(title, arms[label]["median"]) for label, title in ARM_TITLES.items() if label in arms] metric = {"metric": row["metric"], "workload": configuration["workload"], - "measured": arms["candidate"]["median"], - "comparison_arms": [(title, arms[label]["median"]) - for label, title in ARM_TITLES.items() if label in arms]} + "measured": arms["candidate"]["median"], "comparison_arms": compared} if "baseline" in arms: metric["reference"] = {"value": arms["baseline"]["median"]} elif row.get("candidate_vs_control"): metric["reference"] = {"value": row["control"]["stats"]["median"]} + # A chart draws these arms in place of its reference, so the server measured against is one. + compared.insert(0, (f'{row["control"]["server"]} (control)', row["control"]["stats"]["median"])) configuration["metrics"].append(metric) run = {"id": "controlled", "source_sha": candidate["sha"], "started_at": record["started_at"], "profile": "controlled performance", "measurement_kind": "controlled", "outcome": "passed", diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index a8b8f037..19938fb5 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -875,6 +875,8 @@ def test_a_server_comparison_measures_each_server_against_the_first_named(self): report = markdown("t", "h", rows, self.record) self.assertIn("+20.00% · Improved", report) self.assertIn("compared with lanes4-pool32k-prefill2048, the first named", report) + # the variant's chart draws the control it is compared with beside it + self.assertIn('x-axis ["lanes4-pool32k-prefill2048 (control)", "Candidate"]', report) def test_a_moved_pin_says_whether_llama_cpp_moved_too(self): def sample(arm, value): From b47b2b204ad1a871263435764e8b4d0cb254324a Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Tue, 1 Dec 2026 16:24:58 +1100 Subject: [PATCH 47/50] Count a recorded run as done only once its read-back passed A run is finished before it is read back, so a read-back that failed left a finished run behind. A retry found it, took it as recorded and skipped it, and evidence that had failed its check stood as the record. read_back now tags the run eval.read_back=passed as its last step, and start_run takes a finished run as recorded only with that tag. Any other finished run stops the recording for inspection, as an unfinished one already did. Runs recorded before this change carry no tag, so recording one of them again stops the same way. --- scripts/lib/performance_record.py | 16 +++++++++++----- scripts/tests/inference_performance_nightly.py | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/scripts/lib/performance_record.py b/scripts/lib/performance_record.py index d8911c9e..b1f22076 100644 --- a/scripts/lib/performance_record.py +++ b/scripts/lib/performance_record.py @@ -72,15 +72,20 @@ def machine_type(row): return f'{backend}:{row.get("gpu") or row.get("chip") or "unknown"}' +# Set on a run once its read-back has passed: only such a run counts as recorded. +READ_BACK = "eval.read_back" + + def start_run(tracking, key, name, description, tags, parent=None): - """A new run's id, or None when `key` is already recorded. A run left unfinished by an earlier - attempt stops the recording: it is inspected, never written over.""" + """A new run's id, or None when `key` is already recorded and read back. A run left unfinished, + or finished but never read back, by an earlier attempt stops the recording: it is inspected, + never written over.""" found = tracking.find(key) if found is not None: - if found.status == "FINISHED": + if found.status == "FINISHED" and found.tags.get(READ_BACK) == "passed": return None - raise RuntimeError(f"{name} exists as {found.run_id} with status {found.status}; " - "inspect it before recording again") + state = "finished, but its read-back never passed" if found.status == "FINISHED" else found.status + raise RuntimeError(f"{name} exists as {found.run_id} ({state}); inspect it before recording again") every = {"eval.key": key, "eval.program": PROGRAM, "mlflow.note.content": description, **tags} if parent: every["mlflow.parentRunId"] = parent @@ -96,6 +101,7 @@ def read_back(tracking, run_id, artifact, expected): raise RuntimeError(f"read-back of {run_id} failed: status {run.status}, metrics differing: {wrong[:5]}") if artifact is not None and tracking.artifact_sha256(run_id, Path(artifact).name) != sha256(artifact): raise RuntimeError(f"artifact {Path(artifact).name} on {run_id} differs from the local copy") + tracking.log(run_id, tags={READ_BACK: "passed"}) def role_of(rows, candidate, line): diff --git a/scripts/tests/inference_performance_nightly.py b/scripts/tests/inference_performance_nightly.py index 48b0e207..b84e423e 100644 --- a/scripts/tests/inference_performance_nightly.py +++ b/scripts/tests/inference_performance_nightly.py @@ -532,6 +532,20 @@ def test_a_run_left_unfinished_stops_the_recording(self): with self.assertRaisesRegex(RuntimeError, "inspect it"): record_job(tracking, Path(directory), "n1", "job_1", "verified") + def test_a_job_whose_read_back_failed_is_not_taken_as_recorded_on_a_retry(self): + tracking, plan = Memory(), admitted() + with TemporaryDirectory() as directory: + write_job(Path(directory), plan, measured(plan)) + stored = tracking.artifact_sha256 + # the server holds other bytes than the evidence for the job's rows + tracking.artifact_sha256 = lambda run_id, name: ("0" * 64 if name == "n1-rows.jsonl" + else stored(run_id, name)) + with self.assertRaisesRegex(RuntimeError, "differs from the local copy"): + record_job(tracking, Path(directory), "n1", "job_1", "verified") + tracking.artifact_sha256 = stored + with self.assertRaisesRegex(RuntimeError, "read-back never passed"): + record_job(tracking, Path(directory), "n1", "job_1", "verified") + def night_of(self, mode, baseline): result = measured(admitted(), rate=self.rate) lane = {**{field: LANE[field] for field in ("id", "backend", "node", "model")}, "job": "job_1", From 51fc4fdacf815ad2eb12283e7961dceb83f991ce Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Tue, 1 Dec 2026 16:25:32 +1100 Subject: [PATCH 48/50] Test both stop handlers when the group refuses the signal graceful_stop and force_stop swallow EPERM from killpg unless a process of ours can still run in the group, but only group_alive's handling of the same answer was tested. Each handler now raises with a live member left and completes with only a zombie, and force_stop still waits for the child. --- scripts/tests/ci_process_contracts.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/scripts/tests/ci_process_contracts.py b/scripts/tests/ci_process_contracts.py index 4b0275b1..238e09ae 100644 --- a/scripts/tests/ci_process_contracts.py +++ b/scripts/tests/ci_process_contracts.py @@ -8,7 +8,7 @@ from tempfile import TemporaryDirectory from unittest.mock import MagicMock, Mock, patch -from lib.ci_process import command, command_logs, force_stop, group_alive +from lib.ci_process import command, command_logs, force_stop, graceful_stop, group_alive class CommandCleanupContract(unittest.TestCase): @@ -89,6 +89,22 @@ def test_permission_error_for_a_running_child_reads_whose_the_group_is(self): patch("lib.ci_process.subprocess.check_output", return_value=rows): self.assertEqual(group_alive(child), alive) + def test_a_refused_stop_signal_is_an_error_only_while_a_process_of_ours_can_run(self): + # The leader has exited, so killpg answers EPERM; what is left in the group decides. + for stopper in (graceful_stop, force_stop): + for state in ("S", "Z"): + child = Mock(pid=1234) + with self.subTest(stopper=stopper.__name__, state=state), \ + patch("lib.ci_process.os.killpg", side_effect=PermissionError), \ + patch("lib.ci_process.subprocess.check_output", return_value=f"1234 {os.getuid()} {state}\n"): + if state == "S": + with self.assertRaises(PermissionError): + stopper(child) + else: + stopper(child) + if stopper is force_stop: + child.wait.assert_called_once_with(timeout=10) + if __name__ == "__main__": unittest.main() From 1ef589bf69ebc43455058923d9894abebce4e59c Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Tue, 1 Dec 2026 16:52:10 +1100 Subject: [PATCH 49/50] Fail a point whose only failures are streams cut short A stream that ends without output and without an error was counted as part of a pool rejection on its own, though nothing in it says the pool ended it. It now counts only beside a request the server refused for a full KV pool; with no such request the point fails. All 24 distinct rejections recorded in the lab so far had cut-short streams beside full-pool refusals, and none had them alone. --- scripts/lib/performance_load.py | 6 +++++- scripts/tests/inference_performance_contracts.py | 4 ++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/scripts/lib/performance_load.py b/scripts/lib/performance_load.py index be711367..2793a22d 100644 --- a/scripts/lib/performance_load.py +++ b/scripts/lib/performance_load.py @@ -141,7 +141,8 @@ def rejection(directory, requests): an error event it counts as served and leaves without an output length: that request is cut short here. None when nothing failed, and None unless the export accounts for every measured request, so a load run that broke off is never taken for the server's answer. Any - other error is a fault, at this point as at every other: it raises. + other error is a fault, at this point as at every other: it raises. So do cut-short streams + when no request failed for a full pool, since nothing then shows the pool ended them. """ exports = list(directory.rglob("profile_export.jsonl")) if len(exports) != 1: @@ -159,6 +160,9 @@ def rejection(directory, requests): if unexplained: raise ValueError(f"{sum(failed[error] for error in unexplained)} of {requests} requests failed " f"with errors that are not a full KV pool, such as {json.loads(unexplained[0])}") + if not failed: + raise ValueError(f"{cut_short} of {requests} streams ended without output, " + "and no request failed for a full KV pool") return {"requests": requests, "failed": sum(failed.values()), "cut_short": cut_short, "errors": [{"error_details": json.loads(error), "count": count} for error, count in sorted(failed.items())]} diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index 19938fb5..1094d8fb 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -775,6 +775,10 @@ def test_only_a_full_pool_counts_as_a_rejection_and_any_other_error_fails_the_po self.write(directory, failed=[self.refused, unrelated], served=2) with self.assertRaisesRegex(ValueError, "1 of 4 requests failed with errors that are not a full KV pool"): rejection(Path(directory), 4) + with TemporaryDirectory() as directory: + self.write(directory, served=3, cut_short=1) + with self.assertRaisesRegex(ValueError, "1 of 4 streams ended without output"): + rejection(Path(directory), 4) def test_a_point_the_server_may_reject_keeps_what_it_rejected_in_place_of_metrics(self): from subprocess import CalledProcessError From 012401e0b3ddb346686e8ffbf7b80f318beaa6fa Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Tue, 1 Dec 2026 17:12:23 +1100 Subject: [PATCH 50/50] Take a pool rejection only where llama-server logged one AIPerf keeps llama-server's reason only for a refusal sent before the stream begins. A refusal sent mid-stream it records as an empty response, or as a stream without output, and other faults can leave either; both were taken for a full pool. llama-server logs "send_error: ... Context size has been exceeded." for every request its pool turns away. run_point now reads the lines the server logged while the point ran, and a rejection stands only if the server logged that refusal for every request failed or cut short and sent no other error. This replaces the check in 1ef589bf, which took a cut-short stream on the word of another request's error. In the 120 llama-server logs kept from lab jobs, every error a server sent was this refusal, and each of the 48 server runs with a recorded rejection logged at least as many refusals as it had requests failed or cut short. --- scripts/inference-performance.py | 2 +- scripts/lib/performance_load.py | 42 ++++++++--- .../tests/inference_performance_contracts.py | 74 ++++++++++++------- 3 files changed, 79 insertions(+), 39 deletions(-) diff --git a/scripts/inference-performance.py b/scripts/inference-performance.py index 3cab12df..2d300c28 100644 --- a/scripts/inference-performance.py +++ b/scripts/inference-performance.py @@ -397,7 +397,7 @@ def measure(built, help_text, model, inputs, key, index, server, shape, output, for point in server["points"]: metrics, rejected = run_point(ENDPOINT, point, coordinate, inputs["tokenizer_path"], shape["warmup_requests"], WORK / "aiperf" / name / point["id"], - may_reject=may_reject(built, server, point), + may_reject=may_reject(built, server, point), server_log=log, rate=request_rate(point, backend), context=context) # A rejection is the answer of a server that is still serving; one that died is a fault. if rejected is not None and process.poll() is not None: diff --git a/scripts/lib/performance_load.py b/scripts/lib/performance_load.py index 2793a22d..a578e07f 100644 --- a/scripts/lib/performance_load.py +++ b/scripts/lib/performance_load.py @@ -1,6 +1,7 @@ """Drive one load point with the pinned AIPerf and read back what it measured.""" import json +import re import shutil import subprocess import tempfile @@ -132,17 +133,28 @@ def measurements(export): # How llama-server's answer reads when the requests in flight need more KV than its pool holds: a 500 # naming the context or, mid-stream, an error event AIPerf records as a response without content. POOL_FULL = ("Context size has been exceeded", "No responses with actual content were received") +# The line llama-server logs for each error it sends a client, before the stream or within it. +SENT = re.compile(r"send_error: task id = \d+, error: (.*)") -def rejection(directory, requests): - """What the server failed among the measured requests, from AIPerf's per-request export. +def sent_errors(log, offset): + """The errors a server's log says it sent after its first `offset` bytes.""" + with log.open("rb") as stream: + stream.seek(offset) + return [found.group(1).strip() for found in SENT.finditer(stream.read().decode("utf-8", "replace"))] + + +def rejection(directory, requests, sent): + """What the server failed among the measured requests, from AIPerf's per-request export, + checked against `sent`, the errors the server logged sending while the point ran. AIPerf records an error for a request the server answers with one. A stream that ends on an error event it counts as served and leaves without an output length: that request is - cut short here. None when nothing failed, and None unless the export accounts for every - measured request, so a load run that broke off is never taken for the server's answer. Any - other error is a fault, at this point as at every other: it raises. So do cut-short streams - when no request failed for a full pool, since nothing then shows the pool ended them. + cut short here. Neither always keeps the server's reason, so the server must have logged a + full pool for every request failed or cut short. None when nothing failed, and None unless + the export accounts for every measured request, so a load run that broke off is never taken + for the server's answer. Any other error, in the export or the server's log, is a fault, at + this point as at every other: it raises. """ exports = list(directory.rglob("profile_export.jsonl")) if len(exports) != 1: @@ -160,17 +172,22 @@ def rejection(directory, requests): if unexplained: raise ValueError(f"{sum(failed[error] for error in unexplained)} of {requests} requests failed " f"with errors that are not a full KV pool, such as {json.loads(unexplained[0])}") - if not failed: - raise ValueError(f"{cut_short} of {requests} streams ended without output, " - "and no request failed for a full KV pool") + other = sorted({text for text in sent if POOL_FULL[0] not in text}) + if other: + raise ValueError(f"the server sent errors that are not a full KV pool, such as {other[0]!r}") + ended = sum(failed.values()) + cut_short + if len(sent) < ended: + raise ValueError(f"{ended} of {requests} requests failed or were cut short, but the server " + f"logged only {len(sent)} refusals for a full KV pool") return {"requests": requests, "failed": sum(failed.values()), "cut_short": cut_short, "errors": [{"error_details": json.loads(error), "count": count} for error, count in sorted(failed.items())]} -def run_point(endpoint, point, coordinate, tokenizer_path, warmup, directory: Path, *, may_reject, context, - rate=None): +def run_point(endpoint, point, coordinate, tokenizer_path, warmup, directory: Path, *, may_reject, server_log, + context, rate=None): """One point's metrics, or null metrics and what the server rejected where it may reject. + `server_log` is the server's log, whose lines from this point give its reasons for a rejection. `context` is a lane's, which every turn of a replayed AgentX trace must fit.""" failure, entry = None, dataset(point) if entry is None: @@ -186,6 +203,7 @@ def run_point(endpoint, point, coordinate, tokenizer_path, warmup, directory: Pa # limit (this Mac's "Application Support" tree) before AIPerf adds its own # nesting. Anchor a short, space-free TMPDIR at /tmp instead. short_tmp = Path(tempfile.mkdtemp(prefix="aiperf-tmp-", dir="/tmp")) + offset = server_log.stat().st_size try: command(args, timeout=5400, overrides={"TMPDIR": str(short_tmp)}) except subprocess.CalledProcessError as error: @@ -195,7 +213,7 @@ def run_point(endpoint, point, coordinate, tokenizer_path, warmup, directory: Pa shutil.rmtree(short_tmp, ignore_errors=True) if entry is not None: verify_corpus(corpus, directory.parent, f'{point["id"]}-after') - rejected = rejection(directory, point["requests"]) if may_reject else None + rejected = rejection(directory, point["requests"], sent_errors(server_log, offset)) if may_reject else None if rejected is not None: return dict.fromkeys(METRICS), rejected if failure is not None: diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index 1094d8fb..ee3487f3 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -224,9 +224,11 @@ def test_a_conversation_point_checks_its_pin_before_and_after_even_when_aiperf_f agentx = CONVERSATIONS["points"][0] with TemporaryDirectory() as directory, patch("lib.performance_load.verify_corpus") as verify, \ patch("lib.performance_load.command", side_effect=CalledProcessError(1, ["aiperf"])) as load: + log = Path(directory) / "server.log" + log.touch() with self.assertRaises(CalledProcessError): run_point("http://e", agentx, "m@r", "/t", 2, Path(directory) / "run" / agentx["id"], - may_reject=False, context=16384) + may_reject=False, server_log=log, context=16384) self.assertTrue((Path(directory) / "run").is_dir()) self.assertEqual([call.args[2] for call in verify.call_args_list], ["test-c1-agentx-before", "test-c1-agentx-after"]) @@ -728,6 +730,8 @@ class RejectionTests(unittest.TestCase): point = {"id": "c4-depth4096-pool16k", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 4} refused = {"code": 500, "type": "Internal Server Error", "message": "Context size has been exceeded."} + # what llama-server logs sending for each request its pool turns away + full = "Context size has been exceeded." summary = {"request_count": {"avg": 4}, "request_error_rate": {"avg": 0}, "error_summary": [], "is_complete": True, "output_token_throughput": {"avg": 120.5}} @@ -744,24 +748,39 @@ def request(phase, error, metrics): (Path(directory) / "profile_export.jsonl").write_text( "".join(json.dumps(record) + "\n" for record in records), encoding="utf-8") - def drive(self, directory, may_reject): - return run_point("http://127.0.0.1:9337", self.point, "org/m@rev", "/t", 2, Path(directory), - may_reject=may_reject, context=8192) + def drive(self, directory, may_reject, sent=(), fails=False): + """run_point with AIPerf faked: the server logs sending `sent` while the point runs, and + AIPerf exits non-zero, with no summary export, when every measured request failed.""" + from subprocess import CalledProcessError + log = Path(directory) / "server.log" + # an earlier point's error, which is not this point's answer + log.write_text("0.01.000.000 E srv send_error: task id = 0, error: Loading model\n", encoding="utf-8") + + def load(*_, **__): + with log.open("a", encoding="utf-8") as stream: + stream.writelines(f"0.47.014.510 E srv send_error: task id = {task}, error: {text}\n" + for task, text in enumerate(sent, 1)) + if fails: + raise CalledProcessError(1, ["aiperf"]) + + with patch("lib.performance_load.command", side_effect=load): + return run_point("http://127.0.0.1:9337", self.point, "org/m@rev", "/t", 2, Path(directory), + may_reject=may_reject, server_log=log, context=8192) def test_rejection_counts_failed_and_cut_short_requests_among_the_measured_ones(self): from tempfile import TemporaryDirectory other = dict(self.refused, code=503) with TemporaryDirectory() as directory: self.write(directory, failed=[self.refused, other, self.refused], cut_short=1) - self.assertEqual(rejection(Path(directory), 4), { + self.assertEqual(rejection(Path(directory), 4, [self.full] * 4), { "requests": 4, "failed": 3, "cut_short": 1, "errors": [{"error_details": self.refused, "count": 2}, {"error_details": other, "count": 1}]}) # A load run that broke off before every request is not the server's answer. - self.assertIsNone(rejection(Path(directory), 5)) + self.assertIsNone(rejection(Path(directory), 5, [self.full] * 4)) with TemporaryDirectory() as directory: - self.assertIsNone(rejection(Path(directory), 4)) + self.assertIsNone(rejection(Path(directory), 4, [])) self.write(directory, served=4) - self.assertIsNone(rejection(Path(directory), 4)) + self.assertIsNone(rejection(Path(directory), 4, [])) def test_only_a_full_pool_counts_as_a_rejection_and_any_other_error_fails_the_point(self): from tempfile import TemporaryDirectory @@ -770,33 +789,37 @@ def test_only_a_full_pool_counts_as_a_rejection_and_any_other_error_fails_the_po unrelated = {"code": 503, "type": "Service Unavailable", "message": "Loading model"} with TemporaryDirectory() as directory: self.write(directory, failed=[self.refused, empty_stream], served=2) - self.assertEqual(rejection(Path(directory), 4)["failed"], 2) + self.assertEqual(rejection(Path(directory), 4, [self.full] * 2)["failed"], 2) with TemporaryDirectory() as directory: self.write(directory, failed=[self.refused, unrelated], served=2) with self.assertRaisesRegex(ValueError, "1 of 4 requests failed with errors that are not a full KV pool"): - rejection(Path(directory), 4) + rejection(Path(directory), 4, [self.full] * 2) + + def test_every_request_failed_or_cut_short_needs_the_server_to_have_logged_a_full_pool(self): + from tempfile import TemporaryDirectory + # AIPerf keeps no reason for a stream the server ended part-way; the server's own log does. with TemporaryDirectory() as directory: self.write(directory, served=3, cut_short=1) - with self.assertRaisesRegex(ValueError, "1 of 4 streams ended without output"): - rejection(Path(directory), 4) + self.assertEqual(rejection(Path(directory), 4, [self.full])["cut_short"], 1) + with self.assertRaisesRegex(ValueError, "the server logged only 0 refusals"): + rejection(Path(directory), 4, []) + with self.assertRaisesRegex(ValueError, "the server sent errors that are not a full KV pool"): + rejection(Path(directory), 4, [self.full, "Invalid input batch."]) def test_a_point_the_server_may_reject_keeps_what_it_rejected_in_place_of_metrics(self): from subprocess import CalledProcessError from tempfile import TemporaryDirectory with TemporaryDirectory() as directory: self.write(directory, failed=[self.refused] * 4) - # AIPerf exits non-zero, with no summary export, when every measured request failed. - with patch("lib.performance_load.command", side_effect=CalledProcessError(1, ["aiperf"])): - metrics, rejected = self.drive(directory, may_reject=True) - self.assertEqual((metrics["output_tok_s"], set(metrics.values())), (None, {None})) - self.assertEqual((rejected["failed"], rejected["cut_short"]), (4, 0)) - with self.assertRaises(CalledProcessError): - self.drive(directory, may_reject=False) + metrics, rejected = self.drive(directory, may_reject=True, sent=[self.full] * 4, fails=True) + self.assertEqual((metrics["output_tok_s"], set(metrics.values())), (None, {None})) + self.assertEqual((rejected["failed"], rejected["cut_short"]), (4, 0)) + with self.assertRaises(CalledProcessError): + self.drive(directory, may_reject=False, fails=True) with TemporaryDirectory() as directory: self.write(directory, failed=[self.refused], served=2, cut_short=1) (Path(directory) / "profile_export_aiperf.json").write_text(json.dumps(self.summary)) - with patch("lib.performance_load.command"): - self.assertEqual(self.drive(directory, may_reject=True)[1]["cut_short"], 1) + self.assertEqual(self.drive(directory, may_reject=True, sent=[self.full] * 2)[1]["cut_short"], 1) def test_a_point_the_server_served_is_measured_and_a_broken_load_run_still_fails(self): from subprocess import CalledProcessError @@ -804,12 +827,10 @@ def test_a_point_the_server_served_is_measured_and_a_broken_load_run_still_fails with TemporaryDirectory() as directory: self.write(directory, served=4) (Path(directory) / "profile_export_aiperf.json").write_text(json.dumps(self.summary)) - with patch("lib.performance_load.command"): - metrics, rejected = self.drive(directory, may_reject=True) + metrics, rejected = self.drive(directory, may_reject=True) self.assertEqual((metrics["output_tok_s"], rejected), (120.5, None)) - with patch("lib.performance_load.command", side_effect=CalledProcessError(1, ["aiperf"])): - with self.assertRaises(CalledProcessError): - self.drive(directory, may_reject=True) + with self.assertRaises(CalledProcessError): + self.drive(directory, may_reject=True, fails=True) def test_a_rejected_point_is_a_sample_only_while_its_server_stays_up(self): from tempfile import TemporaryDirectory @@ -827,6 +848,7 @@ def test_a_rejected_point_is_a_sample_only_while_its_server_stays_up(self): sample, = measure(built, "", "/m.gguf", inputs, "m", 0, server, shape, Path(directory)) self.assertEqual((sample["rejected"], sample["metrics"]), (rejected, {"output_tok_s": None})) self.assertTrue(load.call_args.kwargs["may_reject"]) + self.assertEqual(load.call_args.kwargs["server_log"].suffix, ".log") process.poll.return_value = 1 with self.assertRaisesRegex(RuntimeError, "exited while it was rejecting"): measure(built, "", "/m.gguf", inputs, "m", 0, server, shape, Path(directory))