From 0f349b6726c3ec2aa5f2df4efbd3bc36d5f415a0 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sat, 28 Nov 2026 08:28:42 +1100 Subject: [PATCH 01/22] Compare inference revisions on fixed hardware with calibrated intervals --- .gi/templates.yaml | 26 ++- .github/workflows/inference.yml | 6 +- Justfile | 4 + ci/README.md | 40 +++++ ci/automation.just | 2 + scripts/inference-dispatch.py | 16 +- scripts/inference-execute.py | 7 +- scripts/inference-paired.py | 189 ++++++++++++++++++++ scripts/inference-plan.py | 6 +- scripts/inference-report.sh | 21 +-- scripts/lib/inference-report-baseline.sh | 144 ++++----------- scripts/lib/inference_paired_collect.py | 53 ++++++ scripts/lib/inference_pairs.py | 100 +++++++++++ scripts/lib/inference_probe.py | 23 ++- scripts/lib/inference_rendezvous.py | 97 ++++++++++ scripts/tests/inference-report.sh | 108 +++-------- scripts/tests/inference_paired_execution.py | 99 ++++++++++ scripts/tests/inference_pairs.py | 168 +++++++++++++++++ scripts/tests/inference_probe.py | 7 + 19 files changed, 894 insertions(+), 222 deletions(-) create mode 100644 scripts/inference-paired.py create mode 100644 scripts/lib/inference_paired_collect.py create mode 100644 scripts/lib/inference_pairs.py create mode 100644 scripts/lib/inference_rendezvous.py create mode 100644 scripts/tests/inference_paired_execution.py create mode 100644 scripts/tests/inference_pairs.py diff --git a/.gi/templates.yaml b/.gi/templates.yaml index 1feb732c..b9c73855 100644 --- a/.gi/templates.yaml +++ b/.gi/templates.yaml @@ -513,7 +513,7 @@ } }, { - "name": "Short Spark PR inference smoke", + "name": "Paired Spark PR inference qualification", "group": "Inference", "target": { "executor": "lab", @@ -640,23 +640,30 @@ } ], "default": "Qwen3.5-4B" + }, + { + "key": "baseline_sha", + "label": "Admitted main commit", + "kind": "text", + "required": true, + "default": "legacy" } ], "budget": { "max_usd": 0, - "max_duration_s": 1800, + "max_duration_s": 14400, "grace_s": 60 }, "retain": "never", "key": "inference-pr-standalone", - "command": "cd \"$JIANYANG_REPO_DIR\" && just inference-execute ${profile} ${model_key} standalone", + "command": "cd \"$JIANYANG_REPO_DIR\" && just inference-paired ${model_key} standalone ${baseline_sha}", "env": { "HF_HOME": "/mnt/model-store/huggingface", "HF_HUB_CACHE": "/mnt/model-store/huggingface/hub" } }, { - "name": "Short Spark PR inference smoke", + "name": "Paired Spark PR inference qualification", "group": "Inference", "target": { "executor": "lab", @@ -895,16 +902,23 @@ "label": "spark-001272" } ] + }, + { + "key": "baseline_sha", + "label": "Admitted main commit", + "kind": "text", + "required": true, + "default": "legacy" } ], "budget": { "max_usd": 0, - "max_duration_s": 1800, + "max_duration_s": 14400, "grace_s": 60 }, "retain": "never", "key": "inference-pr-split", - "command": "cd \"$JIANYANG_REPO_DIR\" && just inference-execute ${profile} ${model_key} split", + "command": "cd \"$JIANYANG_REPO_DIR\" && just inference-paired ${model_key} split ${baseline_sha}", "roles": [ { "name": "leader", diff --git a/.github/workflows/inference.yml b/.github/workflows/inference.yml index 4e1df0dc..4610da1f 100644 --- a/.github/workflows/inference.yml +++ b/.github/workflows/inference.yml @@ -98,6 +98,7 @@ jobs: outputs: source: ${{ steps.admission.outputs.source || github.event.pull_request.head.sha || github.event.workflow_run.head_sha || github.sha }} profile: ${{ steps.admission.outputs.profile || 'pr' }} + baseline: ${{ steps.admission.outputs.baseline || steps.admission.outputs.source }} matrix: ${{ steps.matrix.outputs.matrix }} steps: # Credentialed controller source always comes from protected main. @@ -131,7 +132,7 @@ jobs: max-parallel: 3 matrix: ${{ fromJSON(needs.plan.outputs.matrix) }} runs-on: ${{ vars.SKIPPY_DEPOT_RUNNERS_ENABLED == 'true' && 'depot-ubuntu-24.04-4' || 'ubuntu-24.04' }} - timeout-minutes: ${{ matrix.profile == 'pr' && 100 || 360 }} + timeout-minutes: ${{ matrix.profile == 'pr' && 260 || 360 }} env: EVIDENCE: target/ci-evidence/inference-${{ matrix.id }} steps: @@ -145,11 +146,13 @@ jobs: SOURCE_SHA: ${{ needs.plan.outputs.source }} PROFILE: ${{ matrix.profile }} CONFIGURATION: ${{ matrix.configuration }} + BASELINE_SHA: ${{ needs.plan.outputs.baseline }} NIGHTLY_PUBLICATION: ${{ needs.plan.outputs.profile == 'nightly' && github.event_name == 'schedule' && github.ref == 'refs/heads/main' && github.repository == 'Mesh-LLM/skippy' }} JIANYANG_INFERENCE_SSH_KEY: ${{ secrets.JIANYANG_INFERENCE_SSH_KEY }} run: | flags=() if [[ "$NIGHTLY_PUBLICATION" == true ]]; then flags+=(--collect-public); fi + if [[ "$PROFILE" == pr ]]; then flags+=(--baseline "$BASELINE_SHA"); fi just inference-dispatch "$PROFILE" "$SOURCE_SHA" "$EVIDENCE" "$CONFIGURATION" "${flags[@]}" - name: Cancel outstanding JY jobs and formations if: cancelled() || failure() @@ -270,6 +273,7 @@ jobs: env: GH_TOKEN: ${{ github.token }} SOURCE_SHA: ${{ needs.plan.outputs.source || github.event.pull_request.head.sha }} + BASELINE_SHA: ${{ needs.plan.outputs.baseline }} PLAN: ${{ needs.plan.result }} REQUIRED: 'true' RESULT: ${{ needs.qualification.result }} diff --git a/Justfile b/Justfile index c7954141..c320ac37 100644 --- a/Justfile +++ b/Justfile @@ -200,6 +200,10 @@ inference-dispatch profile source output="target/ci-evidence/inference" *configu inference-execute profile model mode: @"{{ automation_python }}" scripts/inference-execute.py "$@" +[positional-arguments] +inference-paired model mode baseline: + @"{{ automation_python }}" scripts/inference-paired.py "$@" + [positional-arguments] inference-cancel ledger="target/ci-evidence/inference/jobs.json": @"{{ automation_python }}" scripts/inference-dispatch.py cancel "$@" diff --git a/ci/README.md b/ci/README.md index 08d2f13a..933b8e82 100644 --- a/ci/README.md +++ b/ci/README.md @@ -172,6 +172,46 @@ The lab-results comment uses `scripts/inference-report.sh` with hosted-runner configuration and native-attempt identity, updates only its bot-owned comment, and refuses to replace results for a newer commit or workflow attempt. +PR throughput comparisons pin current protected main during admission, regardless +of the latest nightly outcome. Each PR-profile native job builds that main commit +in a separate disposable worktree and retains the candidate build. Both revisions +run inside the same exclusive job or atomic two-Spark formation. The two roles +keep their placement and wait at a barrier after each restarted server arm. +Build hashes, source commits, host/kernel/driver identities, raw responses and +client timings remain in the lab evidence. All builds finish before measurement. + +The fixed design runs six main/main pairs for noise calibration, followed by six +main/candidate pairs, alternating A/B and B/A order. Every arm repeats each of +the three prompt shapes three times. A shape-matched 64-token warmup precedes +each uncached 128-token measured response at concurrency one. Prefixes differ +between repetitions; cached or truncated responses invalidate the evidence. +Quality, offload, streaming and native split admission checks run for every arm. +No changes to the workload fixtures are accepted between the two revisions. + +The controller recomputes per-shape server-phase rates and paired log-ratio +Student-t intervals (six pairs, df=5, pointwise 95%). It does not treat nested +requests as independent rounds or combine different prompt lengths. A/A noise +is the maximum absolute log-interval endpoint, converted back to a percentage. +A performance verdict requires the candidate interval to clear that envelope; +an A/A interval excluding equality, or an envelope above 5%, makes the comparison +inconclusive. These per-metric intervals have no matrix-wide multiplicity +correction. Qualification still tests correctness and complete evidence; +inconclusive performance is not a claimed win or loss. The PR table reports the +interval and noise alongside each estimate. Historical runs never replace a +missing paired comparison. + +Scheduled PR-profile smoke rows run the same design with main in both arms; +their paired receipts retain the noise check in Actions artifacts. The twelve +AgentX workloads and their saved historical baseline policy are separate. +The paired native budget is four hours, with additional controller cleanup time. +Offline protocol, statistics and reporting checks run with `just ci-automation`. +They do not establish device qualification or a measured noise floor. + +Deployment requires the protected controller to reach main and JY's installed +`.gi/templates.yaml` definitions to be synced. Before that controller is merged, +old controllers retain their legacy smoke behavior through the template's +explicit `legacy` default; they cannot produce a paired comparison receipt. + The shared report renderer takes normalized qualification JSON. It renders Mermaid charts for Actions summaries and saves the Hugging Face card’s PNG charts in `charts/` beside its README. PNG export uses the reporting diff --git a/ci/automation.just b/ci/automation.just index d2a7461d..44a9c53d 100644 --- a/ci/automation.just +++ b/ci/automation.just @@ -8,6 +8,8 @@ inference-contracts: @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_build.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_contracts.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_probe.py + @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_pairs.py + @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_paired_execution.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/jy_read_recovery.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_markdown.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_nightly.py diff --git a/scripts/inference-dispatch.py b/scripts/inference-dispatch.py index 476ba77a..36530e5c 100644 --- a/scripts/inference-dispatch.py +++ b/scripts/inference-dispatch.py @@ -16,6 +16,7 @@ from lib.inference_nightly_metrics import collect_nightly from lib.inference_throughput import collect from lib.jy_qualification import Pilot, placement +from lib.inference_paired_collect import collect_pairs TERMINAL = {"succeeded", "failed", "cancelled", "expired"} FAILURE = TERMINAL - {"succeeded"} @@ -119,8 +120,12 @@ def record(ledger, identifiers): temporary.unlink(missing_ok=True) -def dispatch(pilot, profile, sha, output, configuration, collect_public=False): +def dispatch(pilot, profile, sha, output, configuration, collect_public=False, baseline=None): result = plan(profile, sha) + if profile == "pr": + if baseline is None or not re.fullmatch(r"[0-9a-f]{40}", baseline): + raise ValueError("PR comparisons require an admitted immutable main SHA") + result["baseline_sha"] = baseline if configuration is not None: result["rows"] = [row for row in result["rows"] if row["id"] == configuration] if len(result["rows"]) != 1: @@ -133,7 +138,7 @@ def dispatch(pilot, profile, sha, output, configuration, collect_public=False): # Manual qualification may queue behind another PR's atomic Spark pair; # a PR profile waits for placement instead of failing fast, and the job # timeout in inference.yml carries the same headroom. - deadline = time.monotonic() + (5400 if profile == "pr" else 21000) + deadline = time.monotonic() + (15000 if profile == "pr" else 21000) try: for row in result["rows"]: identity, mode = row["id"], row["mode"] @@ -147,6 +152,8 @@ def dispatch(pilot, profile, sha, output, configuration, collect_public=False): "model_key": model_key}, "idempotency_key": f"inference-{run_id}-{profile}-{attempt}-{identity}-{sha}", } + if profile == "pr": + body["inputs"]["baseline_sha"] = baseline launched = launch(pilot, f"/v1/repos/skippy/templates/{template}/launch", body, deadline, mode == "split") handle = resource_id(launched.get("job_id")) @@ -154,6 +161,8 @@ def dispatch(pilot, profile, sha, output, configuration, collect_public=False): record(ledger, identifiers) write_json(output / f"{identity}-launch.json", launched) job = wait(pilot, handle, identity, sha, output, deadline) + if profile == "pr": + collect_pairs(pilot, job, row, sha, baseline, output) if collect_public: collect_nightly(pilot, job, row, sha, output, model_key, profile) elif profile == "pr": @@ -178,12 +187,13 @@ def main(): action.add_argument("output", type=Path) action.add_argument("configuration", nargs="?") action.add_argument("--collect-public", action="store_true") + action.add_argument("--baseline", help="Protected admission's immutable main SHA") actions.add_parser("cancel").add_argument("ledger", type=Path) actions.add_parser("control-preflight") args = parser.parse_args() pilot = Pilot() if args.action == "dispatch": - dispatch(pilot, args.profile, args.sha, args.output, args.configuration, args.collect_public) + dispatch(pilot, args.profile, args.sha, args.output, args.configuration, args.collect_public, args.baseline) elif args.action == "cancel": cancel(pilot, args.ledger) else: diff --git a/scripts/inference-execute.py b/scripts/inference-execute.py index 92bd9f0b..db833ccb 100644 --- a/scripts/inference-execute.py +++ b/scripts/inference-execute.py @@ -117,7 +117,7 @@ def acknowledge_worker(): connection.sendall(b"HTTP/1.1 200 OK\r\nContent-Length: 22\r\nConnection: close\r\n\r\n" + body) -def execute(profile, key, mode): +def execute(profile, key, mode, repetitions=1): sha, gpu = authority() result = plan(profile, sha) if not any(row["id"] == f"{key}-{mode}" for row in result["rows"]): @@ -161,7 +161,10 @@ def execute(profile, key, mode): score(coordinate, output, profile) if profile == "pr": streaming(coordinate, output) - measure(coordinate, output) + for repetition in range(repetitions): + probe_output = output if repetition == 0 else output / f"probe-{repetition}" + probe_output.mkdir(parents=True, exist_ok=True) + measure(coordinate, probe_output, repetition if repetitions > 1 else None) scope = "GPU startup, deterministic endpoint repeats and bounded streaming smoke" else: performance(profile, coordinate, context, output, inputs) diff --git a/scripts/inference-paired.py b/scripts/inference-paired.py new file mode 100644 index 00000000..8f91c6be --- /dev/null +++ b/scripts/inference-paired.py @@ -0,0 +1,189 @@ +#!/usr/bin/env python3 +"""Compare pinned main and candidate on the current exclusive JY allocation.""" + +import argparse +import json +import os +import platform +import re +import shutil +import subprocess +import sys +import tempfile +from contextlib import contextmanager, nullcontext +from pathlib import Path +from runpy import run_path + +from lib.ci_artifacts import digest, read_json, write_json +from lib.ci_process import DEADLINE, cancel_on_signal, capture, command, time_budget +from lib.inference_pairs import PROTOCOL, REPETITIONS, ROUNDS, schedule, summarize +from lib.inference_probe import validate_evidence +from lib.inference_rendezvous import Coordinator, await_condition, exchange, worker_state + +ROOT = Path(__file__).resolve().parents[1] +EXECUTE = run_path(str(ROOT / "scripts/inference-execute.py"))["execute"] + + +@contextmanager +def revision(directory, sha, output): + previous, environment = Path.cwd(), os.environ.copy() + os.chdir(directory) + os.environ.update(JIANYANG_COMMIT=sha, JIANYANG_REPO_DIR=str(directory), + JIANYANG_ARTIFACT_DIR=str(output)) + try: + yield + finally: + os.chdir(previous) + os.environ.clear() + os.environ.update(environment) + + +@contextmanager +def baseline_tree(sha): + if not re.fullmatch(r"[0-9a-f]{40}", sha): + raise ValueError("comparison main must be an immutable commit") + with tempfile.TemporaryDirectory(prefix="skippy-main-", dir=ROOT / "target") as temporary: + directory = Path(temporary) / "source" + try: + command(["git", "cat-file", "-e", sha + "^{commit}"], timeout=30) + except subprocess.CalledProcessError: + command(["git", "fetch", "--no-tags", "https://github.com/Mesh-LLM/skippy.git", sha], timeout=180) + command(["git", "worktree", "add", "--detach", str(directory), sha], timeout=60) + try: + yield directory + finally: + # Cleanup keeps its own bounded budget even when measurement expired. + token = DEADLINE.set(None) + try: + command(["git", "worktree", "remove", "--force", str(directory)], timeout=120) + finally: + DEADLINE.reset(token) + + +def host(role, node): + return {"role": role, "node": node, "hostname": platform.node(), + "kernel": platform.release(), "arch": platform.machine(), + "gpu": capture(["nvidia-smi", "--query-gpu=name,driver_version", "--format=csv,noheader"]).strip()} + + +def samples(directory, coordinate): + result = [] + for repetition in range(REPETITIONS): + path = directory if repetition == 0 else directory / f"probe-{repetition}" + responses = validate_evidence(read_json(path / "throughput-probe.json"), coordinate) + for shape, response in enumerate(responses): + timing = response["timings"] + result.append({"shape": shape, "prefill_tokens": timing["prompt_n"], + "prefill_ms": timing["prompt_ms"], "decode_tokens": timing["predicted_n"], + "decode_ms": timing["predicted_ms"]}) + return result + + +def prepare(main, baseline, candidate, output): + # Both arms use this harness, one workload and the exact same model bytes. + for path in ("ci/inference-artifacts.json", "ci/inference-quality.json"): + if digest(ROOT / path) != digest(main / path): + raise ValueError("paired comparison model or quality fixtures changed") + with revision(main, baseline, output): + command(["just", "inference-build"], timeout=7200) + identities = {"main": read_json(main / "target/inference-build.json"), + "candidate": read_json(ROOT / "target/inference-build.json")} + if identities["main"]["stack_commit"] != baseline or identities["candidate"]["stack_commit"] != candidate: + raise ValueError("paired comparison executable source mismatch") + return identities + + +def run_arm(design, main, baseline, key, mode, output): + directory = output / f'{design["experiment"]}-{design["round"]}-{design["arm"]}' + directory.mkdir() + source = main if design["source_sha"] == baseline else ROOT + with revision(source, design["source_sha"], directory): + EXECUTE("pr", key, mode, REPETITIONS) + return directory + + +def worker(origin, designs, main, baseline, key, output, identity): + worker_state(origin) + exchange(origin, "/ready", identity) + try: + for index, design in enumerate(designs): + def ready(): + state = exchange(origin, "/state") + if state["complete"] or state["error"]: + raise RuntimeError("paired inference leader stopped") + return state["index"] == index + await_condition(ready) + run_arm(design, main, baseline, key, "split", output) + exchange(origin, "/done", {"index": index}) + except BaseException: + exchange(origin, "/error", {"failed": True}) + raise + + +def execute(key, mode, baseline): + # Old protected controllers can encounter a PR's provisional template before + # this controller reaches main. Preserve their original smoke protocol. + if baseline == "legacy": + EXECUTE("pr", key, mode) + return + candidate = os.environ["JIANYANG_COMMIT"] + if capture(["git", "rev-parse", "HEAD"]).strip() != candidate: + raise ValueError("paired comparison candidate differs from JY admission") + output = Path(os.environ["JIANYANG_ARTIFACT_DIR"]).resolve() + output.mkdir(parents=True, exist_ok=True) + peers = json.loads(os.environ["JIANYANG_PEERS"]) if mode == "split" else [] + role = os.environ.get("JIANYANG_ROLE", "leader") + node = next((p["node"] for p in peers if p["role"] == role), platform.node()) + with baseline_tree(baseline) as main: + identities = prepare(main, baseline, candidate, output) + local = host(role, node) + designs = schedule(baseline, candidate) + if role == "worker": + leader = next(p["host"] for p in peers if p["role"] == "leader") + origin = f"http://[{leader}]:9913" if ":" in leader else f"http://{leader}:9913" + worker(origin, designs, main, baseline, key, output, {"host": local, "builds": identities}) + return + remote = next((p["host"] for p in peers if p["role"] == "worker"), None) + with Coordinator(remote) if remote else nullcontext() as coordinator: + placements = [local] + builds = [{"role": role, **identities}] + if coordinator: + ready = coordinator.wait(lambda s: s["worker"], seconds=7200) + placements.append(ready["host"]) + builds.append({"role": "worker", **ready["builds"]}) + evidence = {"schema_version": 1, "protocol": PROTOCOL, "source_sha": candidate, + "baseline_sha": baseline, "configuration": f"{key}-{mode}", "rounds": ROUNDS, + "repetitions": REPETITIONS, "placements": placements, "builds": builds, "runs": []} + try: + for index, design in enumerate(designs): + if coordinator: + coordinator.state["index"] = index + directory = run_arm(design, main, baseline, key, mode, output) + if coordinator: + coordinator.wait(lambda s: s["done"] == index) + coordinate = read_json(ROOT / "ci/inference-artifacts.json")[key] + coordinate = f'{coordinate["repo"]}@{coordinate["revision"]}' + evidence["runs"].append({**design, "placements": placements, "quality": "passed", + "samples": samples(directory, coordinate)}) + # Preserve the existing standalone nightly smoke receipts too. + if design["experiment"] == "ab" and design["arm"] == "b": + for name in ("qualification.json", "quality.json", "throughput-probe.json", + "provenance.json", "split-admissions.json"): + if (directory / name).is_file(): + shutil.copyfile(directory / name, output / name) + evidence["summary"] = summarize(evidence, candidate, baseline, f"{key}-{mode}") + finally: + write_json(output / "paired-probe.json", evidence) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("model") + parser.add_argument("mode", choices=("standalone", "split")) + parser.add_argument("baseline") + args = parser.parse_args() + try: + with cancel_on_signal(), time_budget(14400): + execute(args.model, args.mode, args.baseline) + except (OSError, ValueError, KeyError, RuntimeError, subprocess.SubprocessError, KeyboardInterrupt) as error: + sys.exit(str(error)) diff --git a/scripts/inference-plan.py b/scripts/inference-plan.py index ddfd93f5..38a51165 100644 --- a/scripts/inference-plan.py +++ b/scripts/inference-plan.py @@ -97,7 +97,11 @@ def admit(): plan(profile, sha) if is_pr: admit_pr(sha) - output(source=sha, profile=profile) + # Pin main independently of nightly success. Never use a moving ref on a + # native worker or select the baseline by its measured performance. + baseline = github(f"repos/{REPO}/git/ref/heads/main")["object"]["sha"] if is_pr else sha + plan(profile, baseline) + output(source=sha, profile=profile, baseline=baseline) def main(): diff --git a/scripts/inference-report.sh b/scripts/inference-report.sh index e912d7ea..d4e972f6 100644 --- a/scripts/inference-report.sh +++ b/scripts/inference-report.sh @@ -47,7 +47,7 @@ fi # shellcheck source=scripts/lib/inference-report-baseline.sh source "$root/scripts/lib/inference-report-baseline.sh" -prepare_baseline +baseline_note=$(prepare_baseline) cat > "$temporary/body.md" <> "$temporary/body.md" + continue + fi if [[ $state == Passed && -f $rates ]]; then # Invalid current evidence remains a reporting failure, not an unavailable baseline. validate_rates "$rates" "$receipt" "$SOURCE_SHA" "$row" || fail 'Comment throughput evidence identity mismatch' @@ -112,20 +117,16 @@ while IFS= read -r row; do if jq -e '.workload == "DGX Spark warm probe v2"' "$rates" > /dev/null; then prefill=$(rate "$rates" prefill) decode=$(rate "$rates" decode) - if baseline=$(baseline_for_row "$row" 2> /dev/null); then - prefill_delta=$(delta "$rates" "$baseline/$row-throughput.json" prefill "$receipt" "$baseline/$row-job.json") - decode_delta=$(delta "$rates" "$baseline/$row-throughput.json" decode "$receipt" "$baseline/$row-job.json") - fi fi fi - printf "| \`%s\` | %s | %s | %s | %s | %s | %s | %s |\n" "$row" "$state" "$prefill" "$prefill_delta" "$decode" "$decode_delta" "$action" "$lab" >> "$temporary/body.md" + printf "| \`%s\` | %s | %s | %s | %s | %s | Unavailable | %s | %s |\n" "$row" "$state" "$prefill" "$prefill_delta" "$decode" "$decode_delta" "$action" "$lab" >> "$temporary/body.md" done < "$temporary/rows.txt" cat >> "$temporary/body.md" <<'EOF' -TPS comes from three separate warmed, uncached probes at concurrency 1, each generating exactly 128 tokens. The scored correctness answers and each probe's 64-token warmup are excluded. Each rate is total tokens / total server-reported phase time, not an average of request rates. Client elapsed times and raw responses are retained in throughput-probe.json. These bounded samples are not sustained benchmarks or controlled speedup comparisons. Legacy short-answer receipts and missing or invalid probe evidence show as Unavailable. +Paired measurements run six main/main pairs, then six main/PR pairs, alternating A/B and B/A order. Every arm restarts the server and repeats each of three prompt shapes three times, with an uncached 64-token warmup and exactly 128 measured output tokens per request at concurrency 1. Correctness and streaming checks must pass for every arm. Each shape is reported separately. -Deltas use unrounded rates from matching PR-profile smoke receipts on the latest successful main run, including the nightly smoke evidence. Positive means faster. Changed workload inputs, different serving host classes, unequal phase token counts or missing evidence show Unavailable. Physical Spark placement and runtime conditions can differ; deltas are descriptive, not controlled speedup claims. +Rates are diagnostic server phase timings, not end-to-end client throughput. Each round rate is total tokens / total phase time; the table shows geometric mean rates and paired geometric ratios. Pointwise 95% Student-t intervals use six server-pair log ratios (df=5); nested requests are not independent trials. Raw responses, client times, build provenance, and placements are retained in lab evidence. A/A noise is the largest absolute log-interval bound, converted to a percentage. Improvement/regression requires the PR interval to clear that noise envelope. An A/A interval excluding equality or an envelope above 5% makes the comparison inconclusive. Intervals are per shape/phase, without a matrix-wide multiple-comparison correction. Missing paired evidence gives no delta; saved historical main runs are never substituted. Smoke checks cover GPU startup, deterministic endpoint repeats and bounded streaming. They do not establish an AgentX performance score. [Nightly history and saved performance baselines](https://huggingface.co/datasets/meshllm/skippy-inference-qualification) are published separately; a saved baseline can be older than the latest successful main run used here. The lab retains native results and logs. GitHub evidence copies expire after 30 days. EOF diff --git a/scripts/lib/inference-report-baseline.sh b/scripts/lib/inference-report-baseline.sh index 6fbe42f1..efb69d51 100644 --- a/scripts/lib/inference-report-baseline.sh +++ b/scripts/lib/inference-report-baseline.sh @@ -1,124 +1,50 @@ #!/usr/bin/env bash -# Protected reporter helpers. Downloaded evidence and candidate trees are data only. -: "${repository:?Reporter repository required}" "${temporary:?Reporter workspace required}" +# Protected paired-result formatter. Candidate/native receipts are data only. validate_rates() { jq -e --arg sha "$3" --arg row "$4" --slurpfile job "$2" ' - def uint: type == "number" and . >= 0 and . == floor and . < 18446744073709551616; - ((keys - ["workload"]) == (["source_sha", "configuration", "job_id", "run_id", "requests", - "prefill_tokens", "prefill_ms", "decode_tokens", "decode_ms"] | sort)) and - (if has("workload") then - .workload == "DGX Spark warm probe v2" and .decode_tokens == 384 - else true end) and .source_sha == $sha and .configuration == $row and .requests == 3 and - (.prefill_tokens | uint) and (.decode_tokens | uint) and - (.prefill_ms | type == "number") and (.decode_ms | type == "number") and $job[0].repo_rev == $sha and $job[0].status == "succeeded" and - (.job_id | type == "string" and test("^job_[A-Za-z0-9_]+$")) and .job_id == $job[0].id and .run_id == $job[0].runs[-1].id and $job[0].runs[-1].status == "succeeded" and - (.run_id | type == "string" and test("^run_[A-Za-z0-9_]+$")) + (.job_id | type == "string" and test("^job_[A-Za-z0-9_]+$")) and + (.run_id | type == "string" and test("^run_[A-Za-z0-9_]+$")) and + (if has("workload") then .workload == "DGX Spark warm probe v2" and .decode_tokens == 384 else true end) ' "$1" > /dev/null } prepare_baseline() { - baseline_ready=false - baseline_note='Main comparison unavailable: no readable successful main run.' - # Filter again locally: a PR can name its branch main, but is not a main run. - if ! gh api "$repository/actions/workflows/inference.yml/runs?branch=main&status=success&per_page=100" \ - --paginate --slurp > "$temporary/main-runs.json"; then return; fi - if ! jq -e ' - [.[] | .workflow_runs[] | select(.head_branch == "main" and .conclusion == "success") | - select(.event == "schedule" or .event == "workflow_dispatch" or .event == "push") ] | - sort_by(.created_at, .id) | last | - select(.id > 0 and .id == (.id | floor) and - .run_attempt > 0 and .run_attempt == (.run_attempt | floor) and - (.head_sha | type == "string" and test("^[a-fA-F0-9]{40}$"))) - ' "$temporary/main-runs.json" > "$temporary/main-run.json"; then return; fi - baseline_run=$(jq -r .id "$temporary/main-run.json") - baseline_attempt=$(jq -r .run_attempt "$temporary/main-run.json") - baseline_sha=$(jq -r .head_sha "$temporary/main-run.json") - baseline_url="https://github.com/Mesh-LLM/skippy/actions/runs/$baseline_run/attempts/$baseline_attempt" - baseline_note="Latest successful main: [run $baseline_run, attempt $baseline_attempt]($baseline_url), commit \`$baseline_sha\`." - # Compare workload inputs by blob identity without fetching/executing PR code. - # Engine sources are intentionally excluded: their performance is being measured. - local inputs - inputs='["scripts/inference-execute.py", "scripts/lib/inference_checks.py", - "scripts/lib/inference_throughput.py", "scripts/lib/inference_probe.py", "scripts/lib/inference_inputs.py", - "scripts/lib/inference_ladder.py", "scripts/lib/ci_artifacts.py", - "scripts/lib/ci_process.py", "scripts/lib/ci_smoke.py", - "ci/inference-quality.json", "ci/inference-artifacts.json", ".gi/templates.yaml"]' - if ! gh api "$repository/git/trees/$SOURCE_SHA?recursive=1" > "$temporary/current-tree.json" || - ! gh api "$repository/git/trees/$baseline_sha?recursive=1" > "$temporary/main-tree.json" || - ! jq -e --argjson inputs "$inputs" --slurpfile main "$temporary/main-tree.json" ' - def contract: - if .truncated == false then - [.tree[] | select(.type == "blob") | select(.path as $p | $inputs | index($p)) | - {path, sha}] | sort_by(.path) - else [] end; - contract as $current | ($main[0] | contract) as $previous | - ($current | length) == ($inputs | length) and $current == $previous - ' "$temporary/current-tree.json" > /dev/null; then - baseline_note+=' Comparison unavailable: workload inputs changed or could not be verified.' - return - fi - if ! gh api "$repository/actions/runs/$baseline_run/attempts/$baseline_attempt/jobs?per_page=100" \ - --paginate --slurp | jq -e '[.[] | .jobs[]]' > "$temporary/main-jobs.json" || - ! gh run download "$baseline_run" --repo Mesh-LLM/skippy \ - --pattern "inference-*-$baseline_run-$baseline_attempt" --dir "$temporary/baseline"; then - baseline_note+=' Comparison unavailable: saved evidence is missing, expired or unreadable.' - return - fi - baseline_ready=true -} - -baseline_for_row() { - [[ $baseline_ready == true ]] || return 1 - local id=$1 candidate found='' name - # Nightly adds smoke-$id artifacts; AgentX artifacts must never supply PR rates. - for name in "$id" "smoke-$id"; do - candidate="$temporary/baseline/inference-$name-$baseline_run-$baseline_attempt" - [[ -f $candidate/$id-throughput.json ]] || continue - [[ -z $found ]] || return 1 - jq -e --arg name "qualification ($name)" ' - any(.[]; .name == $name and .conclusion == "success") - ' "$temporary/main-jobs.json" > /dev/null || return 1 - jq -e --arg sha "$baseline_sha" --arg row "$id" ' - .schema_version == 1 and .source_sha == $sha and .profile == "pr" and - .hardware == "nvidia-gb10-dgx-spark" and - (.rows | length) == 1 and .rows[0].id == $row and - (if ($row | endswith("-split")) then .rows[0].mode == "split" and .rows[0].machines == 2 - else .rows[0].mode == "standalone" and .rows[0].machines == 1 end) - ' "$candidate/plan.json" > /dev/null || return 1 - validate_rates "$candidate/$id-throughput.json" "$candidate/$id-job.json" "$baseline_sha" "$id" || return 1 - jq -e '.workload == "DGX Spark warm probe v2"' "$candidate/$id-throughput.json" > /dev/null || return 1 - found=$candidate - done - [[ -n $found ]] || return 1 - printf '%s' "$found" + [[ ${BASELINE_SHA:-} =~ ^[a-f0-9]{40}$ ]] || fail 'Missing admitted immutable main SHA' + printf 'Paired reference: protected main commit %s, pinned at admission and rerun on the same reserved hardware.' "$BASELINE_SHA" } -delta() { - local current=$1 saved=$2 phase=$3 current_job=$4 saved_job=$5 value main_rate - # Match the reported serving host class. Physical nodes/conditions can differ. - if ! jq -e --slurpfile main "$saved_job" ' - def hardware: .machine.host | {arch, chip, cpu_cores, gpu, gpu_count}; - hardware as $current | ($main[0] | hardware) as $previous | - $current == $previous and $current.arch == "aarch64" and - $current.gpu == "NVIDIA GB10" and $current.gpu_count == 1 and - ($current.chip | type == "string" and length > 0) and $current.cpu_cores > 0 - ' "$current_job" > /dev/null; then printf Unavailable; return; fi - value=$(jq -r --arg phase "$phase" --slurpfile main "$saved" ' - .[$phase + "_tokens"] as $tokens | .[$phase + "_ms"] as $ms | - $main[0][$phase + "_tokens"] as $previous_tokens | - $main[0][$phase + "_ms"] as $previous_ms | - if $tokens == $previous_tokens and $tokens > 0 and $ms > 0 and $previous_ms > 0 and - ($ms | isfinite) and ($previous_ms | isfinite) then - (($previous_ms / $ms - 1) * 100) | if isfinite then . else "Unavailable" end - else "Unavailable" end - ' "$current") - if [[ $value == Unavailable ]]; then printf Unavailable; return; fi - main_rate=$(rate "$saved" "$phase") - if [[ $main_rate == Unavailable ]]; then printf Unavailable; return; fi - printf '%+.1f%% (main %s)' "$value" "$main_rate" +paired_rows() { + local pairs=$1 receipt=$2 row=$3 state=$4 action=$5 lab=$6 + jq -e --arg sha "$SOURCE_SHA" --arg main "$BASELINE_SHA" --arg row "$row" --slurpfile job "$receipt" ' + def positive: type == "number" and isfinite and . > 0; + def phase: + (.main_tok_s | positive) and (.candidate_tok_s | positive) and + (.ratio | positive) and (.ci95 | length == 2) and all(.ci95[]; positive) and + .ci95[0] <= .ratio and .ratio <= .ci95[1] and + (.noise_pct | type == "number" and isfinite and . >= 0) and + (.calibrated | type == "boolean") and + (.verdict == "improved" or .verdict == "regressed" or .verdict == "inconclusive") and + (if .calibrated then true else .verdict == "inconclusive" end); + .schema_version == 1 and .protocol == "DGX Spark paired probe v1" and + .source_sha == $sha and .baseline_sha == $main and .configuration == $row and + .rounds == 6 and .repetitions == 3 and (.runs | length == 24) and + .job_id == $job[0].id and .run_id == $job[0].runs[-1].id and + $job[0].repo_rev == $sha and $job[0].status == "succeeded" and + $job[0].runs[-1].status == "succeeded" and + (.summary | map(.shape)) == [0,1,2] and + all(.summary[]; (.prefill | phase) and (.decode | phase)) + ' "$pairs" > /dev/null || fail 'Paired comparison evidence mismatch' + jq -r --arg row "$row" --arg state "$state" --arg action "$action" --arg lab "$lab" ' + def rounded: (. * 10 | round) / 10 | tostring; + def pct: ((. - 1) * 100) as $p | (if $p >= 0 then "+" else "" end) + ($p | rounded) + "%"; + def comparison: + "\(.ratio | pct) [\(.ci95[0] | pct), \(.ci95[1] | pct)] · \(.verdict) (main \(.main_tok_s | rounded))"; + .summary[] | + "| `\($row)` · \(.prefill.tokens_per_request) input | \($state) | \(.prefill.candidate_tok_s | rounded) | \(.prefill | comparison) | \(.decode.candidate_tok_s | rounded) | \(.decode | comparison) | \(.prefill.noise_pct | rounded)% / \(.decode.noise_pct | rounded)% | \($action) | \($lab) |" + ' "$pairs" } diff --git a/scripts/lib/inference_paired_collect.py b/scripts/lib/inference_paired_collect.py new file mode 100644 index 00000000..9e8d09a2 --- /dev/null +++ b/scripts/lib/inference_paired_collect.py @@ -0,0 +1,53 @@ +"""Admit and independently summarize same-allocation native comparison evidence.""" + +import re +import os +from pathlib import Path + +from .ci_artifacts import write_json +from .inference_pairs import summarize +from .inference_throughput import fetch_artifact, successful_run + + +def collect_pairs(pilot, job, row, candidate, baseline, output): + run_id = successful_run(job, candidate) + evidence = fetch_artifact(pilot, run_id, "paired-probe.json") + summary = summarize(evidence, candidate, baseline, row["id"]) + placements = {p["role"]: p for p in evidence["placements"]} + if placements["leader"]["hostname"] != job["machine"]["host"]["hostname"]: + raise ValueError("comparison leader differs from reserved JY machine") + if row["mode"] == "split": + formation = pilot.api("GET", f'/v1/formations/{job["formation_id"]}') + members = formation["members"] + if (formation["status"] != "succeeded" or len(members) != 2 + or any(m["status"] != "succeeded" or m["node"] != placements[m["role"]]["node"] + for m in members)): + raise ValueError("comparison does not match the successful JY formation") + builds = evidence["builds"] + if len(builds) != len(placements) or {b["role"] for b in builds} != set(placements): + raise ValueError("comparison build provenance is incomplete") + for build in builds: + for name, sha in (("main", baseline), ("candidate", candidate)): + identity = build[name] + if identity["stack_commit"] != sha or not re.fullmatch(r"[0-9a-f]{64}", identity["cli_sha256"]): + raise ValueError("comparison build provenance mismatch") + receipt = {**evidence, "summary": summary, "job_id": job["id"], "run_id": run_id} + write_json(output / f'{row["id"]}-paired.json', receipt) + lines = [f'### Paired inference: {row["id"]}', "", f"Main `{baseline}` · candidate `{candidate}`", + "", "Server phase timings; six A/A pairs and six alternating A/B pairs.", "", + "| Input tokens | Phase | Main tok/s | Candidate tok/s | Change [pointwise 95% CI] | A/A noise | Verdict |", + "| ---: | --- | ---: | ---: | --- | ---: | --- |"] + for shape in summary: + for phase in ("prefill", "decode"): + item = shape[phase] + change = [100 * (v - 1) for v in (item["ratio"], *item["ci95"])] + lines.append(f'| {shape["prefill"]["tokens_per_request"]} | {phase} | ' + f'{item["main_tok_s"]:.1f} | {item["candidate_tok_s"]:.1f} | ' + f'{change[0]:+.1f}% [{change[1]:+.1f}%, {change[2]:+.1f}%] | ' + f'{item["noise_pct"]:.1f}% | {item["verdict"]} |') + lines.extend(["", "Uncalibrated A/A results make A/B inconclusive. See ci/README.md for the design and limitations.", ""]) + report = "\n".join(lines) + (output / f'{row["id"]}-comparison.md').write_text(report, encoding="utf-8") + if os.environ.get("GITHUB_STEP_SUMMARY"): + with Path(os.environ["GITHUB_STEP_SUMMARY"]).open("a", encoding="utf-8") as stream: + stream.write(report) diff --git a/scripts/lib/inference_pairs.py b/scripts/lib/inference_pairs.py new file mode 100644 index 00000000..3ee809e1 --- /dev/null +++ b/scripts/lib/inference_pairs.py @@ -0,0 +1,100 @@ +"""Fixed paired design and per-shape inference intervals; no device access.""" + +import math +import re +from statistics import fmean, stdev + +from .inference_probe import PARAGRAPHS, MEASURED_TOKENS + +PROTOCOL = "DGX Spark paired probe v1" +ROUNDS = 6 +REPETITIONS = 3 +# Two-sided Student t, df=5, alpha=.05. The independent unit is a restarted +# server pair, not the requests nested inside that pair. +T95 = 2.570581835636305 +MAX_NOISE = math.log(1.05) + + +def schedule(baseline, candidate): + result = [] + for experiment in ("aa", "ab"): + for round_index in range(ROUNDS): + for arm in (("a", "b") if round_index % 2 == 0 else ("b", "a")): + result.append({"experiment": experiment, "round": round_index, "arm": arm, + "source_sha": candidate if experiment == "ab" and arm == "b" else baseline}) + return result + + +def interval(values): + center = fmean(values) + margin = T95 * stdev(values) / math.sqrt(ROUNDS) + return center, center - margin, center + margin + + +def summarize(evidence, candidate, baseline, configuration): + if (evidence.get("schema_version") != 1 or evidence.get("protocol") != PROTOCOL + or evidence.get("source_sha") != candidate or evidence.get("baseline_sha") != baseline + or evidence.get("configuration") != configuration + or type(evidence.get("rounds")) is not int or evidence["rounds"] != ROUNDS + or type(evidence.get("repetitions")) is not int or evidence["repetitions"] != REPETITIONS + or any(not re.fullmatch(r"[0-9a-f]{40}", sha) for sha in (candidate, baseline))): + raise ValueError("paired inference identity or design mismatch") + placements = evidence["placements"] + roles = {"leader", "worker"} if configuration.endswith("-split") else {"leader"} + if (len(placements) != len(roles) or {p["role"] for p in placements} != roles + or len({p["node"] for p in placements}) != len(roles) + or any(not isinstance(p["node"], str) or not p["node"] for p in placements)): + raise ValueError("paired inference requires one fixed allocation") + expected = schedule(baseline, candidate) + runs = evidence["runs"] + if len(runs) != len(expected): + raise ValueError("incomplete paired inference rounds") + for run, design in zip(runs, expected): + if (any(run.get(k) != v for k, v in design.items()) + or type(run.get("round")) is not int + or run.get("placements") != placements or run.get("quality") != "passed" + or len(run["samples"]) != len(PARAGRAPHS) * REPETITIONS): + raise ValueError("paired inference order, placement or quality mismatch") + for index, sample in enumerate(run["samples"]): + if type(sample["shape"]) is not int or sample["shape"] != index % len(PARAGRAPHS): + raise ValueError("paired inference workload shape mismatch") + for phase in ("prefill", "decode"): + tokens, millis = sample[f"{phase}_tokens"], sample[f"{phase}_ms"] + if (type(tokens) is not int or tokens <= 0 or type(millis) not in (int, float) + or not math.isfinite(millis) or millis <= 0 + or (phase == "decode" and tokens != MEASURED_TOKENS)): + raise ValueError("invalid paired inference timings") + result = [] + for shape, paragraphs in enumerate(PARAGRAPHS): + row = {"shape": shape, "paragraphs": paragraphs} + for phase in ("prefill", "decode"): + rates, counts = {}, set() + for run in runs: + samples = [s for s in run["samples"] if s["shape"] == shape] + counts.update(s[f"{phase}_tokens"] for s in samples) + tokens = sum(s[f"{phase}_tokens"] for s in samples) + millis = sum(s[f"{phase}_ms"] for s in samples) + rate = tokens * 1000 / millis + if not math.isfinite(rate) or rate <= 0: + raise ValueError("invalid paired inference rate") + rates[run["experiment"], run["round"], run["arm"]] = rate + if len(counts) != 1: + raise ValueError("paired inference token counts changed") + logs = {kind: [math.log(rates[kind, r, "b"] / rates[kind, r, "a"]) + for r in range(ROUNDS)] for kind in ("aa", "ab")} + aa, aa_low, aa_high = interval(logs["aa"]) + center, low, high = interval(logs["ab"]) + noise = max(abs(aa_low), abs(aa_high)) + calibrated = aa_low <= 0 <= aa_high and noise <= MAX_NOISE + verdict = ("improved" if calibrated and low > noise else + "regressed" if calibrated and high < -noise else "inconclusive") + geometric = lambda arm: math.exp(fmean(math.log(rates["ab", r, arm]) for r in range(ROUNDS))) + row[phase] = { + "tokens_per_request": next(iter(counts)), "main_tok_s": geometric("a"), + "candidate_tok_s": geometric("b"), "ratio": math.exp(center), + "ci95": [math.exp(low), math.exp(high)], + "aa_ratio": math.exp(aa), "aa_ci95": [math.exp(aa_low), math.exp(aa_high)], + "noise_pct": math.expm1(noise) * 100, "calibrated": calibrated, "verdict": verdict, + } + result.append(row) + return result diff --git a/scripts/lib/inference_probe.py b/scripts/lib/inference_probe.py index abaebd34..7b045ac4 100644 --- a/scripts/lib/inference_probe.py +++ b/scripts/lib/inference_probe.py @@ -16,9 +16,13 @@ "and cache state consistent.") -def payload(model, index, warmup): +def payload(model, index, warmup, repetition=None): # Different early tokens prevent prefix reuse; equal shapes warm the same kernels. prefix = "A" if warmup else "B" + if repetition is not None: + if type(repetition) is not int or not 0 <= repetition < 3: + raise ValueError("invalid repeated probe index") + prefix = chr(65 + repetition * 6 + index * 2 + (0 if warmup else 1)) prompt = f"{prefix}{index}\n" + "\n".join( f"Record {item}: {RECORD}" for item in range(PARAGRAPHS[index]) ) + "\nWrite a detailed engineering analysis of this service, with concrete examples." @@ -55,9 +59,10 @@ def validate_evidence(evidence, model): or evidence["status"] != "passed" or len(evidence["samples"]) != len(PARAGRAPHS)): raise ValueError("incomplete warm throughput probe evidence") responses = [] + repetition = evidence.get("repetition") for index, sample in enumerate(evidence["samples"]): - warm = validate_response(sample["warmup"], payload(model, index, True)) - measured = validate_response(sample["measured"], payload(model, index, False)) + warm = validate_response(sample["warmup"], payload(model, index, True, repetition)) + measured = validate_response(sample["measured"], payload(model, index, False, repetition)) if warm != measured: raise ValueError("throughput warmup and measurement have different prompt shapes") responses.append(sample["measured"]["response"]) @@ -76,18 +81,20 @@ def send(request, sample): sample["client_ms"] = (time.perf_counter_ns() - started) / 1_000_000 -def measure(model, output): +def measure(model, output, repetition=None): evidence = {"schema_version": 1, "workload": WORKLOAD, "status": "incomplete", "samples": []} + if repetition is not None: + evidence["repetition"] = repetition try: for index in range(len(PARAGRAPHS)): sample = {} evidence["samples"].append(sample) sample["warmup"] = {} - send(payload(model, index, True), sample["warmup"]) - validate_response(sample["warmup"], payload(model, index, True)) + send(payload(model, index, True, repetition), sample["warmup"]) + validate_response(sample["warmup"], payload(model, index, True, repetition)) sample["measured"] = {} - send(payload(model, index, False), sample["measured"]) - validate_response(sample["measured"], payload(model, index, False)) + send(payload(model, index, False, repetition), sample["measured"]) + validate_response(sample["measured"], payload(model, index, False, repetition)) evidence["status"] = "passed" validate_evidence(evidence, model) except Exception as error: diff --git a/scripts/lib/inference_rendezvous.py b/scripts/lib/inference_rendezvous.py new file mode 100644 index 00000000..d04202bc --- /dev/null +++ b/scripts/lib/inference_rendezvous.py @@ -0,0 +1,97 @@ +"""Keep split comparison arms in lockstep within one reserved JY formation.""" + +import json +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.error import URLError +from urllib.request import Request, urlopen + +from .ci_process import DEADLINE + + +def await_condition(check, seconds=1800): + deadline = time.monotonic() + seconds + if DEADLINE.get() is not None: + deadline = min(deadline, DEADLINE.get()) + while time.monotonic() < deadline: + value = check() + if value: + return value + time.sleep(0.25) + raise TimeoutError("paired inference rendezvous timed out") + + +class Coordinator: + def __init__(self, worker_host, port=9913): + self.state = {"index": -1, "done": -1, "worker": None, "error": None, "complete": False} + state = self.state + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *_args): + pass + + def do_GET(self): + if self.client_address[0] != worker_host or self.path != "/state": + self.send_error(403) + return + body = json.dumps(state).encode() + self.send_response(200) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_POST(self): + if self.client_address[0] != worker_host or self.path not in {"/ready", "/done", "/error"}: + self.send_error(403) + return + size = int(self.headers.get("Content-Length", "0")) + if not 0 < size <= 65536: + self.send_error(400) + return + value = json.loads(self.rfile.read(size)) + if self.path == "/ready": + state["worker"] = value + elif self.path == "/done": + state["done"] = value["index"] + else: + state["error"] = "split comparison worker failed" + self.send_response(200) + self.end_headers() + + self.server = ThreadingHTTPServer(("0.0.0.0", port), Handler) + self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) + + def __enter__(self): + self.thread.start() + return self + + def wait(self, check, seconds=1800): + def poll(): + if self.state["error"]: + raise RuntimeError(self.state["error"]) + return check(self.state) + return await_condition(poll, seconds) + + def __exit__(self, *_args): + self.state["complete"] = True + self.server.shutdown() + self.server.server_close() + self.thread.join(timeout=10) + + +def exchange(origin, path, value=None): + data = None if value is None else json.dumps(value).encode() + request = Request(origin + path, data=data, headers={"Content-Type": "application/json"}) + with urlopen(request, timeout=5) as response: + body = response.read(65537) + return json.loads(body) if body else True + + +def worker_state(origin): + def poll(): + try: + return exchange(origin, "/state") + except (URLError, TimeoutError, ConnectionError): + return None + return await_condition(poll, seconds=7200) diff --git a/scripts/tests/inference-report.sh b/scripts/tests/inference-report.sh index 9f474e90..cd5b0939 100644 --- a/scripts/tests/inference-report.sh +++ b/scripts/tests/inference-report.sh @@ -8,6 +8,7 @@ export FIXTURE=$fixture export SOURCE_SHA=1111111111111111111111111111111111111111 export GITHUB_RUN_ID=42 GITHUB_RUN_ATTEMPT=2 GITHUB_EVENT_NAME=pull_request_target export PLAN=success REQUIRED=true RESULT=success +export BASELINE_SHA=2222222222222222222222222222222222222222 export GITHUB_EVENT_PATH="$fixture/event.json" GITHUB_STEP_SUMMARY="$fixture/summary.md" mkdir -p "$fixture/bin" "$fixture/evidence" export PATH="$fixture/bin:$PATH" @@ -132,90 +133,33 @@ jq -e '.body | contains("Lab Qualification: Failed or incomplete") and contains( REQUIRED=false reject 'irrelevant change' GITHUB_EVENT_NAME=pull_request reject 'unprotected event' SOURCE_SHA=invalid reject 'mutable source' -# Latest successful main: ignore newer failed runs and PR branches called main. -cp "$fixture/good-receipt.json" "$receipt" -cp "$fixture/good-rates.json" "$rates" +# Paired receipts replace historical comparisons; the protected reporter never +# queries successful-main runs or downloads an unrelated allocation. jq 'to_entries | map({id:(.key+1), name:("qualification ("+.value+")"), conclusion:"success"}) | [{jobs: .}]' "$fixture/rows.json" > "$fixture/jobs.json" -export BASELINE_SHA=2222222222222222222222222222222222222222 -jq -n --arg sha "$BASELINE_SHA" '[{workflow_runs:[ - {id:40,run_attempt:3,head_branch:"main",head_sha:$sha,conclusion:"success",event:"workflow_dispatch",created_at:"2026-11-21"}, - {id:30,run_attempt:1,head_branch:"main",head_sha:$sha,conclusion:"success",event:"schedule",created_at:"2026-11-20"}, - {id:50,run_attempt:1,head_branch:"main",head_sha:$sha,conclusion:"failure",event:"schedule",created_at:"2026-11-22"}, - {id:60,run_attempt:1,head_branch:"main",head_sha:$sha,conclusion:"success",event:"pull_request_target",created_at:"2026-11-22"} -]}]' > "$fixture/main-runs.json" -cp "$fixture/jobs.json" "$fixture/main-jobs.json" -jq -n '{truncated:false,tree:(["scripts/inference-execute.py", "scripts/lib/inference_checks.py", - "scripts/lib/inference_throughput.py", "scripts/lib/inference_probe.py", "scripts/lib/inference_inputs.py", - "scripts/lib/inference_ladder.py", "scripts/lib/ci_artifacts.py", "scripts/lib/ci_process.py", - "scripts/lib/ci_smoke.py", "ci/inference-quality.json", "ci/inference-artifacts.json", - ".gi/templates.yaml"] | map({path:.,type:"blob",sha:"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}))}' > "$fixture/current-tree.json" -cp "$fixture/current-tree.json" "$fixture/main-tree.json" -baseline="$fixture/baseline/inference-$row-40-3" -mkdir -p "$baseline" -jq -n --arg sha "$BASELINE_SHA" --arg row "$row" '{schema_version:1,source_sha:$sha,profile:"pr",hardware:"nvidia-gb10-dgx-spark",rows:[{id:$row,mode:"standalone",machines:1}]}' > "$baseline/plan.json" -jq '.machine.host={arch:"aarch64",chip:"Cortex-X925",cpu_cores:20,gpu:"NVIDIA GB10",gpu_count:1}' "$receipt" > "$fixture/hardware-job.json" -cp "$fixture/hardware-job.json" "$receipt" -jq --arg sha "$BASELINE_SHA" '.repo_rev=$sha' "$receipt" > "$baseline/$row-job.json" -jq --arg sha "$BASELINE_SHA" '.source_sha=$sha | .prefill_ms=1200 | .decode_ms=1920' "$rates" > "$baseline/$row-throughput.json" -report -jq -e '.body | contains("| 500.0 | +100.0% (main 250.0) | 100.0 | -50.0% (main 200.0) |") and contains("/runs/40/attempts/3") and contains("commit `2222222222222222222222222222222222222222`")' "$fixture/posted.json" > /dev/null -cp "$baseline/$row-throughput.json" "$fixture/main-rates.json" -cp "$baseline/plan.json" "$fixture/main-plan.json" -cp "$baseline/$row-job.json" "$fixture/main-job.json" - -# Same run data emitted by #118: select nightly smoke, never extended AgentX. -nightly="$fixture/baseline/inference-smoke-$row-40-3" -mv "$baseline" "$nightly" -jq --arg row "$row" '.[0].jobs[0].name=("qualification (smoke-"+$row+")")' "$fixture/jobs.json" > "$fixture/main-jobs.json" -report -jq -e '.body | contains("+100.0% (main 250.0)")' "$fixture/posted.json" > /dev/null -mv "$nightly" "$baseline" -cp "$fixture/jobs.json" "$fixture/main-jobs.json" - -unavailable() { - report - jq -e '.body | contains("| 500.0 | Unavailable | 100.0 | Unavailable |")' "$fixture/posted.json" > /dev/null -} -for changed in '.profile="nightly"' '.source_sha="wrong"' '.rows[0].mode="split"'; do - jq "$changed" "$fixture/main-plan.json" > "$baseline/plan.json" - unavailable -done -cp "$fixture/main-plan.json" "$baseline/plan.json" -for changed in '.source_sha="wrong"' '.run_id="run_wrong"' '.prefill_ms=0 | .decode_ms=0' '.prefill_tokens=301 | .decode_tokens=31' 'del(.workload)'; do - jq "$changed" "$fixture/main-rates.json" > "$baseline/$row-throughput.json" - unavailable -done -cp "$fixture/main-rates.json" "$baseline/$row-throughput.json" -for changed in '.machine.host.gpu="other"' '.machine.host=null' '.status="failed"'; do - jq "$changed" "$fixture/main-job.json" > "$baseline/$row-job.json" - unavailable -done -cp "$fixture/main-job.json" "$baseline/$row-job.json" -jq '.[0].jobs[0].conclusion="failure"' "$fixture/jobs.json" > "$fixture/main-jobs.json" -unavailable -cp "$fixture/jobs.json" "$fixture/main-jobs.json" -# One phase can remain comparable when only the other phase has different work. -jq '.prefill_tokens=301' "$fixture/main-rates.json" > "$baseline/$row-throughput.json" -report -jq -e '.body | contains("| 500.0 | Unavailable | 100.0 | -50.0% (main 200.0) |")' "$fixture/posted.json" > /dev/null -# Use unrounded values: both decode rates display 100.0 but the delta is +0.1%. -jq '.decode_ms=(384000 / 100.04)' "$fixture/good-rates.json" > "$rates" -jq '.prefill_ms=600 | .decode_ms=(384000 / 99.98)' "$fixture/main-rates.json" > "$baseline/$row-throughput.json" +PYTHONPATH="$root/scripts" python3 - "$fixture/evidence/$row-paired.json" "$row" <<'PYDATA' +import json, os, sys +from lib.inference_pairs import PROTOCOL, ROUNDS, REPETITIONS, schedule, summarize +source, baseline = os.environ['SOURCE_SHA'], os.environ['BASELINE_SHA'] +placement = [{'role':'leader','node':'spark-test'}] +data = {'schema_version':1,'protocol':PROTOCOL,'source_sha':source,'baseline_sha':baseline, + 'configuration':sys.argv[2],'rounds':ROUNDS,'repetitions':REPETITIONS, + 'placements':placement,'runs':[],'job_id':'job_test','run_id':'run_test'} +for design in schedule(baseline, source): + ratio = 1.1 if design['experiment']=='ab' and design['arm']=='b' else 1 + data['runs'].append({**design,'placements':placement,'quality':'passed', + 'samples':[{'shape':i%3,'prefill_tokens':200+i%3,'prefill_ms':100/ratio, + 'decode_tokens':128,'decode_ms':200/ratio} for i in range(REPETITIONS*3)]}) +data['summary'] = summarize(data, source, baseline, sys.argv[2]) +with open(sys.argv[1], 'w') as stream: json.dump(data, stream) +PYDATA report -jq -e '.body | contains("+0.0% (main 500.0)") and contains("100.0 | +0.1% (main 100.0)")' "$fixture/posted.json" > /dev/null -cp "$fixture/good-rates.json" "$rates" -cp "$fixture/main-rates.json" "$baseline/$row-throughput.json" -for changed in '.truncated=true' '.tree[0].sha="changed"' '.tree=[]'; do - jq "$changed" "$fixture/current-tree.json" > "$fixture/main-tree.json" - unavailable - jq -e '.body | contains("workload inputs changed or could not be verified")' "$fixture/posted.json" > /dev/null +jq -e '.body | contains("+10% [+10%, +10%] · improved") and contains("pinned at admission") and contains("200 input")' "$fixture/posted.json" > /dev/null +cp "$fixture/evidence/$row-paired.json" "$fixture/good-paired.json" +for changed in '.baseline_sha="wrong"' '.source_sha="wrong"' '.run_id="wrong"' '.rounds=5' '.runs=[]' '.summary=[]' '.summary[0].decode.ci95=[0,2]' '.summary[0].decode.calibrated=false'; do + jq "$changed" "$fixture/good-paired.json" > "$fixture/evidence/$row-paired.json" + reject "$changed" done -cp "$fixture/current-tree.json" "$fixture/main-tree.json" -touch "$fixture/download-fails" -unavailable -jq -e '.body | contains("missing, expired or unreadable")' "$fixture/posted.json" > /dev/null -rm "$fixture/download-fails" -rm "$baseline/$row-throughput.json" -unavailable +cp "$fixture/good-paired.json" "$fixture/evidence/$row-paired.json" +BASELINE_SHA=main reject 'mutable baseline' printf '%s\n' 'Inference report contracts passed' diff --git a/scripts/tests/inference_paired_execution.py b/scripts/tests/inference_paired_execution.py new file mode 100644 index 00000000..da196fc0 --- /dev/null +++ b/scripts/tests/inference_paired_execution.py @@ -0,0 +1,99 @@ +"""Offline native orchestration checks; these do not qualify any GPU.""" + +import os +from pathlib import Path +from runpy import run_path +from tempfile import TemporaryDirectory +import unittest +from unittest.mock import Mock, patch + +from lib.ci_artifacts import write_json +from lib.inference_pairs import schedule + +MODULE = Path(__file__).resolve().parents[1] / "inference-paired.py" +BASELINE, CANDIDATE = "a" * 40, "b" * 40 + + +class ExecutionTests(unittest.TestCase): + def setUp(self): + self.module = run_path(str(MODULE)) + + def test_arms_use_the_selected_build_and_restore_state_even_after_failure(self): + run = self.module["run_arm"] + with TemporaryDirectory() as temporary: + root = Path(temporary).resolve() + candidate, main, output = (root / name for name in ("candidate", "main", "evidence")) + for directory in (candidate, main, output): + directory.mkdir() + previous = Path.cwd() + environment = os.environ.copy() + calls = [] + def execute(profile, key, mode, repeats): + calls.append((Path.cwd(), os.environ["JIANYANG_COMMIT"], profile, key, mode, repeats)) + if len(calls) == 2: + raise RuntimeError("injected failed arm") + with patch.dict(run.__globals__, ROOT=candidate, EXECUTE=execute): + for index, sha in enumerate((BASELINE, CANDIDATE)): + design = {"experiment": "ab", "round": index, "arm": "a", "source_sha": sha} + if index == 0: + run(design, main, BASELINE, "qwen35-4b", "standalone", output) + else: + with self.assertRaisesRegex(RuntimeError, "injected"): + run(design, main, BASELINE, "qwen35-4b", "standalone", output) + self.assertEqual(Path.cwd(), previous) + self.assertEqual(os.environ, environment) + self.assertEqual(calls, [(main, BASELINE, "pr", "qwen35-4b", "standalone", 3), + (candidate, CANDIDATE, "pr", "qwen35-4b", "standalone", 3)]) + + def test_builds_main_once_before_measurement_and_rejects_changed_fixtures(self): + prepare = self.module["prepare"] + with TemporaryDirectory() as temporary: + root = Path(temporary) + candidate, main, output = (root / name for name in ("candidate", "main", "evidence")) + for directory, sha in ((main, BASELINE), (candidate, CANDIDATE)): + (directory / "ci").mkdir(parents=True) + (directory / "target").mkdir() + for name in ("inference-artifacts.json", "inference-quality.json"): + write_json(directory / "ci" / name, {}) + write_json(directory / "target/inference-build.json", {"stack_commit": sha}) + command = Mock() + with patch.dict(prepare.__globals__, ROOT=candidate, command=command): + prepare(main, BASELINE, CANDIDATE, output) + command.assert_called_once_with(["just", "inference-build"], timeout=7200) + write_json(main / "ci/inference-artifacts.json", {"changed": True}) + command.reset_mock() + with self.assertRaisesRegex(ValueError, "fixtures changed"): + prepare(main, BASELINE, CANDIDATE, output) + command.assert_not_called() + + def test_legacy_rollout_does_not_relabel_a_smoke_as_a_paired_result(self): + execute = self.module["execute"] + native = Mock() + with patch.dict(execute.__globals__, EXECUTE=native): + execute("qwen35-4b", "standalone", "legacy") + native.assert_called_once_with("pr", "qwen35-4b", "standalone") + + def test_controller_keeps_one_job_for_the_entire_design_and_requires_its_receipt(self): + module = run_path(str(MODULE.with_name("inference-dispatch.py"))) + dispatch = module["dispatch"] + configuration = "qwen35-4b-standalone" + pilot, launch, wait, collect, pairs = Mock(), Mock(return_value={"job_id": "job_test"}), Mock(), Mock(), Mock() + cancel = Mock() + with TemporaryDirectory() as temporary, patch.dict( + dispatch.__globals__, launch=launch, wait=wait, collect=collect, collect_pairs=pairs, cancel=cancel): + output = Path(temporary) + dispatch(pilot, "pr", CANDIDATE, output, configuration, baseline=BASELINE) + launch.assert_called_once() + body = launch.call_args.args[2] + self.assertEqual(body["ref"], CANDIDATE) + self.assertEqual(body["inputs"]["baseline_sha"], BASELINE) + self.assertEqual(len(schedule(BASELINE, CANDIDATE)), 24) + pairs.assert_called_once() + pairs.side_effect = ValueError("missing paired evidence") + with self.assertRaisesRegex(ValueError, "missing paired evidence"): + dispatch(pilot, "pr", CANDIDATE, output, configuration, baseline=BASELINE) + cancel.assert_called_once() + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/inference_pairs.py b/scripts/tests/inference_pairs.py new file mode 100644 index 00000000..281a19a5 --- /dev/null +++ b/scripts/tests/inference_pairs.py @@ -0,0 +1,168 @@ +"""Offline statistical and evidence-admission regressions for paired inference.""" + +from copy import deepcopy +import math +from pathlib import Path +import os +from runpy import run_path +from tempfile import TemporaryDirectory +import unittest +from unittest.mock import Mock, patch + +from lib.ci_artifacts import read_json +from lib.inference_pairs import PROTOCOL, REPETITIONS, ROUNDS, schedule, summarize +from lib.inference_paired_collect import collect_pairs +from lib.inference_rendezvous import Coordinator, exchange + +CANDIDATE, BASELINE = "a" * 40, "b" * 40 +CONFIGURATION = "qwen35-4b-standalone" + + +def evidence(ratio=1.1, aa_ratios=None, ab_ratios=None): + placements = [{"role": "leader", "node": "node-a", "hostname": "host-a"}] + builds = [{"role": "leader", "main": {"stack_commit": BASELINE, "cli_sha256": "c" * 64}, + "candidate": {"stack_commit": CANDIDATE, "cli_sha256": "d" * 64}}] + data = {"schema_version": 1, "protocol": PROTOCOL, "source_sha": CANDIDATE, + "baseline_sha": BASELINE, "configuration": CONFIGURATION, "rounds": ROUNDS, + "repetitions": REPETITIONS, "placements": placements, "builds": builds, "runs": []} + for design in schedule(BASELINE, CANDIDATE): + ratios = aa_ratios if design["experiment"] == "aa" else ab_ratios + gain = (ratios[design["round"]] if ratios else + 1 if design["experiment"] == "aa" else ratio) if design["arm"] == "b" else 1 + samples = [{"shape": shape, "prefill_tokens": 200 + shape, "prefill_ms": 100 / gain, + "decode_tokens": 128, "decode_ms": 200 / gain} + for _ in range(REPETITIONS) for shape in range(3)] + data["runs"].append({**design, "placements": deepcopy(placements), + "quality": "passed", "samples": samples}) + return data + + +def summary(data): + return summarize(data, CANDIDATE, BASELINE, CONFIGURATION) + + +class PairedTests(unittest.TestCase): + def test_balanced_order_and_identical_source_for_noise_calibration(self): + design = schedule(BASELINE, CANDIDATE) + self.assertEqual(len(design), 24) + self.assertEqual([d["arm"] for d in design[:8]], list("abbaabba")) + self.assertTrue(all(d["source_sha"] == BASELINE for d in design[:12])) + self.assertEqual(sum(d["source_sha"] == CANDIDATE for d in design), 6) + + def test_detects_both_signs_per_shape_without_treating_nested_requests_as_rounds(self): + for ratio, verdict in ((1.1, "improved"), (0.9, "regressed"), (1, "inconclusive")): + for row in summary(evidence(ratio)): + for phase in ("prefill", "decode"): + self.assertAlmostEqual(row[phase]["ratio"], ratio) + self.assertEqual(row[phase]["verdict"], verdict) + # Known df=5 Student-t interval on six log ratios: mean zero, stdev sqrt(28/5). + logs = [-3, -2, -1, 1, 2, 3] + data = evidence(ab_ratios=[math.exp(x / 100) for x in logs]) + item = summary(data)[0]["decode"] + margin = 2.570581835636305 * math.sqrt(28 / 5) / math.sqrt(6) / 100 + self.assertAlmostEqual(item["ci95"][0], math.exp(-margin)) + self.assertAlmostEqual(item["ci95"][1], math.exp(margin)) + self.assertEqual(item["verdict"], "inconclusive") + + def test_noise_or_systematic_order_bias_blocks_a_performance_verdict(self): + for noise in ([0.9, 1.1] * 3, [1.02] * 6): + item = summary(evidence(1.2, aa_ratios=noise))[0]["prefill"] + self.assertFalse(item["calibrated"]) + self.assertEqual(item["verdict"], "inconclusive") + item = summary(evidence(1.001, aa_ratios=[0.99, 1.01] * 3))[0]["prefill"] + self.assertTrue(item["calibrated"]) + self.assertEqual(item["verdict"], "inconclusive") + + def test_rejects_partial_reordered_changed_hardware_quality_or_workload(self): + changes = [lambda d: d["runs"].pop(), + lambda d: d["runs"].reverse(), + lambda d: d["runs"][0].update(source_sha=CANDIDATE), + lambda d: d["runs"][0].update(placements=[]), + lambda d: d["runs"][0].update(quality="failed"), + lambda d: d["runs"][0]["samples"].pop(), + lambda d: d["runs"][0]["samples"][0].update(prefill_tokens=201), + lambda d: d["runs"][0]["samples"][0].update(decode_tokens=127), + lambda d: d["runs"][0]["samples"][0].update(decode_ms=float("nan")), + lambda d: d.update(rounds=True), + lambda d: d.update(baseline_sha=CANDIDATE)] + for change in changes: + data = evidence() + change(data) + with self.subTest(change=change), self.assertRaises(ValueError): + summary(data) + + def test_controller_recomputes_native_summary_and_binds_it_to_the_job(self): + data = evidence() + data["summary"] = "forged result" + job = {"id": "job_test", "repo_rev": CANDIDATE, "status": "succeeded", + "runs": [{"id": "run_test", "status": "succeeded"}], + "machine": {"host": {"hostname": "host-a"}}} + pilot = Mock() + pilot.api.return_value = data + with TemporaryDirectory() as temporary: + output = Path(temporary) + collect_pairs(pilot, job, {"id": CONFIGURATION, "mode": "standalone"}, + CANDIDATE, BASELINE, output) + receipt = read_json(output / f"{CONFIGURATION}-paired.json") + self.assertEqual(receipt["summary"][0]["decode"]["verdict"], "improved") + self.assertEqual(receipt["run_id"], "run_test") + job["machine"]["host"]["hostname"] = "other-host" + with self.assertRaisesRegex(ValueError, "leader differs"): + collect_pairs(pilot, job, {"id": CONFIGURATION, "mode": "standalone"}, + CANDIDATE, BASELINE, output) + + def test_split_collector_rejects_a_different_worker_even_with_valid_rates(self): + data = evidence() + configuration = "qwen3-coder-30b-a3b-split" + data["configuration"] = configuration + data["placements"].append({"role": "worker", "node": "node-b", "hostname": "host-b"}) + data["builds"].append({**deepcopy(data["builds"][0]), "role": "worker"}) + for run in data["runs"]: + run["placements"] = deepcopy(data["placements"]) + job = {"id": "job_test", "repo_rev": CANDIDATE, "status": "succeeded", "formation_id": "frm_test", + "runs": [{"id": "run_test", "status": "succeeded"}], + "machine": {"host": {"hostname": "host-a"}}} + formation = {"status": "succeeded", "members": [ + {"role": "leader", "node": "node-a", "status": "succeeded"}, + {"role": "worker", "node": "node-b", "status": "succeeded"}]} + pilot = Mock() + with TemporaryDirectory() as temporary: + for valid in (True, False): + formation["members"][1]["node"] = "node-b" if valid else "replacement-node" + pilot.api.side_effect = [data, formation] + args = (pilot, job, {"id": configuration, "mode": "split"}, CANDIDATE, BASELINE, Path(temporary)) + if valid: + collect_pairs(*args) + else: + with self.assertRaisesRegex(ValueError, "formation"): + collect_pairs(*args) + + def test_rendezvous_requires_worker_completion_and_propagates_failure(self): + with Coordinator("127.0.0.1", port=0) as coordinator: + origin = f"http://127.0.0.1:{coordinator.server.server_address[1]}" + exchange(origin, "/ready", {"host": "worker"}) + self.assertEqual(coordinator.wait(lambda s: s["worker"]), {"host": "worker"}) + coordinator.state["index"] = 2 + self.assertEqual(exchange(origin, "/state")["index"], 2) + exchange(origin, "/done", {"index": 2}) + self.assertTrue(coordinator.wait(lambda s: s["done"] == 2)) + exchange(origin, "/error", {"failed": True}) + with self.assertRaisesRegex(RuntimeError, "worker failed"): + coordinator.wait(lambda s: s["done"] == 3) + + def test_admission_pins_current_main_instead_of_selecting_a_successful_nightly(self): + module = run_path(str(Path(__file__).resolve().parents[1] / "inference-plan.py")) + admit = module["admit"] + event = {"pull_request": {"head": {"sha": CANDIDATE}}} + github = Mock(return_value={"object": {"sha": BASELINE}}) + output = Mock() + with patch.dict(os.environ, GITHUB_EVENT_NAME="pull_request_target", GITHUB_EVENT_PATH="event.json"), \ + patch.dict(admit.__globals__, read_json=Mock(return_value=event), admit_pr=Mock(), + github=github, output=output): + admit() + github.assert_called_once_with("repos/Mesh-LLM/skippy/git/ref/heads/main") + output.assert_called_once_with(source=CANDIDATE, profile="pr", baseline=BASELINE) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/inference_probe.py b/scripts/tests/inference_probe.py index 1df8f0a1..f526d2b0 100644 --- a/scripts/tests/inference_probe.py +++ b/scripts/tests/inference_probe.py @@ -29,6 +29,13 @@ def evidence(model=MODEL): class ProbeTests(unittest.TestCase): + def test_repeated_probes_have_distinct_early_prefixes(self): + prefixes = {probe.payload(MODEL, i, warmup, repetition)["messages"][0]["content"].splitlines()[0] + for repetition in range(3) for i in range(3) for warmup in (True, False)} + self.assertEqual(len(prefixes), 18) + with self.assertRaisesRegex(ValueError, "repeated probe"): + probe.payload(MODEL, 0, False, 3) + def test_only_measured_tokens_survive_validation(self): responses = probe.validate_evidence(evidence(), MODEL) self.assertEqual(len(responses), 3) From c3fde3396a67a9155c27e2d1b654dc6810f5c121 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sat, 28 Nov 2026 08:34:38 +1100 Subject: [PATCH 02/22] Pin protected main for manual PR-profile comparisons --- scripts/inference-plan.py | 2 +- scripts/tests/inference_pairs.py | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/scripts/inference-plan.py b/scripts/inference-plan.py index 38a51165..89774d51 100644 --- a/scripts/inference-plan.py +++ b/scripts/inference-plan.py @@ -99,7 +99,7 @@ def admit(): admit_pr(sha) # Pin main independently of nightly success. Never use a moving ref on a # native worker or select the baseline by its measured performance. - baseline = github(f"repos/{REPO}/git/ref/heads/main")["object"]["sha"] if is_pr else sha + baseline = github(f"repos/{REPO}/git/ref/heads/main")["object"]["sha"] if profile == "pr" else sha plan(profile, baseline) output(source=sha, profile=profile, baseline=baseline) diff --git a/scripts/tests/inference_pairs.py b/scripts/tests/inference_pairs.py index 281a19a5..71c86bde 100644 --- a/scripts/tests/inference_pairs.py +++ b/scripts/tests/inference_pairs.py @@ -163,6 +163,16 @@ def test_admission_pins_current_main_instead_of_selecting_a_successful_nightly(s github.assert_called_once_with("repos/Mesh-LLM/skippy/git/ref/heads/main") output.assert_called_once_with(source=CANDIDATE, profile="pr", baseline=BASELINE) + # A manual PR-profile run on a branch must not call that branch "main". + github.reset_mock() + output.reset_mock() + with patch.dict(os.environ, GITHUB_EVENT_NAME="workflow_dispatch", GITHUB_EVENT_PATH="event.json", + GITHUB_SHA=CANDIDATE, QUALIFICATION_PROFILE="pr"), \ + patch.dict(admit.__globals__, read_json=Mock(return_value={}), github=github, output=output): + admit() + github.assert_called_once_with("repos/Mesh-LLM/skippy/git/ref/heads/main") + output.assert_called_once_with(source=CANDIDATE, profile="pr", baseline=BASELINE) + if __name__ == "__main__": unittest.main() From 0549d93557c62f4de1a7ba24d76116aabdc15f6a Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sat, 28 Nov 2026 09:12:49 +1100 Subject: [PATCH 03/22] Retain every paired inference arm in uploaded evidence archives --- scripts/inference-paired.py | 11 +++++++++-- scripts/tests/inference_paired_execution.py | 8 ++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/scripts/inference-paired.py b/scripts/inference-paired.py index 8f91c6be..e8719652 100644 --- a/scripts/inference-paired.py +++ b/scripts/inference-paired.py @@ -9,6 +9,7 @@ import shutil import subprocess import sys +import tarfile import tempfile from contextlib import contextmanager, nullcontext from pathlib import Path @@ -97,8 +98,14 @@ def run_arm(design, main, baseline, key, mode, output): directory = output / f'{design["experiment"]}-{design["round"]}-{design["arm"]}' directory.mkdir() source = main if design["source_sha"] == baseline else ROOT - with revision(source, design["source_sha"], directory): - EXECUTE("pr", key, mode, REPETITIONS) + try: + with revision(source, design["source_sha"], directory): + EXECUTE("pr", key, mode, REPETITIONS) + finally: + # JY uploads top-level files only. Archive each arm, including partial + # failures, so raw responses and logs survive native workspace cleanup. + with tarfile.open(output / f"{directory.name}-evidence.tar.gz", "w:gz") as archive: + archive.add(directory, arcname=directory.name) return directory diff --git a/scripts/tests/inference_paired_execution.py b/scripts/tests/inference_paired_execution.py index da196fc0..07c87b8c 100644 --- a/scripts/tests/inference_paired_execution.py +++ b/scripts/tests/inference_paired_execution.py @@ -1,6 +1,7 @@ """Offline native orchestration checks; these do not qualify any GPU.""" import os +import tarfile from pathlib import Path from runpy import run_path from tempfile import TemporaryDirectory @@ -30,6 +31,9 @@ def test_arms_use_the_selected_build_and_restore_state_even_after_failure(self): calls = [] def execute(profile, key, mode, repeats): calls.append((Path.cwd(), os.environ["JIANYANG_COMMIT"], profile, key, mode, repeats)) + artifacts = Path(os.environ["JIANYANG_ARTIFACT_DIR"]) + (artifacts / "probe-1").mkdir() + (artifacts / "probe-1/throughput-probe.json").write_text('{"raw_body":"retained"}') if len(calls) == 2: raise RuntimeError("injected failed arm") with patch.dict(run.__globals__, ROOT=candidate, EXECUTE=execute): @@ -42,6 +46,10 @@ def execute(profile, key, mode, repeats): run(design, main, BASELINE, "qwen35-4b", "standalone", output) self.assertEqual(Path.cwd(), previous) self.assertEqual(os.environ, environment) + archive_path = output / f"ab-{index}-a-evidence.tar.gz" + with tarfile.open(archive_path) as archive: + response = archive.extractfile(f"ab-{index}-a/probe-1/throughput-probe.json").read() + self.assertEqual(response, b'{"raw_body":"retained"}') self.assertEqual(calls, [(main, BASELINE, "pr", "qwen35-4b", "standalone", 3), (candidate, CANDIDATE, "pr", "qwen35-4b", "standalone", 3)]) From 05bb3022a2d8dc344a8d72a8c61e0ab37185214b Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sat, 28 Nov 2026 09:16:08 +1100 Subject: [PATCH 04/22] Require uploaded arm archives from both comparison roles --- ci/README.md | 3 +++ scripts/lib/inference_paired_collect.py | 36 ++++++++++++++++++++++--- scripts/tests/inference_pairs.py | 34 ++++++++++++++++++----- 3 files changed, 63 insertions(+), 10 deletions(-) diff --git a/ci/README.md b/ci/README.md index 933b8e82..526bb99b 100644 --- a/ci/README.md +++ b/ci/README.md @@ -179,6 +179,9 @@ run inside the same exclusive job or atomic two-Spark formation. The two roles keep their placement and wait at a barrier after each restarted server arm. Build hashes, source commits, host/kernel/driver identities, raw responses and client timings remain in the lab evidence. All builds finish before measurement. +Each arm has a top-level evidence archive because JY does not upload nested +directories. Collection requires every arm archive in the uploaded manifest, +including the worker's archives for split runs, and retains their hashes. The fixed design runs six main/main pairs for noise calibration, followed by six main/candidate pairs, alternating A/B and B/A order. Every arm repeats each of diff --git a/scripts/lib/inference_paired_collect.py b/scripts/lib/inference_paired_collect.py index 9e8d09a2..da1376f4 100644 --- a/scripts/lib/inference_paired_collect.py +++ b/scripts/lib/inference_paired_collect.py @@ -1,12 +1,29 @@ """Admit and independently summarize same-allocation native comparison evidence.""" -import re import os +import re +import time from pathlib import Path from .ci_artifacts import write_json from .inference_pairs import summarize -from .inference_throughput import fetch_artifact, successful_run +from .inference_throughput import ARTIFACT_RETRIES, ARTIFACT_RETRY_DELAY, fetch_artifact, successful_run + + +def arm_archives(pilot, run_id, runs): + expected = {f'{r["experiment"]}-{r["round"]}-{r["arm"]}-evidence.tar.gz' for r in runs} + for attempt in range(ARTIFACT_RETRIES + 1): + manifest = pilot.api("GET", f"/v1/artifacts/{run_id}")["artifacts"] + found = {row["key"].rsplit("/", 1)[-1]: row for row in manifest + if row["key"].rsplit("/", 1)[-1] in expected and row["kind"] == "raw"} + if set(found) == expected: + if any(type(row["size_bytes"]) is not int or row["size_bytes"] <= 0 + or not re.fullmatch(r"[0-9a-f]{64}", row["sha256"]) for row in found.values()): + raise ValueError("invalid paired inference archive manifest") + return [found[name] for name in sorted(found)] + if attempt < ARTIFACT_RETRIES: + time.sleep(ARTIFACT_RETRY_DELAY) + raise ValueError("incomplete uploaded paired inference arm archives") def collect_pairs(pilot, job, row, candidate, baseline, output): @@ -14,15 +31,24 @@ def collect_pairs(pilot, job, row, candidate, baseline, output): evidence = fetch_artifact(pilot, run_id, "paired-probe.json") summary = summarize(evidence, candidate, baseline, row["id"]) placements = {p["role"]: p for p in evidence["placements"]} + worker_archives = [] if placements["leader"]["hostname"] != job["machine"]["host"]["hostname"]: raise ValueError("comparison leader differs from reserved JY machine") if row["mode"] == "split": formation = pilot.api("GET", f'/v1/formations/{job["formation_id"]}') members = formation["members"] - if (formation["status"] != "succeeded" or len(members) != 2 + if (formation["id"] != job["formation_id"] or formation["status"] != "succeeded" or len(members) != 2 + or {m["role"] for m in members} != {"leader", "worker"} + or not any(m["role"] == "leader" and m["job_id"] == job["id"] for m in members) or any(m["status"] != "succeeded" or m["node"] != placements[m["role"]]["node"] for m in members)): raise ValueError("comparison does not match the successful JY formation") + worker = next(m for m in members if m["role"] == "worker") + worker_job = pilot.api("GET", f'/v1/jobs/{worker["job_id"]}') + worker_run = successful_run(worker_job, candidate) + if worker_job["machine"]["host"]["hostname"] != placements["worker"]["hostname"]: + raise ValueError("comparison worker differs from reserved JY machine") + worker_archives = arm_archives(pilot, worker_run, evidence["runs"]) builds = evidence["builds"] if len(builds) != len(placements) or {b["role"] for b in builds} != set(placements): raise ValueError("comparison build provenance is incomplete") @@ -31,7 +57,9 @@ def collect_pairs(pilot, job, row, candidate, baseline, output): identity = build[name] if identity["stack_commit"] != sha or not re.fullmatch(r"[0-9a-f]{64}", identity["cli_sha256"]): raise ValueError("comparison build provenance mismatch") - receipt = {**evidence, "summary": summary, "job_id": job["id"], "run_id": run_id} + archives = arm_archives(pilot, run_id, evidence["runs"]) + receipt = {**evidence, "summary": summary, "job_id": job["id"], "run_id": run_id, + "archives": archives, "worker_archives": worker_archives} write_json(output / f'{row["id"]}-paired.json', receipt) lines = [f'### Paired inference: {row["id"]}', "", f"Main `{baseline}` · candidate `{candidate}`", "", "Server phase timings; six A/A pairs and six alternating A/B pairs.", "", diff --git a/scripts/tests/inference_pairs.py b/scripts/tests/inference_pairs.py index 71c86bde..a07d55d5 100644 --- a/scripts/tests/inference_pairs.py +++ b/scripts/tests/inference_pairs.py @@ -11,7 +11,7 @@ from lib.ci_artifacts import read_json from lib.inference_pairs import PROTOCOL, REPETITIONS, ROUNDS, schedule, summarize -from lib.inference_paired_collect import collect_pairs +from lib.inference_paired_collect import arm_archives, collect_pairs from lib.inference_rendezvous import Coordinator, exchange CANDIDATE, BASELINE = "a" * 40, "b" * 40 @@ -41,6 +41,12 @@ def summary(data): return summarize(data, CANDIDATE, BASELINE, CONFIGURATION) +def archives(data): + return {"artifacts": [ + {"key": f'project/job_test/run_test/raw/{r["experiment"]}-{r["round"]}-{r["arm"]}-evidence.tar.gz', + "kind": "raw", "size_bytes": 123, "sha256": "d" * 64} for r in data["runs"]]} + + class PairedTests(unittest.TestCase): def test_balanced_order_and_identical_source_for_noise_calibration(self): design = schedule(BASELINE, CANDIDATE) @@ -98,7 +104,7 @@ def test_controller_recomputes_native_summary_and_binds_it_to_the_job(self): "runs": [{"id": "run_test", "status": "succeeded"}], "machine": {"host": {"hostname": "host-a"}}} pilot = Mock() - pilot.api.return_value = data + pilot.api.side_effect = [data, archives(data), data] with TemporaryDirectory() as temporary: output = Path(temporary) collect_pairs(pilot, job, {"id": CONFIGURATION, "mode": "standalone"}, @@ -122,14 +128,17 @@ def test_split_collector_rejects_a_different_worker_even_with_valid_rates(self): job = {"id": "job_test", "repo_rev": CANDIDATE, "status": "succeeded", "formation_id": "frm_test", "runs": [{"id": "run_test", "status": "succeeded"}], "machine": {"host": {"hostname": "host-a"}}} - formation = {"status": "succeeded", "members": [ - {"role": "leader", "node": "node-a", "status": "succeeded"}, - {"role": "worker", "node": "node-b", "status": "succeeded"}]} + formation = {"id": "frm_test", "status": "succeeded", "members": [ + {"role": "leader", "node": "node-a", "job_id": "job_test", "status": "succeeded"}, + {"role": "worker", "node": "node-b", "job_id": "job_worker", "status": "succeeded"}]} + worker_job = {"repo_rev": CANDIDATE, "status": "succeeded", + "runs": [{"id": "run_worker", "status": "succeeded"}], + "machine": {"host": {"hostname": "host-b"}}} pilot = Mock() with TemporaryDirectory() as temporary: for valid in (True, False): formation["members"][1]["node"] = "node-b" if valid else "replacement-node" - pilot.api.side_effect = [data, formation] + pilot.api.side_effect = [data, formation, worker_job, archives(data), archives(data)] args = (pilot, job, {"id": configuration, "mode": "split"}, CANDIDATE, BASELINE, Path(temporary)) if valid: collect_pairs(*args) @@ -137,6 +146,19 @@ def test_split_collector_rejects_a_different_worker_even_with_valid_rates(self): with self.assertRaisesRegex(ValueError, "formation"): collect_pairs(*args) + def test_missing_uploaded_arm_is_not_a_successful_comparison(self): + data = evidence() + complete = archives(data) + incomplete = {"artifacts": complete["artifacts"][:-1]} + pilot = Mock() + with patch("lib.inference_paired_collect.time.sleep"): + pilot.api.side_effect = [incomplete, complete] + self.assertEqual(len(arm_archives(pilot, "run_test", data["runs"])), 24) + pilot.api.side_effect = None + pilot.api.return_value = incomplete + with self.assertRaisesRegex(ValueError, "incomplete uploaded"): + arm_archives(pilot, "run_test", data["runs"]) + def test_rendezvous_requires_worker_completion_and_propagates_failure(self): with Coordinator("127.0.0.1", port=0) as coordinator: origin = f"http://127.0.0.1:{coordinator.server.server_address[1]}" From 5634f35e27abf22e8bb20383360f59ba0d6bbce4 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sat, 28 Nov 2026 15:20:58 +1100 Subject: [PATCH 05/22] Support IPv6 coordination and legacy reports during rollout --- scripts/inference-paired.py | 3 ++- scripts/inference-report.sh | 2 +- scripts/lib/inference-report-baseline.sh | 10 ++++++++-- scripts/lib/inference_rendezvous.py | 18 ++++++++++++------ scripts/tests/inference-report.sh | 5 +++++ scripts/tests/inference_pairs.py | 24 +++++++++++++----------- 6 files changed, 41 insertions(+), 21 deletions(-) diff --git a/scripts/inference-paired.py b/scripts/inference-paired.py index 15742c09..dc9aee8b 100644 --- a/scripts/inference-paired.py +++ b/scripts/inference-paired.py @@ -153,7 +153,8 @@ def execute(key, mode, baseline): worker(origin, designs, main, baseline, key, output, {"host": local, "builds": identities}) return remote = next((p["host"] for p in peers if p["role"] == "worker"), None) - with Coordinator(remote) if remote else nullcontext() as coordinator: + leader_host = next((p["host"] for p in peers if p["role"] == "leader"), None) + with Coordinator(remote, host=leader_host) if remote else nullcontext() as coordinator: placements = [local] builds = [{"role": role, **identities}] if coordinator: diff --git a/scripts/inference-report.sh b/scripts/inference-report.sh index 0638e41e..0a691d13 100644 --- a/scripts/inference-report.sh +++ b/scripts/inference-report.sh @@ -47,7 +47,7 @@ fi # shellcheck source=scripts/lib/inference-report-baseline.sh source "$root/scripts/lib/inference-report-baseline.sh" -baseline_note=$(prepare_baseline) +baseline_note=$(prepare_baseline "$directory") cat > "$temporary/body.md" < /dev/null + # Old protected producers remain readable, but their short answers are never warm TPS. jq 'del(.workload) | .decode_tokens=11 | .decode_ms=400' "$fixture/good-rates.json" > "$rates" report @@ -163,4 +167,5 @@ for changed in '.baseline_sha="wrong"' '.source_sha="wrong"' '.run_id="wrong"' ' done cp "$fixture/good-paired.json" "$fixture/evidence/$row-paired.json" BASELINE_SHA=main reject 'mutable baseline' +BASELINE_SHA='' reject 'missing paired baseline' printf '%s\n' 'Inference report contracts passed' diff --git a/scripts/tests/inference_pairs.py b/scripts/tests/inference_pairs.py index a07d55d5..4b7f429d 100644 --- a/scripts/tests/inference_pairs.py +++ b/scripts/tests/inference_pairs.py @@ -160,17 +160,19 @@ def test_missing_uploaded_arm_is_not_a_successful_comparison(self): arm_archives(pilot, "run_test", data["runs"]) def test_rendezvous_requires_worker_completion_and_propagates_failure(self): - with Coordinator("127.0.0.1", port=0) as coordinator: - origin = f"http://127.0.0.1:{coordinator.server.server_address[1]}" - exchange(origin, "/ready", {"host": "worker"}) - self.assertEqual(coordinator.wait(lambda s: s["worker"]), {"host": "worker"}) - coordinator.state["index"] = 2 - self.assertEqual(exchange(origin, "/state")["index"], 2) - exchange(origin, "/done", {"index": 2}) - self.assertTrue(coordinator.wait(lambda s: s["done"] == 2)) - exchange(origin, "/error", {"failed": True}) - with self.assertRaisesRegex(RuntimeError, "worker failed"): - coordinator.wait(lambda s: s["done"] == 3) + for host, address in (("127.0.0.1", "127.0.0.1"), ("::1", "[::1]")): + with self.subTest(host=host): + with Coordinator(host, port=0, host=host) as coordinator: + origin = f"http://{address}:{coordinator.server.server_address[1]}" + exchange(origin, "/ready", {"host": "worker"}) + self.assertEqual(coordinator.wait(lambda s: s["worker"]), {"host": "worker"}) + coordinator.state["index"] = 2 + self.assertEqual(exchange(origin, "/state")["index"], 2) + exchange(origin, "/done", {"index": 2}) + self.assertTrue(coordinator.wait(lambda s: s["done"] == 2)) + exchange(origin, "/error", {"failed": True}) + with self.assertRaisesRegex(RuntimeError, "worker failed"): + coordinator.wait(lambda s: s["done"] == 3) def test_admission_pins_current_main_instead_of_selecting_a_successful_nightly(self): module = run_path(str(Path(__file__).resolve().parents[1] / "inference-plan.py")) From f874ff6b9112c727893c00f418f9553cc0a63b93 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sat, 28 Nov 2026 23:31:00 +1100 Subject: [PATCH 06/22] Register controlled split inference noise pilot --- .gi/templates.yaml | 18 ++++- Justfile | 2 +- ci/README.md | 23 +++++++ ci/automation.just | 1 + ci/inference-noise-pilot.json | 21 ++++++ scripts/inference-execute.py | 13 ++-- scripts/inference-paired.py | 30 ++++++-- scripts/lib/inference_noise.py | 113 +++++++++++++++++++++++++++++++ scripts/tests/inference_noise.py | 111 ++++++++++++++++++++++++++++++ 9 files changed, 318 insertions(+), 14 deletions(-) create mode 100644 ci/inference-noise-pilot.json create mode 100644 scripts/lib/inference_noise.py create mode 100644 scripts/tests/inference_noise.py diff --git a/.gi/templates.yaml b/.gi/templates.yaml index b9c73855..45347101 100644 --- a/.gi/templates.yaml +++ b/.gi/templates.yaml @@ -909,6 +909,22 @@ "kind": "text", "required": true, "default": "legacy" + }, + { + "key": "experiment", + "label": "Measurement protocol", + "kind": "choice", + "choices": [ + { + "value": "paired", + "label": "paired" + }, + { + "value": "noise-pilot", + "label": "noise-pilot" + } + ], + "default": "paired" } ], "budget": { @@ -918,7 +934,7 @@ }, "retain": "never", "key": "inference-pr-split", - "command": "cd \"$JIANYANG_REPO_DIR\" && just inference-paired ${model_key} split ${baseline_sha}", + "command": "cd \"$JIANYANG_REPO_DIR\" && just inference-paired ${model_key} split ${baseline_sha} ${experiment}", "roles": [ { "name": "leader", diff --git a/Justfile b/Justfile index c320ac37..5281c064 100644 --- a/Justfile +++ b/Justfile @@ -201,7 +201,7 @@ inference-execute profile model mode: @"{{ automation_python }}" scripts/inference-execute.py "$@" [positional-arguments] -inference-paired model mode baseline: +inference-paired model mode baseline experiment="paired": @"{{ automation_python }}" scripts/inference-paired.py "$@" [positional-arguments] diff --git a/ci/README.md b/ci/README.md index 3ed6dd7a..a9c7962f 100644 --- a/ci/README.md +++ b/ci/README.md @@ -253,6 +253,29 @@ inconclusive performance is not a claimed win or loss. The PR table reports the interval and noise alongside each estimate. Historical runs never replace a missing paired comparison. +The opt-in `noise-pilot` experiment is a separate diagnostic, registered in +`ci/inference-noise-pilot.json`. It runs two fresh main-only split arms with +cycled/blocked shape order reversed between arms, twelve repetitions per shape +and condition, and unchanged warmup/output lengths. The pinned InferenceKit +wrapper records environment capabilities before timing. One-second GPU and host +telemetry, raw responses, quality checks and mutual peer identities are archived +for both roles. Default boost clocks remain in effect. This instrumented pilot +writes `noise-pilot.json`, never a paired qualification receipt or speed verdict. +Its requests are nested observations for diagnosing noise, not independent rounds. +For example, on an already admitted exclusive split allocation: + +```sh +just inference-paired qwen3-coder-30b-a3b split cc2a27435e798649a9cb938d600d39722e4a2263 noise-pilot +``` + +The registered later performance target is a 2% material effect with at most +1% pointwise 95% CI half-width. Choose and register the final round count from +the pilot before fresh A/A and A/B collection; do not extend a final run until +it becomes significant. Historical six-round inconclusive runs retain their +original verdicts. The current v1 verdict implementation still needs an explicit +within-tolerance decision and sufficient live precision before performance +resolution can be claimed. + Scheduled PR-profile smoke rows run the same design with main in both arms; their paired receipts retain the noise check in Actions artifacts. The twelve AgentX workloads and their saved historical baseline policy are separate. diff --git a/ci/automation.just b/ci/automation.just index b4daae4b..35be4d34 100644 --- a/ci/automation.just +++ b/ci/automation.just @@ -17,6 +17,7 @@ inference-contracts: @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_peer_evidence.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_contracts.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_probe.py + @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_noise.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_pairs.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_paired_execution.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/jy_read_recovery.py diff --git a/ci/inference-noise-pilot.json b/ci/inference-noise-pilot.json new file mode 100644 index 00000000..eb75d196 --- /dev/null +++ b/ci/inference-noise-pilot.json @@ -0,0 +1,21 @@ +{ + "protocol": "DGX Spark noise pilot v1", + "purpose": "Diagnose split within-arm variability; no candidate performance verdict", + "hypothesis": "Cycling short/mid/long shapes causes more timing variance than blocked equal-shape requests", + "baseline_sha": "cc2a27435e798649a9cb938d600d39722e4a2263", + "configuration": "qwen3-coder-30b-a3b-split", + "arms": [["cycled", "blocked"], ["blocked", "cycled"]], + "repetitions_per_condition_shape": 12, + "warmup_tokens": 64, + "measured_tokens": 128, + "paragraphs": [8, 32, 64], + "concurrency": 1, + "temperature": 0, + "seed": 42, + "prefix_policy": "Unique fixed-width three-digit salt per condition position, repetition, shape and warm/measure; prompt token counts must match within each shape", + "gates": ["full output", "zero cached tokens", "constant per-shape prompt tokens", "quality and streaming", "native admission and GPU offload", "mutual formation/source/attempt proof"], + "diagnostics": "One-second GPU clocks/temperature/power/utilization and host CPU/load samples; default boost clocks; InferenceKit doctor before each arm", + "analysis": "Retain every request; compare within-arm CV and temporal clusters by condition/shape/phase; two server arms are diagnostic, not independent performance proof", + "final_claim_target": {"material_effect": 0.02, "maximum_ci95_half_width": 0.01, "round_count": "Register from pilot before fresh main/main and main/PR acquisition; never extend a final run after observing its verdict"}, + "budget": {"approved": true, "max_usd": 0, "max_duration_s": 14400, "exclusive_machines": 2, "authorization": "Existing user-authorized exclusive lab qualification; no preemption or paid rental"} +} diff --git a/scripts/inference-execute.py b/scripts/inference-execute.py index a4af5ef3..1d99cb08 100644 --- a/scripts/inference-execute.py +++ b/scripts/inference-execute.py @@ -89,7 +89,7 @@ def wait_for(server, url, seconds, poll, check): raise RuntimeError("inference server or split leader timed out") -def execute(profile, key, mode, repetitions=1): +def execute(profile, key, mode, repetitions=1, probe=None): sha, gpu = authority() result = plan(profile, sha) if not any(row["id"] == f"{key}-{mode}" for row in result["rows"]): @@ -144,10 +144,13 @@ def execute(profile, key, mode, repetitions=1): score(coordinate, output, profile) if profile == "pr": streaming(coordinate, output) - for repetition in range(repetitions): - probe_output = output if repetition == 0 else output / f"probe-{repetition}" - probe_output.mkdir(parents=True, exist_ok=True) - measure(coordinate, probe_output, repetition if repetitions > 1 else None) + if probe is not None: + probe(coordinate, output) + else: + for repetition in range(repetitions): + probe_output = output if repetition == 0 else output / f"probe-{repetition}" + probe_output.mkdir(parents=True, exist_ok=True) + measure(coordinate, probe_output, repetition if repetitions > 1 else None) scope = "GPU startup, deterministic endpoint repeats and bounded streaming smoke" else: performance(profile, coordinate, context, output, inputs) diff --git a/scripts/inference-paired.py b/scripts/inference-paired.py index dc9aee8b..e7b6b3d1 100644 --- a/scripts/inference-paired.py +++ b/scripts/inference-paired.py @@ -20,6 +20,7 @@ from lib.inference_pairs import PROTOCOL, REPETITIONS, ROUNDS, schedule, summarize from lib.inference_probe import validate_evidence from lib.inference_rendezvous import Coordinator, await_condition, exchange, worker_state +from lib import inference_noise as noise ROOT = Path(__file__).resolve().parents[1] EXECUTE = run_path(str(ROOT / "scripts/inference-execute.py"))["execute"] @@ -100,7 +101,11 @@ def run_arm(design, main, baseline, key, mode, output): source = main if design["source_sha"] == baseline else ROOT try: with revision(source, design["source_sha"], directory): - EXECUTE("pr", key, mode, REPETITIONS) + if design["experiment"] == "noise": + with noise.diagnostics(directory): + EXECUTE("pr", key, mode, probe=noise.probe(design["round"])) + else: + EXECUTE("pr", key, mode, REPETITIONS) finally: # JY uploads top-level files only. Archive each arm, including partial # failures, so raw responses and logs survive native workspace cleanup. @@ -129,7 +134,10 @@ def ready(): raise -def execute(key, mode, baseline): +def execute(key, mode, baseline, experiment="paired"): + diagnostic = experiment == "noise-pilot" + if diagnostic and (f"{key}-{mode}" != noise.registration()["configuration"] or baseline == "legacy"): + raise ValueError("noise pilot requires its registered configuration and main commit") # Old protected controllers can encounter a PR's provisional template before # this controller reaches main. Preserve their original smoke protocol. if baseline == "legacy": @@ -146,7 +154,7 @@ def execute(key, mode, baseline): with baseline_tree(baseline) as main: identities = prepare(main, baseline, candidate, output) local = host(role, node) - designs = schedule(baseline, candidate) + designs = noise.schedule(baseline) if diagnostic else schedule(baseline, candidate) if role == "worker": leader = next(p["host"] for p in peers if p["role"] == "leader") origin = f"http://[{leader}]:9913" if ":" in leader else f"http://{leader}:9913" @@ -164,6 +172,9 @@ def execute(key, mode, baseline): evidence = {"schema_version": 1, "protocol": PROTOCOL, "source_sha": candidate, "baseline_sha": baseline, "configuration": f"{key}-{mode}", "rounds": ROUNDS, "repetitions": REPETITIONS, "placements": placements, "builds": builds, "runs": []} + if diagnostic: + evidence.update(protocol=noise.registration()["protocol"], rounds=2, + repetitions=12, diagnostic_only=True, registration=noise.registration()) try: for index, design in enumerate(designs): if coordinator: @@ -174,16 +185,20 @@ def execute(key, mode, baseline): coordinate = read_json(ROOT / "ci/inference-artifacts.json")[key] coordinate = f'{coordinate["repo"]}@{coordinate["revision"]}' evidence["runs"].append({**design, "placements": placements, "quality": "passed", - "samples": samples(directory, coordinate)}) + "samples": (read_json(directory / "noise-pilot.json") if diagnostic + else samples(directory, coordinate))}) # Preserve the existing standalone nightly smoke receipts too. if design["experiment"] == "ab" and design["arm"] == "b": for name in ("qualification.json", "quality.json", "throughput-probe.json", "provenance.json", "split-admissions.json", "split-peer.json"): if (directory / name).is_file(): shutil.copyfile(directory / name, output / name) - evidence["summary"] = summarize(evidence, candidate, baseline, f"{key}-{mode}") + if not diagnostic: + evidence["summary"] = summarize(evidence, candidate, baseline, f"{key}-{mode}") + else: + evidence["status"] = "diagnostic-complete" finally: - write_json(output / "paired-probe.json", evidence) + write_json(output / ("noise-pilot.json" if diagnostic else "paired-probe.json"), evidence) if __name__ == "__main__": @@ -191,9 +206,10 @@ def execute(key, mode, baseline): parser.add_argument("model") parser.add_argument("mode", choices=("standalone", "split")) parser.add_argument("baseline") + parser.add_argument("experiment", nargs="?", choices=("paired", "noise-pilot"), default="paired") args = parser.parse_args() try: with cancel_on_signal(), time_budget(14400): - execute(args.model, args.mode, args.baseline) + execute(args.model, args.mode, args.baseline, args.experiment) except (OSError, ValueError, KeyError, RuntimeError, subprocess.SubprocessError, KeyboardInterrupt) as error: sys.exit(str(error)) diff --git a/scripts/lib/inference_noise.py b/scripts/lib/inference_noise.py new file mode 100644 index 00000000..848bbb32 --- /dev/null +++ b/scripts/lib/inference_noise.py @@ -0,0 +1,113 @@ +"""Registered shape-order diagnostic; never a candidate speed qualification.""" + +import json +import os +import subprocess +import threading +from contextlib import contextmanager +from datetime import datetime, timezone +from functools import partial +from pathlib import Path + +from .ci_artifacts import digest, read_json, write_json +from .ci_process import command, start, stop +from .inference_probe import PARAGRAPHS, payload, send, validate_response + +ROOT = Path(__file__).resolve().parents[2] +REGISTRATION = ROOT / "ci/inference-noise-pilot.json" + + +def registration(): + return read_json(REGISTRATION) + + +def schedule(baseline): + if baseline != registration()["baseline_sha"]: + raise ValueError("noise pilot baseline differs from registration") + return [{"experiment": "noise", "round": index, "arm": "a", "source_sha": baseline} + for index in range(len(registration()["arms"]))] + + +def requests(condition, repetitions): + cells = [(shape, repeat) for shape in range(len(PARAGRAPHS)) for repeat in range(repetitions)] + if condition == "cycled": + cells.sort(key=lambda cell: (cell[1], cell[0])) + elif condition != "blocked": + raise ValueError("unknown noise pilot condition") + return cells + + +def request(model, position, shape, repeat, warmup): + result = payload(model, shape, warmup) + text = result["messages"][0]["content"].split("\n", 1)[1] + # Match tokenization length while preventing early-prefix reuse. Live gates + # verify the token counts; textual width alone is not tokenization proof. + salt = position * 100 + repeat * len(PARAGRAPHS) + shape + result["messages"][0]["content"] = f'{"W" if warmup else "M"}{salt:03d}\n{text}' + return result + + +def measure(model, output, arm): + design = registration() + evidence = {"protocol": design["protocol"], "registration": design, + "registration_sha256": digest(REGISTRATION), "arm": arm, + "status": "incomplete", "samples": []} + counts = {} + try: + for position, condition in enumerate(design["arms"][arm]): + for shape, repeat in requests(condition, design["repetitions_per_condition_shape"]): + sample = {"condition": condition, "position": position, "shape": shape, "repetition": repeat} + evidence["samples"].append(sample) + for warmup, name in ((True, "warmup"), (False, "measured")): + expected = request(model, position, shape, repeat, warmup) + record = {"started_at": datetime.now(timezone.utc).isoformat()} + sample[name] = record + send(expected, record) + record["completed_at"] = datetime.now(timezone.utc).isoformat() + count = validate_response(record, expected) + if count != counts.setdefault(shape, count): + raise ValueError("noise pilot prompt token shape changed") + evidence["status"] = "passed" + except BaseException as error: + evidence.update(status="failed", error=str(error)) + raise + finally: + write_json(output / "noise-pilot.json", evidence) + + +def probe(arm): + return partial(measure, arm=arm) + + +@contextmanager +def diagnostics(output): + # Run the pinned wrapper outside measured requests. Its records and any + # unsupported profiler capabilities remain in each uploaded arm archive. + doctor = command([str(ROOT / "scripts/inferencekit.sh"), "doctor"], timeout=180, capture_stdout=True, + overrides={"INFERENCEKIT_RUNS_DIR": str(output / "inferencekit")}) + (output / "doctor.log").write_text(doctor) + done = threading.Event() + + def host_samples(): + with (output / "host.jsonl").open("w") as stream: + while not done.is_set(): + record = {"at": datetime.now(timezone.utc).isoformat(), + "load": os.getloadavg(), "cpu": Path("/proc/stat").read_text().splitlines()[0]} + stream.write(json.dumps(record) + "\n") + stream.flush() + done.wait(1) + + with (output / "gpu.csv").open("wb") as stream: + gpu = start(["nvidia-smi", "--query-gpu=timestamp,temperature.gpu,power.draw,clocks.sm,clocks.mem," + "utilization.gpu,utilization.memory,pstate", "--format=csv", "--loop-ms=1000"], + stdout=stream, stderr=subprocess.STDOUT) + thread = threading.Thread(target=host_samples, daemon=True) + thread.start() + try: + yield + if gpu.poll() is not None: + raise RuntimeError("noise pilot GPU telemetry stopped; inspect gpu.csv") + finally: + done.set() + thread.join(timeout=5) + stop(gpu) diff --git a/scripts/tests/inference_noise.py b/scripts/tests/inference_noise.py new file mode 100644 index 00000000..0add95b0 --- /dev/null +++ b/scripts/tests/inference_noise.py @@ -0,0 +1,111 @@ +"""Offline guards for the registered diagnostic; no hardware qualification.""" + +import json +import unittest +from contextlib import nullcontext +from pathlib import Path +from runpy import run_path +from tempfile import TemporaryDirectory +from unittest.mock import Mock, patch + +from lib import inference_noise as noise + +MODEL = "fixture@" + "a" * 40 + + +def reply(request, record): + shape = next(i for i, n in enumerate(noise.PARAGRAPHS) + if request["messages"][0]["content"].count("Record ") == n) + count = request["max_tokens"] + response = {"choices": [{"message": {"content": "answer"}}], + "usage": {"prompt_tokens": 200 + shape, "completion_tokens": count, + "prompt_tokens_details": {"cached_tokens": 0}}, + "timings": {"prompt_n": 200 + shape, "prompt_ms": 100, + "predicted_n": count, "predicted_ms": 200}} + record.update(payload=request, client_ms=350, raw_body=json.dumps(response), response=response) + + +class NoiseTests(unittest.TestCase): + def test_registered_design_balances_order_and_rejects_another_baseline(self): + design = noise.registration() + self.assertEqual(design["arms"], [["cycled", "blocked"], ["blocked", "cycled"]]) + arms = noise.schedule(design["baseline_sha"]) + self.assertEqual(len(arms), 2) + self.assertTrue(all(arm["source_sha"] == design["baseline_sha"] for arm in arms)) + with self.assertRaisesRegex(ValueError, "registration"): + noise.schedule("b" * 40) + + def test_conditions_change_only_order_and_have_unique_equal_width_prefixes(self): + cycled, blocked = (noise.requests(condition, 12) for condition in ("cycled", "blocked")) + self.assertEqual(sorted(cycled), sorted(blocked)) + self.assertEqual(cycled[:3], [(0, 0), (1, 0), (2, 0)]) + self.assertEqual(blocked[:3], [(0, 0), (0, 1), (0, 2)]) + prefixes = {noise.request(MODEL, pos, shape, rep, warm)["messages"][0]["content"].splitlines()[0] + for pos in range(2) for shape, rep in cycled for warm in (True, False)} + self.assertEqual(len(prefixes), 144) + self.assertEqual({len(prefix) for prefix in prefixes}, {4}) + + def test_all_raw_requests_retained_separate_from_paired_qualification(self): + with TemporaryDirectory() as temporary, patch.object(noise, "send", side_effect=reply) as send: + output = Path(temporary) + noise.measure(MODEL, output, 0) + evidence = json.loads((output / "noise-pilot.json").read_text()) + self.assertFalse((output / "paired-probe.json").exists()) + self.assertEqual(send.call_count, 144) + self.assertEqual(evidence["status"], "passed") + self.assertEqual(len(evidence["samples"]), 72) + for sample in evidence["samples"]: + for name in ("warmup", "measured"): + self.assertIn("raw_body", sample[name]) + self.assertIn("started_at", sample[name]) + self.assertIn("completed_at", sample[name]) + + def test_rejects_shape_changes_cache_hits_and_truncation_without_dropping_data(self): + def shape_change(record): + record["response"]["usage"]["prompt_tokens"] += 1 + record["response"]["timings"]["prompt_n"] += 1 + mutations = [shape_change, + lambda r: r["response"]["usage"]["prompt_tokens_details"].update(cached_tokens=1), + lambda r: r["response"]["usage"].update(completion_tokens=1)] + for mutate in mutations: + calls = [] + def send(request, record): + reply(request, record) + calls.append(record) + if len(calls) == 2: + mutate(record) + with self.subTest(mutate=mutate), TemporaryDirectory() as temporary, \ + patch.object(noise, "send", side_effect=send): + output = Path(temporary) + with self.assertRaises(ValueError): + noise.measure(MODEL, output, 0) + evidence = json.loads((output / "noise-pilot.json").read_text()) + self.assertEqual(evidence["status"], "failed") + self.assertEqual(len(evidence["samples"]), 1) + self.assertIn("raw_body", evidence["samples"][0]["measured"]) + + def test_pilot_arm_keeps_standard_native_checks_and_partial_archive(self): + module = run_path(str(noise.ROOT / "scripts/inference-paired.py")) + run = module["run_arm"] + design = noise.schedule(noise.registration()["baseline_sha"])[0] + native = Mock(side_effect=RuntimeError("injected")) + with TemporaryDirectory() as temporary: + output = Path(temporary) + with patch.dict(run.__globals__, EXECUTE=native), \ + patch.object(noise, "diagnostics", return_value=nullcontext()): + with self.assertRaisesRegex(RuntimeError, "injected"): + run(design, output, design["source_sha"], "model", "split", output) + self.assertTrue((output / "noise-0-a-evidence.tar.gz").is_file()) + self.assertEqual(native.call_args.args, ("pr", "model", "split")) + self.assertTrue(callable(native.call_args.kwargs["probe"])) + + def test_pilot_cannot_take_legacy_or_unregistered_configuration(self): + execute = run_path(str(noise.ROOT / "scripts/inference-paired.py"))["execute"] + for model, mode, baseline in (("qwen35-4b", "standalone", noise.registration()["baseline_sha"]), + ("qwen3-coder-30b-a3b", "split", "legacy")): + with self.assertRaisesRegex(ValueError, "registered configuration"): + execute(model, mode, baseline, "noise-pilot") + + +if __name__ == "__main__": + unittest.main() From a7b258839a54a2b7be0779faec3d866b48662a0f Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sat, 28 Nov 2026 23:59:39 +1100 Subject: [PATCH 07/22] Capture native phases in split noise diagnostics --- .gi/templates.yaml | 4 +++ ci/README.md | 6 ++++ ci/inference-noise-profile.json | 51 ++++++++++++++++++++++++++++++++ scripts/inference-paired.py | 24 ++++++++------- scripts/lib/inference_noise.py | 40 +++++++++++++++---------- scripts/tests/inference_noise.py | 28 ++++++++++++++++++ 6 files changed, 128 insertions(+), 25 deletions(-) create mode 100644 ci/inference-noise-profile.json diff --git a/.gi/templates.yaml b/.gi/templates.yaml index 45347101..d4b2ed3f 100644 --- a/.gi/templates.yaml +++ b/.gi/templates.yaml @@ -922,6 +922,10 @@ { "value": "noise-pilot", "label": "noise-pilot" + }, + { + "value": "noise-profile", + "label": "noise-profile" } ], "default": "paired" diff --git a/ci/README.md b/ci/README.md index a9c7962f..fa3791df 100644 --- a/ci/README.md +++ b/ci/README.md @@ -262,6 +262,12 @@ telemetry, raw responses, quality checks and mutual peer identities are archived for both roles. Default boost clocks remain in effect. This instrumented pilot writes `noise-pilot.json`, never a paired qualification receipt or speed verdict. Its requests are nested observations for diagnosing noise, not independent rounds. +The separately registered `noise-profile` experiment in +`ci/inference-noise-profile.json` uses three repetitions per condition and +enables existing native OTLP phase spans on both roles. It retains +`noise-profile.json` and per-arm `phases.jsonl` for correlating chunk counts, +runtime locks, compute, writes and downstream waits. Instrumentation changes +timing; this experiment likewise cannot produce performance qualification. For example, on an already admitted exclusive split allocation: ```sh diff --git a/ci/inference-noise-profile.json b/ci/inference-noise-profile.json new file mode 100644 index 00000000..f9fce3e1 --- /dev/null +++ b/ci/inference-noise-profile.json @@ -0,0 +1,51 @@ +{ + "protocol": "DGX Spark noise phase profile v1", + "purpose": "Locate short-prefill latency clusters inside native compute, runtime locks, activation writes or downstream waits; no speed claim", + "hypothesis": "The recurring ~20ms short-prefill latency step can be localized in existing per-request phase spans", + "baseline_sha": "cc2a27435e798649a9cb938d600d39722e4a2263", + "configuration": "qwen3-coder-30b-a3b-split", + "arms": [ + [ + "cycled", + "blocked" + ], + [ + "blocked", + "cycled" + ] + ], + "repetitions_per_condition_shape": 3, + "warmup_tokens": 64, + "measured_tokens": 128, + "paragraphs": [ + 8, + 32, + 64 + ], + "concurrency": 1, + "temperature": 0, + "seed": 42, + "prefix_policy": "Unique fixed-width three-digit salt per condition position, repetition, shape and warm/measure; prompt token counts must match within each shape", + "gates": [ + "full output", + "zero cached tokens", + "constant per-shape prompt tokens", + "quality and streaming", + "native admission and GPU offload", + "mutual formation/source/attempt proof" + ], + "diagnostics": "Pinned InferenceKit doctor, one-second UTC GPU and host samples, and existing SKIPPY_TELEMETRY_OTLP_FILE debug phase spans on both roles. Instrumented timings cannot qualify performance.", + "analysis": "Retain every request and trace span; correlate prefill chunk counts, stage0 compute, runtime-lock waits, forward writes and downstream waits with each request latency; do not infer GPU kernel time from CPU spans or hide dropped trace records", + "final_claim_target": { + "material_effect": 0.02, + "maximum_ci95_half_width": 0.01, + "round_count": "Register from pilot before fresh main/main and main/PR acquisition; never extend a final run after observing its verdict" + }, + "budget": { + "approved": true, + "max_usd": 0, + "max_duration_s": 14400, + "exclusive_machines": 2, + "authorization": "Existing user-authorized exclusive lab qualification; no preemption or paid rental" + } +} diff --git a/scripts/inference-paired.py b/scripts/inference-paired.py index e7b6b3d1..857b0a1d 100644 --- a/scripts/inference-paired.py +++ b/scripts/inference-paired.py @@ -102,8 +102,9 @@ def run_arm(design, main, baseline, key, mode, output): try: with revision(source, design["source_sha"], directory): if design["experiment"] == "noise": - with noise.diagnostics(directory): - EXECUTE("pr", key, mode, probe=noise.probe(design["round"])) + kind = design.get("diagnostic", "pilot") + with noise.diagnostics(directory, kind): + EXECUTE("pr", key, mode, probe=noise.probe(design["round"], kind)) else: EXECUTE("pr", key, mode, REPETITIONS) finally: @@ -135,8 +136,9 @@ def ready(): def execute(key, mode, baseline, experiment="paired"): - diagnostic = experiment == "noise-pilot" - if diagnostic and (f"{key}-{mode}" != noise.registration()["configuration"] or baseline == "legacy"): + diagnostic = experiment in {"noise-pilot", "noise-profile"} + kind = experiment.removeprefix("noise-") if diagnostic else None + if diagnostic and (f"{key}-{mode}" != noise.registration(kind)["configuration"] or baseline == "legacy"): raise ValueError("noise pilot requires its registered configuration and main commit") # Old protected controllers can encounter a PR's provisional template before # this controller reaches main. Preserve their original smoke protocol. @@ -154,7 +156,7 @@ def execute(key, mode, baseline, experiment="paired"): with baseline_tree(baseline) as main: identities = prepare(main, baseline, candidate, output) local = host(role, node) - designs = noise.schedule(baseline) if diagnostic else schedule(baseline, candidate) + designs = noise.schedule(baseline, kind) if diagnostic else schedule(baseline, candidate) if role == "worker": leader = next(p["host"] for p in peers if p["role"] == "leader") origin = f"http://[{leader}]:9913" if ":" in leader else f"http://{leader}:9913" @@ -173,8 +175,10 @@ def execute(key, mode, baseline, experiment="paired"): "baseline_sha": baseline, "configuration": f"{key}-{mode}", "rounds": ROUNDS, "repetitions": REPETITIONS, "placements": placements, "builds": builds, "runs": []} if diagnostic: - evidence.update(protocol=noise.registration()["protocol"], rounds=2, - repetitions=12, diagnostic_only=True, registration=noise.registration()) + registered = noise.registration(kind) + evidence.update(protocol=registered["protocol"], rounds=len(registered["arms"]), + repetitions=registered["repetitions_per_condition_shape"], + diagnostic_only=True, registration=registered) try: for index, design in enumerate(designs): if coordinator: @@ -185,7 +189,7 @@ def execute(key, mode, baseline, experiment="paired"): coordinate = read_json(ROOT / "ci/inference-artifacts.json")[key] coordinate = f'{coordinate["repo"]}@{coordinate["revision"]}' evidence["runs"].append({**design, "placements": placements, "quality": "passed", - "samples": (read_json(directory / "noise-pilot.json") if diagnostic + "samples": (read_json(directory / f"noise-{kind}.json") if diagnostic else samples(directory, coordinate))}) # Preserve the existing standalone nightly smoke receipts too. if design["experiment"] == "ab" and design["arm"] == "b": @@ -198,7 +202,7 @@ def execute(key, mode, baseline, experiment="paired"): else: evidence["status"] = "diagnostic-complete" finally: - write_json(output / ("noise-pilot.json" if diagnostic else "paired-probe.json"), evidence) + write_json(output / (f"noise-{kind}.json" if diagnostic else "paired-probe.json"), evidence) if __name__ == "__main__": @@ -206,7 +210,7 @@ def execute(key, mode, baseline, experiment="paired"): parser.add_argument("model") parser.add_argument("mode", choices=("standalone", "split")) parser.add_argument("baseline") - parser.add_argument("experiment", nargs="?", choices=("paired", "noise-pilot"), default="paired") + parser.add_argument("experiment", nargs="?", choices=("paired", "noise-pilot", "noise-profile"), default="paired") args = parser.parse_args() try: with cancel_on_signal(), time_budget(14400): diff --git a/scripts/lib/inference_noise.py b/scripts/lib/inference_noise.py index 848bbb32..54bea9d4 100644 --- a/scripts/lib/inference_noise.py +++ b/scripts/lib/inference_noise.py @@ -14,18 +14,18 @@ from .inference_probe import PARAGRAPHS, payload, send, validate_response ROOT = Path(__file__).resolve().parents[2] -REGISTRATION = ROOT / "ci/inference-noise-pilot.json" +REGISTRATIONS = {kind: ROOT / f"ci/inference-noise-{kind}.json" for kind in ("pilot", "profile")} -def registration(): - return read_json(REGISTRATION) +def registration(kind="pilot"): + return read_json(REGISTRATIONS[kind]) -def schedule(baseline): - if baseline != registration()["baseline_sha"]: +def schedule(baseline, kind="pilot"): + if baseline != registration(kind)["baseline_sha"]: raise ValueError("noise pilot baseline differs from registration") - return [{"experiment": "noise", "round": index, "arm": "a", "source_sha": baseline} - for index in range(len(registration()["arms"]))] + return [{"experiment": "noise", "round": index, "arm": "a", "source_sha": baseline, + "diagnostic": kind} for index in range(len(registration(kind)["arms"]))] def requests(condition, repetitions): @@ -47,10 +47,10 @@ def request(model, position, shape, repeat, warmup): return result -def measure(model, output, arm): - design = registration() +def measure(model, output, arm, kind="pilot"): + design = registration(kind) evidence = {"protocol": design["protocol"], "registration": design, - "registration_sha256": digest(REGISTRATION), "arm": arm, + "registration_sha256": digest(REGISTRATIONS[kind]), "arm": arm, "status": "incomplete", "samples": []} counts = {} try: @@ -72,21 +72,23 @@ def measure(model, output, arm): evidence.update(status="failed", error=str(error)) raise finally: - write_json(output / "noise-pilot.json", evidence) + write_json(output / f"noise-{kind}.json", evidence) -def probe(arm): - return partial(measure, arm=arm) +def probe(arm, kind="pilot"): + return partial(measure, arm=arm, kind=kind) @contextmanager -def diagnostics(output): +def diagnostics(output, kind="pilot"): # Run the pinned wrapper outside measured requests. Its records and any # unsupported profiler capabilities remain in each uploaded arm archive. doctor = command([str(ROOT / "scripts/inferencekit.sh"), "doctor"], timeout=180, capture_stdout=True, overrides={"INFERENCEKIT_RUNS_DIR": str(output / "inferencekit")}) (output / "doctor.log").write_text(doctor) done = threading.Event() + trace = "SKIPPY_TELEMETRY_OTLP_FILE" + previous_trace = os.environ.get(trace) def host_samples(): with (output / "host.jsonl").open("w") as stream: @@ -100,14 +102,22 @@ def host_samples(): with (output / "gpu.csv").open("wb") as stream: gpu = start(["nvidia-smi", "--query-gpu=timestamp,temperature.gpu,power.draw,clocks.sm,clocks.mem," "utilization.gpu,utilization.memory,pstate", "--format=csv", "--loop-ms=1000"], - stdout=stream, stderr=subprocess.STDOUT) + overrides={"TZ": "UTC"}, stdout=stream, stderr=subprocess.STDOUT) thread = threading.Thread(target=host_samples, daemon=True) thread.start() try: + if kind == "profile": + os.environ[trace] = str(output / "phases.jsonl") yield if gpu.poll() is not None: raise RuntimeError("noise pilot GPU telemetry stopped; inspect gpu.csv") + if kind == "profile" and not (output / "phases.jsonl").stat().st_size: + raise RuntimeError("noise phase profile is empty") finally: + if previous_trace is None: + os.environ.pop(trace, None) + else: + os.environ[trace] = previous_trace done.set() thread.join(timeout=5) stop(gpu) diff --git a/scripts/tests/inference_noise.py b/scripts/tests/inference_noise.py index 0add95b0..26aebbfa 100644 --- a/scripts/tests/inference_noise.py +++ b/scripts/tests/inference_noise.py @@ -1,6 +1,7 @@ """Offline guards for the registered diagnostic; no hardware qualification.""" import json +import os import unittest from contextlib import nullcontext from pathlib import Path @@ -106,6 +107,33 @@ def test_pilot_cannot_take_legacy_or_unregistered_configuration(self): with self.assertRaisesRegex(ValueError, "registered configuration"): execute(model, mode, baseline, "noise-pilot") + def test_phase_profile_has_its_own_registration_and_output(self): + design = noise.registration("profile") + self.assertNotEqual(design["protocol"], noise.registration()["protocol"]) + with TemporaryDirectory() as temporary, patch.object(noise, "send", side_effect=reply) as send: + output = Path(temporary) + noise.measure(MODEL, output, 0, "profile") + saved = json.loads((output / "noise-profile.json").read_text()) + self.assertFalse((output / "noise-pilot.json").exists()) + self.assertEqual(send.call_count, 36) + self.assertEqual(saved["registration"], design) + self.assertEqual(saved["status"], "passed") + + def test_phase_profile_restores_environment_and_stops_sampler_on_failure(self): + trace = "SKIPPY_TELEMETRY_OTLP_FILE" + gpu, stop, command = Mock(), Mock(), Mock(return_value="doctor") + with TemporaryDirectory() as temporary, patch.dict(os.environ, {trace: "original"}), \ + patch.object(noise, "command", command), patch.object(noise, "start", return_value=gpu), \ + patch.object(noise, "stop", stop), patch.object(noise.threading, "Thread"): + output = Path(temporary) + with self.assertRaisesRegex(RuntimeError, "injected"): + with noise.diagnostics(output, "profile"): + self.assertEqual(os.environ[trace], str(output / "phases.jsonl")) + raise RuntimeError("injected") + self.assertEqual(os.environ[trace], "original") + self.assertEqual((output / "doctor.log").read_text(), "doctor") + stop.assert_called_once_with(gpu) + if __name__ == "__main__": unittest.main() From 2d13715738dd2a3300662d4ffbdb1191a33b6dec Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sun, 29 Nov 2026 00:29:21 +1100 Subject: [PATCH 08/22] Require detailed native spans for noise phase diagnostics --- ci/README.md | 5 +++ ci/inference-noise-profile.json | 4 +-- scripts/inference-execute.py | 15 +++++--- scripts/inference-paired.py | 3 +- scripts/lib/inference_noise.py | 5 +-- scripts/lib/inference_noise_phases.py | 52 +++++++++++++++++++++++++++ scripts/tests/inference_noise.py | 43 ++++++++++++++++++++++ 7 files changed, 118 insertions(+), 9 deletions(-) create mode 100644 scripts/lib/inference_noise_phases.py diff --git a/ci/README.md b/ci/README.md index fa3791df..f8e22a89 100644 --- a/ci/README.md +++ b/ci/README.md @@ -268,6 +268,11 @@ enables existing native OTLP phase spans on both roles. It retains `noise-profile.json` and per-arm `phases.jsonl` for correlating chunk counts, runtime locks, compute, writes and downstream waits. Instrumentation changes timing; this experiment likewise cannot produce performance qualification. +The v2 diagnostic explicitly sets `--telemetry-level debug`; a file sink alone +preserves the server's summary level. Every leader request must have one matching +prefill span with its phase breakdown and response timing. Worker traces must +contain binary decode and message timing spans. Missing detailed spans fail the +diagnostic even when the trace file is nonempty. For example, on an already admitted exclusive split allocation: ```sh diff --git a/ci/inference-noise-profile.json b/ci/inference-noise-profile.json index f9fce3e1..a0477e9d 100644 --- a/ci/inference-noise-profile.json +++ b/ci/inference-noise-profile.json @@ -1,5 +1,5 @@ { - "protocol": "DGX Spark noise phase profile v1", + "protocol": "DGX Spark noise phase profile v2", "purpose": "Locate short-prefill latency clusters inside native compute, runtime locks, activation writes or downstream waits; no speed claim", "hypothesis": "The recurring ~20ms short-prefill latency step can be localized in existing per-request phase spans", "baseline_sha": "cc2a27435e798649a9cb938d600d39722e4a2263", @@ -34,7 +34,7 @@ "native admission and GPU offload", "mutual formation/source/attempt proof" ], - "diagnostics": "Pinned InferenceKit doctor, one-second UTC GPU and host samples, and existing SKIPPY_TELEMETRY_OTLP_FILE debug phase spans on both roles. Instrumented timings cannot qualify performance.", + "diagnostics": "Explicit --telemetry-level debug with SKIPPY_TELEMETRY_OTLP_FILE on both roles; one-second UTC GPU/host samples and pinned InferenceKit doctor. Require per-request prefill breakdown on leader and binary decode/message phase spans on worker. Instrumented timings cannot qualify performance.", "analysis": "Retain every request and trace span; correlate prefill chunk counts, stage0 compute, runtime-lock waits, forward writes and downstream waits with each request latency; do not infer GPU kernel time from CPU spans or hide dropped trace records", "final_claim_target": { "material_effect": 0.02, diff --git a/scripts/inference-execute.py b/scripts/inference-execute.py index 1d99cb08..82399701 100644 --- a/scripts/inference-execute.py +++ b/scripts/inference-execute.py @@ -89,7 +89,16 @@ def wait_for(server, url, seconds, poll, check): raise RuntimeError("inference server or split leader timed out") -def execute(profile, key, mode, repetitions=1, probe=None): +def server_command(worker, phase_profile=False): + args = ["target/debug/skippy", "--debug", "serve", "--startup-timeout-secs", "300"] + if phase_profile: + args += ["--telemetry-level", "debug"] + if not worker: + args += ["--speculative-strategy", "disabled", "--generation-concurrency", "1"] + return args + + +def execute(profile, key, mode, repetitions=1, probe=None, phase_profile=False): sha, gpu = authority() result = plan(profile, sha) if not any(row["id"] == f"{key}-{mode}" for row in result["rows"]): @@ -106,9 +115,7 @@ def execute(profile, key, mode, repetitions=1, probe=None): model = admit(key, inputs) coordinate = f'{inputs["repo"]}@{inputs["revision"]}' context = 4096 if profile == "pr" else 65536 - args = ["target/debug/skippy", "--debug", "serve", "--startup-timeout-secs", "300"] - if not worker: - args += ["--speculative-strategy", "disabled", "--generation-concurrency", "1"] + args = server_command(worker, phase_profile) if mode == "split": args += prepare_split(model, coordinate, profile, context, output, worker) else: diff --git a/scripts/inference-paired.py b/scripts/inference-paired.py index 857b0a1d..3b406df7 100644 --- a/scripts/inference-paired.py +++ b/scripts/inference-paired.py @@ -104,7 +104,8 @@ def run_arm(design, main, baseline, key, mode, output): if design["experiment"] == "noise": kind = design.get("diagnostic", "pilot") with noise.diagnostics(directory, kind): - EXECUTE("pr", key, mode, probe=noise.probe(design["round"], kind)) + EXECUTE("pr", key, mode, probe=noise.probe(design["round"], kind), + phase_profile=kind == "profile") else: EXECUTE("pr", key, mode, REPETITIONS) finally: diff --git a/scripts/lib/inference_noise.py b/scripts/lib/inference_noise.py index 54bea9d4..6c0e19c5 100644 --- a/scripts/lib/inference_noise.py +++ b/scripts/lib/inference_noise.py @@ -12,6 +12,7 @@ from .ci_artifacts import digest, read_json, write_json from .ci_process import command, start, stop from .inference_probe import PARAGRAPHS, payload, send, validate_response +from .inference_noise_phases import verify_phases ROOT = Path(__file__).resolve().parents[2] REGISTRATIONS = {kind: ROOT / f"ci/inference-noise-{kind}.json" for kind in ("pilot", "profile")} @@ -111,8 +112,8 @@ def host_samples(): yield if gpu.poll() is not None: raise RuntimeError("noise pilot GPU telemetry stopped; inspect gpu.csv") - if kind == "profile" and not (output / "phases.jsonl").stat().st_size: - raise RuntimeError("noise phase profile is empty") + if kind == "profile": + verify_phases(output, os.environ.get("JIANYANG_ROLE", "leader")) finally: if previous_trace is None: os.environ.pop(trace, None) diff --git a/scripts/lib/inference_noise_phases.py b/scripts/lib/inference_noise_phases.py new file mode 100644 index 00000000..0470ae9f --- /dev/null +++ b/scripts/lib/inference_noise_phases.py @@ -0,0 +1,52 @@ +"""Require useful native phase evidence, not merely a nonempty trace file.""" + +import json +import math +from collections import Counter +from datetime import datetime + +from .ci_artifacts import digest, read_json, write_json + + +def verify_phases(output, role): + path = output / "phases.jsonl" + counts, prefills = Counter(), [] + with path.open() as stream: + for line in stream: + for resource in json.loads(line).get("resourceSpans", []): + for scope in resource.get("scopeSpans", []): + for span in scope.get("spans", []): + counts[span["name"]] += 1 + if span["name"] == "stage.openai_prefill": + prefills.append(span) + proof = {"status": "passed", "role": role, "trace_sha256": digest(path), "span_counts": dict(counts)} + if role == "worker": + if not all(counts[name] for name in ("stage.binary_llama_decode", "stage.binary_message_timing")): + raise ValueError("noise profile lacks detailed worker phase spans") + elif role == "leader": + samples = read_json(output / "noise-profile.json")["samples"] + matched = 0 + for sample in samples: + for name in ("warmup", "measured"): + request = sample[name] + begin, end = (datetime.fromisoformat(request[key]).timestamp() + for key in ("started_at", "completed_at")) + spans = [span for span in prefills if begin <= int(span["startTimeUnixNano"]) / 1e9 <= end] + if len(spans) != 1: + raise ValueError("noise profile lacks a unique prefill span for each request") + attributes = {row["key"]: row["value"] for row in spans[0].get("attributes", [])} + required = ("stage0_compute_ms", "runtime_lock_wait_ms", "forward_write_ms", "downstream_wait_ms") + if not all("llama_stage." + key in attributes for key in required): + raise ValueError("noise profile lacks prefill phase breakdown") + elapsed = attributes.get("llama_stage.elapsed_ms", {}) + millis = float(elapsed.get("doubleValue", elapsed.get("intValue", "nan"))) + if not math.isfinite(millis) or abs(millis - request["response"]["timings"]["prompt_ms"]) >= 1: + raise ValueError("noise profile span differs from response prefill timing") + matched += 1 + if not matched: + raise ValueError("noise profile lacks measured requests") + proof["requests_with_prefill_breakdown"] = matched + else: + raise ValueError("unknown noise profile role") + write_json(output / "phase-proof.json", proof) + return proof diff --git a/scripts/tests/inference_noise.py b/scripts/tests/inference_noise.py index 26aebbfa..5289de24 100644 --- a/scripts/tests/inference_noise.py +++ b/scripts/tests/inference_noise.py @@ -10,6 +10,7 @@ from unittest.mock import Mock, patch from lib import inference_noise as noise +from lib.inference_noise_phases import verify_phases MODEL = "fixture@" + "a" * 40 @@ -134,6 +135,48 @@ def test_phase_profile_restores_environment_and_stops_sampler_on_failure(self): self.assertEqual((output / "doctor.log").read_text(), "doctor") stop.assert_called_once_with(gpu) + def test_both_native_roles_explicitly_enable_debug_only_for_phase_diagnostics(self): + command = run_path(str(noise.ROOT / "scripts/inference-execute.py"))["server_command"] + for worker in (True, False): + self.assertNotIn("--telemetry-level", command(worker)) + args = command(worker, phase_profile=True) + self.assertEqual(args[args.index("--telemetry-level") + 1], "debug") + + def test_nonempty_summary_trace_cannot_pass_phase_diagnostics(self): + with TemporaryDirectory() as temporary: + output = Path(temporary) + (output / "phases.jsonl").write_text(json.dumps({"resourceSpans": [{"scopeSpans": [ + {"spans": [{"name": "stage.openai_request_summary"}]}]}]}) + "\n") + (output / "noise-profile.json").write_text(json.dumps({"samples": [{"warmup": { + "started_at": "2026-11-28T00:00:00+00:00", "completed_at": "2026-11-28T00:00:01+00:00"}}]})) + for role in ("leader", "worker"): + with self.subTest(role=role), self.assertRaisesRegex(ValueError, "lacks"): + verify_phases(output, role) + self.assertFalse((output / "phase-proof.json").exists()) + + def test_each_request_needs_a_matching_prefill_breakdown(self): + def request(start, end): + return {"started_at": f"1970-01-01T00:00:0{start}+00:00", + "completed_at": f"1970-01-01T00:00:0{end}+00:00", + "response": {"timings": {"prompt_ms": 100}}} + attrs = [{"key": "llama_stage." + name, "value": {"doubleValue": value}} + for name, value in (("stage0_compute_ms", 60), ("runtime_lock_wait_ms", 0), + ("forward_write_ms", 1), ("downstream_wait_ms", 39), ("elapsed_ms", 100))] + spans = [{"name": "stage.openai_prefill", "startTimeUnixNano": str(start), "attributes": attrs} + for start in (100000000, 2100000000)] + with TemporaryDirectory() as temporary: + output = Path(temporary) + (output / "noise-profile.json").write_text(json.dumps({"samples": [ + {"warmup": request(0, 1), "measured": request(2, 3)}]})) + def trace(records): + (output / "phases.jsonl").write_text(json.dumps({"resourceSpans": [ + {"scopeSpans": [{"spans": records}]}]}) + "\n") + trace(spans) + self.assertEqual(verify_phases(output, "leader")["requests_with_prefill_breakdown"], 2) + trace(spans[:1]) + with self.assertRaisesRegex(ValueError, "unique prefill"): + verify_phases(output, "leader") + if __name__ == "__main__": unittest.main() From f5cab8d5afbe4c7fb0c9434d8956c5e78f798e77 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sun, 29 Nov 2026 01:20:41 +1100 Subject: [PATCH 09/22] Build both qualification revisions with shared release policy --- Justfile | 4 +- ci/README.md | 11 ++++- ci/inference-noise-pilot.json | 55 ++++++++++++++++++--- ci/inference-noise-profile.json | 11 ++++- scripts/inference-build.py | 48 +++++++++++++----- scripts/inference-execute.py | 6 +-- scripts/inference-paired.py | 6 ++- scripts/lib/inference_checks.py | 4 +- scripts/lib/inference_inputs.py | 10 ++-- scripts/tests/inference_build.py | 32 ++++++++++-- scripts/tests/inference_paired_execution.py | 10 +++- 11 files changed, 156 insertions(+), 41 deletions(-) diff --git a/Justfile b/Justfile index 5281c064..40721d4c 100644 --- a/Justfile +++ b/Justfile @@ -209,12 +209,12 @@ inference-cancel ledger="target/ci-evidence/inference/jobs.json": @"{{ automation_python }}" scripts/inference-dispatch.py cancel "$@" inference-build: - @"{{ automation_python }}" scripts/inference-build.py + @"{{ automation_python }}" "{{ justfile_directory() }}/scripts/inference-build.py" inference-build-uncached: @command -v hf uv nvidia-smi @SCCACHE_BASEDIRS="$PWD" LLAMA_STAGE_BACKEND=cuda LLAMA_STAGE_CUDA_ARCHITECTURES=121 LLAMA_STAGE_LINK_MODE=static just llama-build - @LLAMA_STAGE_BACKEND=cuda LLAMA_STAGE_CUDA_ARCHITECTURES=121 LLAMA_STAGE_LINK_MODE=static cargo build --locked -p skippy-cli -p skippy-correctness + @LLAMA_STAGE_BACKEND=cuda LLAMA_STAGE_CUDA_ARCHITECTURES=121 LLAMA_STAGE_LINK_MODE=static cargo build --release --locked -p skippy-cli -p skippy-correctness # Linux diagnostic: retain all MiMo2 graph assertions and report peak memory. native-contract-build: llama-prepare diff --git a/ci/README.md b/ci/README.md index f8e22a89..96546868 100644 --- a/ci/README.md +++ b/ci/README.md @@ -229,6 +229,15 @@ run inside the same exclusive job or atomic two-Spark formation. The two roles keep their placement and wait at a barrier after each restarted server arm. Build hashes, source commits, host/kernel/driver identities, raw responses and client timings remain in the lab evidence. All builds finish before measurement. +Both source trees use the candidate's pinned qualification build driver and +Just recipes, with each tree supplying its own source and native inputs. Rust +uses the release profile at opt-level 3; the CUDA native libraries retain their +Release/static configuration. Executables are installed in +`target/inference-bin`, and the v3 cache identity records the shared driver hash, +source, release settings, features, linkage and environment overrides. Different +main/candidate build policies fail admission. This qualifies the source-built +static CUDA configuration; it does not qualify a shipped dynamic runtime package. +Earlier dev-profile receipts retain their original source and diagnostic scope. Each arm has a top-level evidence archive because JY does not upload nested directories. Collection requires every arm archive in the uploaded manifest, including the worker's archives for split runs, and retains their hashes. @@ -268,7 +277,7 @@ enables existing native OTLP phase spans on both roles. It retains `noise-profile.json` and per-arm `phases.jsonl` for correlating chunk counts, runtime locks, compute, writes and downstream waits. Instrumentation changes timing; this experiment likewise cannot produce performance qualification. -The v2 diagnostic explicitly sets `--telemetry-level debug`; a file sink alone +The phase diagnostic explicitly sets `--telemetry-level debug`; a file sink alone preserves the server's summary level. Every leader request must have one matching prefill span with its phase breakdown and response timing. Worker traces must contain binary decode and message timing spans. Missing detailed spans fail the diff --git a/ci/inference-noise-pilot.json b/ci/inference-noise-pilot.json index eb75d196..01a7fb4e 100644 --- a/ci/inference-noise-pilot.json +++ b/ci/inference-noise-pilot.json @@ -1,21 +1,60 @@ { - "protocol": "DGX Spark noise pilot v1", - "purpose": "Diagnose split within-arm variability; no candidate performance verdict", - "hypothesis": "Cycling short/mid/long shapes causes more timing variance than blocked equal-shape requests", + "protocol": "DGX Spark release noise pilot v1", + "purpose": "Diagnose whether short-prefill latency steps persist in optimized Rust release builds; no candidate verdict or final power estimate", + "hypothesis": "Unoptimized Rust framing/conversion contributes to the observed short-prefill delay distribution; retain both cycled and blocked conditions to expose order sensitivity", "baseline_sha": "cc2a27435e798649a9cb938d600d39722e4a2263", "configuration": "qwen3-coder-30b-a3b-split", - "arms": [["cycled", "blocked"], ["blocked", "cycled"]], + "arms": [ + [ + "cycled", + "blocked" + ], + [ + "blocked", + "cycled" + ] + ], "repetitions_per_condition_shape": 12, "warmup_tokens": 64, "measured_tokens": 128, - "paragraphs": [8, 32, 64], + "paragraphs": [ + 8, + 32, + 64 + ], "concurrency": 1, "temperature": 0, "seed": 42, "prefix_policy": "Unique fixed-width three-digit salt per condition position, repetition, shape and warm/measure; prompt token counts must match within each shape", - "gates": ["full output", "zero cached tokens", "constant per-shape prompt tokens", "quality and streaming", "native admission and GPU offload", "mutual formation/source/attempt proof"], + "gates": [ + "full output", + "zero cached tokens", + "constant per-shape prompt tokens", + "quality and streaming", + "native admission and GPU offload", + "mutual formation/source/attempt proof" + ], "diagnostics": "One-second GPU clocks/temperature/power/utilization and host CPU/load samples; default boost clocks; InferenceKit doctor before each arm", "analysis": "Retain every request; compare within-arm CV and temporal clusters by condition/shape/phase; two server arms are diagnostic, not independent performance proof", - "final_claim_target": {"material_effect": 0.02, "maximum_ci95_half_width": 0.01, "round_count": "Register from pilot before fresh main/main and main/PR acquisition; never extend a final run after observing its verdict"}, - "budget": {"approved": true, "max_usd": 0, "max_duration_s": 14400, "exclusive_machines": 2, "authorization": "Existing user-authorized exclusive lab qualification; no preemption or paid rental"} + "final_claim_target": { + "material_effect": 0.02, + "maximum_ci95_half_width": 0.01, + "round_count": "Register from pilot before fresh main/main and main/PR acquisition; never extend a final run after observing its verdict" + }, + "budget": { + "approved": true, + "max_usd": 0, + "max_duration_s": 14400, + "exclusive_machines": 2, + "authorization": "Existing user-authorized exclusive lab qualification; no preemption or paid rental" + }, + "build_policy": { + "rust_profile": "release", + "rust_opt_level": 3, + "native_profile": "Release", + "linkage": "static", + "cuda_architectures": "121", + "same_pinned_harness_both_sources": true, + "scope": "Source-built CUDA qualification; not shipped dynamic package" + } } diff --git a/ci/inference-noise-profile.json b/ci/inference-noise-profile.json index a0477e9d..2b2830c8 100644 --- a/ci/inference-noise-profile.json +++ b/ci/inference-noise-profile.json @@ -1,5 +1,5 @@ { - "protocol": "DGX Spark noise phase profile v2", + "protocol": "DGX Spark release noise phase profile v1", "purpose": "Locate short-prefill latency clusters inside native compute, runtime locks, activation writes or downstream waits; no speed claim", "hypothesis": "The recurring ~20ms short-prefill latency step can be localized in existing per-request phase spans", "baseline_sha": "cc2a27435e798649a9cb938d600d39722e4a2263", @@ -47,5 +47,14 @@ "max_duration_s": 14400, "exclusive_machines": 2, "authorization": "Existing user-authorized exclusive lab qualification; no preemption or paid rental" + }, + "build_policy": { + "rust_profile": "release", + "rust_opt_level": 3, + "native_profile": "Release", + "linkage": "static", + "cuda_architectures": "121", + "same_pinned_harness_both_sources": true, + "scope": "Source-built CUDA qualification; not shipped dynamic package" } } diff --git a/scripts/inference-build.py b/scripts/inference-build.py index b5f47785..ad8bb478 100644 --- a/scripts/inference-build.py +++ b/scripts/inference-build.py @@ -10,11 +10,27 @@ import subprocess import sys import tempfile +import tomllib from pathlib import Path from lib.ci_artifacts import digest, read_json, write_json from lib.ci_process import cancel_on_signal, capture, command -from lib.inference_inputs import BINARIES, BUILD_IDENTITY, DEBUG_DIR, check_executables, identity, lock +from lib.inference_inputs import BINARIES, BUILD_IDENTITY, BINARY_DIR, check_executables, identity, lock + +HARNESS_ROOT = Path(__file__).resolve().parents[1] + + +def build_policy(): + files = ("Justfile", "scripts/inference-build.py", "scripts/lib/inference_inputs.py") + hashes = {name: digest(HARNESS_ROOT / name) for name in files} + release = tomllib.loads(Path("Cargo.toml").read_text()).get("profile", {}).get("release", {}) + overrides = {k: v for k, v in os.environ.items() if k.startswith("CARGO_PROFILE_RELEASE_")} + if str(overrides.get("CARGO_PROFILE_RELEASE_OPT_LEVEL", release.get("opt-level", 3))) != "3": + raise ValueError("inference qualification requires release opt-level 3") + return {"cargo_profile": "release", "rust_features": [], "native_link": "static", + "rust_release": release, "release_overrides": overrides, + "harness_commit": capture(["git", "-C", str(HARNESS_ROOT), "rev-parse", "HEAD"]).strip(), + "harness_sha256": cache_key(hashes)} def cache_key(inputs): @@ -32,37 +48,40 @@ def native_inputs(): def dependency_key(inputs): - return cache_key({name: value for name, value in inputs.items() if name != "source"}) + dependencies = {name: value for name, value in inputs.items() if name != "source"} + if "policy" in dependencies: + dependencies["policy"] = {k: v for k, v in dependencies["policy"].items() if k != "harness_commit"} + return cache_key(dependencies) def source_inputs(sha): environment = { name: value for name, value in os.environ.items() - if name.startswith(("LLAMA_", "SKIPPY_")) or name in { + if name.startswith(("LLAMA_", "SKIPPY_", "CARGO_PROFILE_")) or name in { "CC", "CXX", "CUDACXX", "CFLAGS", "CXXFLAGS", "RUSTFLAGS", "CARGO_ENCODED_RUSTFLAGS" } } return { - "schema": 2, "native_inputs_sha256": native_inputs(), "source": sha, + "schema": 3, "native_inputs_sha256": native_inputs(), "source": sha, "policy": build_policy(), "os": platform.system().lower(), "arch": platform.machine(), "compiler_extra_files": {path: digest(Path(path)) for path in filter(None, os.environ.get("SCCACHE_EXTRAFILES", "").split(os.pathsep))}, "cargo_lock_sha256": digest(Path("Cargo.lock")), "rust": capture(["rustc", "-vV"]), "cuda": capture(["nvcc", "--version"]), "cxx": capture(["c++", "--version"]), "cmake": capture(["cmake", "--version"]), "backend": "cuda", "architectures": "121", - "link": "static", "debug": 0, "environment": environment, + "link": "static", "profile": "release", "environment": environment, } def install_binaries(directory): - DEBUG_DIR.mkdir(parents=True, exist_ok=True) + BINARY_DIR.mkdir(parents=True, exist_ok=True) for name in BINARIES: - shutil.copy(directory / name, DEBUG_DIR / name) + shutil.copy(directory / name, BINARY_DIR / name) def build(sha, root, inputs, key, cached): dependencies = dependency_key(inputs) - cargo_root = root.parent / "cargo-v2" + cargo_root = root.parent / "cargo-v3" cargo_root.mkdir(parents=True, exist_ok=True) with lock(cargo_root / f"{dependencies}.lock"): cargo_target = cargo_root / dependencies @@ -74,7 +93,7 @@ def build(sha, root, inputs, key, cached): environment = { "CARGO_TARGET_DIR": str(cargo_target), "SCCACHE_DIR": str(root.parent / "compiler"), "SCCACHE_BASEDIRS": str(Path.cwd()), "CARGO_INCREMENTAL": "0", "SCCACHE_SERVER_PORT": "4227", - "SCCACHE_CACHE_SIZE": "20G", "CARGO_PROFILE_DEV_DEBUG": "0", + "SCCACHE_CACHE_SIZE": "20G", "SCCACHE_EXTRAFILES": os.pathsep.join(extra_files), } sccache = shutil.which("sccache") @@ -85,8 +104,10 @@ def build(sha, root, inputs, key, cached): except subprocess.CalledProcessError: pass command([sccache, "--start-server"], overrides=environment, timeout=30) - command(["just", "inference-build-uncached"], overrides=environment, timeout=7200) - install_binaries(cargo_target / "debug") + command(["just", "--justfile", str(HARNESS_ROOT / "Justfile"), + "--working-directory", str(Path.cwd()), "inference-build-uncached"], + overrides=environment, timeout=7200) + install_binaries(cargo_target / "release") build_id = identity(sha) build_id.update(cache_key=key, dependency_cache_key=dependencies, build_inputs=inputs, cache_hit=False) write_json(BUILD_IDENTITY, build_id) @@ -94,7 +115,7 @@ def build(sha, root, inputs, key, cached): stage = Path(tmp) / "entry" stage.mkdir() for name in BINARIES: - shutil.copy(DEBUG_DIR / name, stage / name) + shutil.copy(BINARY_DIR / name, stage / name) write_json(stage / "identity.json", build_id) stage.rename(cached) if sccache: @@ -108,7 +129,8 @@ def main(): command(["git", "diff", "--exit-code", "HEAD"], timeout=30) inputs = source_inputs(sha) key = cache_key(inputs) - root = Path(os.environ["HOME"]) / ".cache/skippy/inference-build-v2" + command(["git", "-C", str(HARNESS_ROOT), "diff", "--exit-code", "HEAD"], timeout=30) + root = Path(os.environ["HOME"]) / ".cache/skippy/inference-build-v3" root.mkdir(parents=True, exist_ok=True) cached = root / key with lock(root / f"{key}.lock"): diff --git a/scripts/inference-execute.py b/scripts/inference-execute.py index 82399701..f134e0f1 100644 --- a/scripts/inference-execute.py +++ b/scripts/inference-execute.py @@ -18,7 +18,7 @@ from lib.ci_process import cancel_on_signal, capture, command, start, stop from lib.ci_smoke import curl from lib.inference_checks import ENDPOINT, numerical, offload, performance, score, streaming -from lib.inference_inputs import admit, fixture, input_hashes, record +from lib.inference_inputs import BINARY_DIR, admit, fixture, input_hashes, record from lib.inference_ladder import plan from lib.inference_admission import split_admissions_digest from lib.inference_probe import measure @@ -59,7 +59,7 @@ def address(ip, port): with tempfile.TemporaryDirectory() as tmp: directory = Path(tmp) / "plan" args = [ - "target/debug/skippy", "plan-split", "--model-path", str(model), "--model-id", + str(BINARY_DIR / "skippy"), "plan-split", "--model-path", str(model), "--model-id", coordinate, "--worker", address(leader, 9400), "--worker", address(follower, 9401), "--ctx-size", str(context), "--n-gpu-layers", "999", "--output-dir", str(directory), ] @@ -90,7 +90,7 @@ def wait_for(server, url, seconds, poll, check): def server_command(worker, phase_profile=False): - args = ["target/debug/skippy", "--debug", "serve", "--startup-timeout-secs", "300"] + args = [str(BINARY_DIR / "skippy"), "--debug", "serve", "--startup-timeout-secs", "300"] if phase_profile: args += ["--telemetry-level", "debug"] if not worker: diff --git a/scripts/inference-paired.py b/scripts/inference-paired.py index 3b406df7..350b7fa7 100644 --- a/scripts/inference-paired.py +++ b/scripts/inference-paired.py @@ -87,11 +87,15 @@ def prepare(main, baseline, candidate, output): if digest(ROOT / path) != digest(main / path): raise ValueError("paired comparison model or quality fixtures changed") with revision(main, baseline, output): - command(["just", "inference-build"], timeout=7200) + command(["just", "--justfile", str(ROOT / "Justfile"), + "--working-directory", str(main), "inference-build"], timeout=7200) identities = {"main": read_json(main / "target/inference-build.json"), "candidate": read_json(ROOT / "target/inference-build.json")} if identities["main"]["stack_commit"] != baseline or identities["candidate"]["stack_commit"] != candidate: raise ValueError("paired comparison executable source mismatch") + policies = [identity["build_inputs"]["policy"] for identity in identities.values()] + if policies[0] != policies[1] or policies[0]["cargo_profile"] != "release": + raise ValueError("paired comparison build policies differ or are not release") return identities diff --git a/scripts/lib/inference_checks.py b/scripts/lib/inference_checks.py index 7b92ddd0..4e3522d1 100644 --- a/scripts/lib/inference_checks.py +++ b/scripts/lib/inference_checks.py @@ -9,7 +9,7 @@ from .ci_artifacts import read_json, write_json from .ci_process import command from .ci_smoke import curl -from .inference_inputs import downloaded_path, safe_relative +from .inference_inputs import BINARY_DIR, downloaded_path, safe_relative ENDPOINT = "http://127.0.0.1:9337" @@ -18,7 +18,7 @@ def numerical(model, coordinate, fixture, output): layers = fixture["layers"] for kind in ("chain", "state-handoff"): args = [ - "target/debug/skippy-correctness", kind, "--model", str(model), "--model-id", + str(BINARY_DIR / "skippy-correctness"), kind, "--model", str(model), "--model-id", coordinate, "--layer-end", str(layers), "--n-gpu-layers", "0", "--ctx-size", "512", "--report-out", str(output / f"{kind}.json"), ] diff --git a/scripts/lib/inference_inputs.py b/scripts/lib/inference_inputs.py index d576a29a..6904541a 100644 --- a/scripts/lib/inference_inputs.py +++ b/scripts/lib/inference_inputs.py @@ -17,7 +17,7 @@ "client_lock_sha256": "ci/aiperf-requirements.lock", "corpus_manifest_sha256": "ci/inference-corpus.json", } -DEBUG_DIR = Path("target/debug") +BINARY_DIR = Path("target/inference-bin") BUILD_IDENTITY = Path("target/inference-build.json") @@ -41,8 +41,8 @@ def check_executables(directory, identity, sha): def record(output, sha): identity = read_json(BUILD_IDENTITY) - check_executables(DEBUG_DIR, identity, sha) - identity.update(input_hashes(), harness="aiperf-0.13.0-python-3.12") + check_executables(BINARY_DIR, identity, sha) + identity.update(input_hashes(), harness="skippy-native-qualification-v3") write_json(output / "provenance.json", identity) @@ -64,9 +64,9 @@ def identity(sha): return { "stack_commit": sha, "native_upstream": Path("llama_cpp/upstream.txt").read_text().strip(), "native_tree": capture(["git", "-C", ".deps/llama.cpp", "rev-parse", "HEAD^{tree}"]).strip(), - "native_abi": abi, "harness": "aiperf-0.13.0-python-3.12", + "native_abi": abi, "harness": "skippy-native-qualification-v3", "cuda_compiler": capture([compiler, "--version"]), **input_hashes(), - **{field: digest(DEBUG_DIR / name) for name, field in BINARIES.items()}, + **{field: digest(BINARY_DIR / name) for name, field in BINARIES.items()}, } diff --git a/scripts/tests/inference_build.py b/scripts/tests/inference_build.py index 2b2104ca..f3b41fcc 100644 --- a/scripts/tests/inference_build.py +++ b/scripts/tests/inference_build.py @@ -13,6 +13,20 @@ class NativeCacheTests(unittest.TestCase): + def test_policy_records_actual_release_configuration_and_rejects_unoptimized_override(self): + policy = BUILD["build_policy"] + with TemporaryDirectory() as temporary, chdir(temporary): + Path("Cargo.toml").write_text('[profile.release]\nlto = "thin"\ncodegen-units = 1\n') + with patch.dict(policy.__globals__, capture=lambda _: "a" * 40), \ + patch.dict(os.environ, {"CARGO_PROFILE_RELEASE_OPT_LEVEL": "3"}): + observed = policy() + self.assertEqual(observed["cargo_profile"], "release") + self.assertEqual(observed["rust_release"], {"lto": "thin", "codegen-units": 1}) + self.assertEqual(observed["release_overrides"]["CARGO_PROFILE_RELEASE_OPT_LEVEL"], "3") + os.environ["CARGO_PROFILE_RELEASE_OPT_LEVEL"] = "0" + with self.assertRaisesRegex(ValueError, "opt-level 3"): + policy() + def test_native_transition_isolates_dependencies_but_rust_edits_reuse_them(self): old = {"schema": 2, "source": "a" * 40, "native_inputs_sha256": "1" * 64} new = dict(old, source="b" * 40, native_inputs_sha256="2" * 64) @@ -22,6 +36,16 @@ def test_native_transition_isolates_dependencies_but_rust_edits_reuse_them(self) self.assertEqual(BUILD["dependency_key"](old), BUILD["dependency_key"](dict(old))) self.assertNotEqual(BUILD["cache_key"](new), BUILD["cache_key"](rust_edit)) + def test_release_policy_changes_invalidate_cache_but_commit_only_does_not_discard_dependencies(self): + inputs = {"source": "a" * 40, "policy": {"cargo_profile": "release", "harness_commit": "a" * 40, + "harness_sha256": "c" * 64}} + next_commit = {**inputs, "source": "b" * 40, + "policy": {**inputs["policy"], "harness_commit": "b" * 40}} + self.assertEqual(BUILD["dependency_key"](inputs), BUILD["dependency_key"](next_commit)) + self.assertNotEqual(BUILD["cache_key"](inputs), BUILD["cache_key"](next_commit)) + dev = {**inputs, "policy": {**inputs["policy"], "cargo_profile": "dev"}} + self.assertNotEqual(BUILD["dependency_key"](inputs), BUILD["dependency_key"](dev)) + def test_patch_removal_and_native_build_changes_invalidate_identity(self): native_inputs = BUILD["native_inputs"] with patch.dict(native_inputs.__globals__, capture=lambda args: "100644 blob old patch\n"): @@ -45,11 +69,13 @@ def command(args, overrides, timeout): identity=lambda _: {}), \ patch("shutil.which", return_value="/bin/sccache"), \ patch("shutil.copy"), patch("pathlib.Path.rename"): - root = Path(tmp) / "inference-build-v2" + root = Path(tmp) / "inference-build-v3" root.mkdir() build(inputs["source"], root, inputs, "key", root / "key") - compiler = next(env for args, env in calls if args == ["just", "inference-build-uncached"]) - self.assertIn("cargo-v2", compiler["CARGO_TARGET_DIR"]) + args, compiler = next((args, env) for args, env in calls if args[-1] == "inference-build-uncached") + self.assertEqual(args[1:3], ["--justfile", str(BUILD["HARNESS_ROOT"] / "Justfile")]) + self.assertIn("cargo-v3", compiler["CARGO_TARGET_DIR"]) + self.assertNotIn("CARGO_PROFILE_DEV_DEBUG", compiler) self.assertEqual(compiler["SCCACHE_EXTRAFILES"].split(os.pathsep)[0], "/existing/input") self.assertTrue(compiler["SCCACHE_EXTRAFILES"].endswith("target/inference-native-inputs.json")) self.assertNotIn("SCCACHE_RECACHE", compiler) diff --git a/scripts/tests/inference_paired_execution.py b/scripts/tests/inference_paired_execution.py index a3f58614..8660644e 100644 --- a/scripts/tests/inference_paired_execution.py +++ b/scripts/tests/inference_paired_execution.py @@ -63,11 +63,17 @@ def test_builds_main_once_before_measurement_and_rejects_changed_fixtures(self): (directory / "target").mkdir() for name in ("inference-artifacts.json", "inference-quality.json"): write_json(directory / "ci" / name, {}) - write_json(directory / "target/inference-build.json", {"stack_commit": sha}) + write_json(directory / "target/inference-build.json", { + "stack_commit": sha, "build_inputs": {"policy": {"cargo_profile": "release"}}}) command = Mock() with patch.dict(prepare.__globals__, ROOT=candidate, command=command): prepare(main, BASELINE, CANDIDATE, output) - command.assert_called_once_with(["just", "inference-build"], timeout=7200) + command.assert_called_once_with(["just", "--justfile", str(candidate / "Justfile"), + "--working-directory", str(main), "inference-build"], timeout=7200) + write_json(main / "target/inference-build.json", { + "stack_commit": BASELINE, "build_inputs": {"policy": {"cargo_profile": "dev"}}}) + with self.assertRaisesRegex(ValueError, "build policies"): + prepare(main, BASELINE, CANDIDATE, output) write_json(main / "ci/inference-artifacts.json", {"changed": True}) command.reset_mock() with self.assertRaisesRegex(ValueError, "fixtures changed"): From 7895aca17e09153a00debd4e5ae5672431254ad1 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sun, 29 Nov 2026 01:41:37 +1100 Subject: [PATCH 10/22] Collect streaming client evidence in fixed release sizing pilot --- .gi/templates.yaml | 22 +++- ci/README.md | 41 ++++++ ci/automation.just | 1 + ci/inference-client-pilot.json | 35 +++++ scripts/inference-paired.py | 34 ++++- scripts/lib/inference_client.py | 182 ++++++++++++++++++++++++++ scripts/lib/inference_client_pilot.py | 42 ++++++ scripts/tests/inference_client.py | 148 +++++++++++++++++++++ 8 files changed, 499 insertions(+), 6 deletions(-) create mode 100644 ci/inference-client-pilot.json create mode 100644 scripts/lib/inference_client.py create mode 100644 scripts/lib/inference_client_pilot.py create mode 100644 scripts/tests/inference_client.py diff --git a/.gi/templates.yaml b/.gi/templates.yaml index d4b2ed3f..5593ac83 100644 --- a/.gi/templates.yaml +++ b/.gi/templates.yaml @@ -647,6 +647,22 @@ "kind": "text", "required": true, "default": "legacy" + }, + { + "key": "experiment", + "label": "Measurement protocol", + "kind": "choice", + "choices": [ + { + "value": "paired", + "label": "paired" + }, + { + "value": "client-pilot", + "label": "client-pilot" + } + ], + "default": "paired" } ], "budget": { @@ -656,7 +672,7 @@ }, "retain": "never", "key": "inference-pr-standalone", - "command": "cd \"$JIANYANG_REPO_DIR\" && just inference-paired ${model_key} standalone ${baseline_sha}", + "command": "cd \"$JIANYANG_REPO_DIR\" && just inference-paired ${model_key} standalone ${baseline_sha} ${experiment}", "env": { "HF_HOME": "/mnt/model-store/huggingface", "HF_HUB_CACHE": "/mnt/model-store/huggingface/hub" @@ -926,6 +942,10 @@ { "value": "noise-profile", "label": "noise-profile" + }, + { + "value": "client-pilot", + "label": "client-pilot" } ], "default": "paired" diff --git a/ci/README.md b/ci/README.md index 96546868..40112cd5 100644 --- a/ci/README.md +++ b/ci/README.md @@ -296,6 +296,47 @@ original verdicts. The current v1 verdict implementation still needs an explicit within-tolerance decision and sufficient live precision before performance resolution can be claimed. +The separate `client-pilot` experiment is registered in +`ci/inference-client-pilot.json` for Coder split and Qwen3.5-4B standalone. +It runs eight independent main/main pairs on one exclusive allocation with +fresh server processes and balanced nominal arm order. This is a sizing pilot, +not the final performance comparison. It records all arm durations and paired +log-ratio vectors; it cannot issue an equivalence or candidate verdict. + +Each arm uses the pinned `scripts/inferencekit.sh bench serve` streaming client +for three cycled shapes, three repetitions per shape, two unique 64-token +warmups before each measured 128-token request, concurrency one. Both arms use +the same release/static build policy. Phase tracing and diagnostic samplers +are off during client timing; native logging remains enabled for offload proof. +The first two pairs check instrumentation; all eight are required for sizing. +Changing the recipe, client or workload requires a new sizing pilot. + +Primary endpoints are per-shape median client TTFT, median client TPOT, and +output tokens divided by the sum of measured request E2E seconds. The latter +excludes warmups and other shapes; it measures concurrency-one service windows, +not loaded capacity. The client process persists within each arm but opens a +new HTTP socket for each request, so TTFT and E2E include connection time. +TPOT uses `(last content event - first content event)/(output tokens - 1)`; +without streamed token IDs the first content event is assumed to hold one token. +It is not an exact inter-token latency measure. Server phases remain separate +diagnostics. Neither three requests per shape nor this pilot supports a p95 gate. + +The adapter independently checks immutable input/output indexes, artifact hashes, +content-event timelines, terminal usage, full length termination, zero cached +tokens and constant input token counts. SSE event counts never count output +tokens. Warmups are retained but excluded from paired summaries. Tool-level +one-round summaries and their absent intervals are not final comparison evidence. +Every role retains its per-arm archive and existing native quality, admission, +offload and mutual completion proofs. For an admitted allocation: + +```sh +just inference-paired qwen3-coder-30b-a3b split cc2a27435e798649a9cb938d600d39722e4a2263 client-pilot +``` + +Final acquisition remains unregistered until pilot variance, covariance and arm +durations establish a feasible fixed count under the four-hour lease. The 2% +material effect and 1% maximum pointwise interval half-width remain unchanged. + Scheduled PR-profile smoke rows run the same design with main in both arms; their paired receipts retain the noise check in Actions artifacts. The twelve AgentX workloads and their saved historical baseline policy are separate. diff --git a/ci/automation.just b/ci/automation.just index 35be4d34..b35cb514 100644 --- a/ci/automation.just +++ b/ci/automation.just @@ -18,6 +18,7 @@ inference-contracts: @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_contracts.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_probe.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_noise.py + @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_pairs.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_paired_execution.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/jy_read_recovery.py diff --git a/ci/inference-client-pilot.json b/ci/inference-client-pilot.json new file mode 100644 index 00000000..6d7c4f4f --- /dev/null +++ b/ci/inference-client-pilot.json @@ -0,0 +1,35 @@ +{ + "protocol": "DGX Spark release client sizing pilot v1", + "purpose": "Fixed independent A/A sizing pilot; no final candidate or equivalence verdict", + "baseline_sha": "cc2a27435e798649a9cb938d600d39722e4a2263", + "configurations": ["qwen3-coder-30b-a3b-split", "qwen35-4b-standalone"], + "pairs": 8, + "order": "a,b in even pairs; b,a in odd pairs; both nominal arms use pinned main", + "fresh_server_per_arm": true, + "exclusive_same_allocation": true, + "workload": "DGX Spark client warm uncached v1", + "paragraphs": [8, 32, 64], + "repetitions_per_shape": 3, + "shape_order": "cycled", + "warmups_per_measurement": 2, + "warmup_tokens": 64, + "measured_tokens": 128, + "concurrency": 1, + "temperature": 0, + "seed": 42, + "primary_endpoints": ["median client TTFT ms", "median client TPOT ms", "measured request output tok/s"], + "diagnostic_endpoints": ["client E2E ms", "separate release shape-order server-phase diagnostic"], + "client": "Pinned inferencekit-cli 0.1.1 bench serve; one process per arm, new socket per request", + "tpot_definition": "(last content event - first content event)/(usage completion tokens - 1); first content event assumed one token; event count never counts tokens", + "throughput_definition": "Sum measured output tokens / sum measured client E2E seconds per shape; excludes warmups and other shapes; concurrency-one service windows, not capacity", + "gates": ["full output and length termination", "terminal usage token counts", "zero cached tokens", "constant prompt tokens per shape", "complete hashed raw client records", "quality and streaming", "release build identity and GPU offload", "both split role archives and mutual peer proof"], + "instrumentation": "Standard native logging for offload proof; phase tracing and diagnostic samplers off during client timing", + "analysis": "Aggregate nested requests within each fresh arm; retain all eight independent paired log-ratio vectors, arm durations and order. First two pairs are instrumentation checks, not evidence the noise disappeared. If build/client/workload changes, restart this pilot.", + "final_design": { + "material_effect": 0.02, + "maximum_pointwise_ci95_ratio_half_width": 0.01, + "round_count": "NOT REGISTERED: size from this separate pilot, freeze analysis/count/budget before fresh final A/A and A/B; never extend after inspecting final outcomes", + "scope": "Warm uncached concurrency-one source-built release/static CUDA; no shipped dynamic package or loaded capacity claim" + }, + "budget": {"max_usd": 0, "max_duration_s": 14400, "no_preemption": true} +} diff --git a/scripts/inference-paired.py b/scripts/inference-paired.py index 350b7fa7..296dd72a 100644 --- a/scripts/inference-paired.py +++ b/scripts/inference-paired.py @@ -11,6 +11,7 @@ import sys import tarfile import tempfile +import time from contextlib import contextmanager, nullcontext from pathlib import Path from runpy import run_path @@ -21,6 +22,8 @@ from lib.inference_probe import validate_evidence from lib.inference_rendezvous import Coordinator, await_condition, exchange, worker_state from lib import inference_noise as noise +from lib import inference_client as client +from lib import inference_client_pilot as client_pilot ROOT = Path(__file__).resolve().parents[1] EXECUTE = run_path(str(ROOT / "scripts/inference-execute.py"))["execute"] @@ -110,6 +113,8 @@ def run_arm(design, main, baseline, key, mode, output): with noise.diagnostics(directory, kind): EXECUTE("pr", key, mode, probe=noise.probe(design["round"], kind), phase_profile=kind == "profile") + elif design["experiment"] == "client": + EXECUTE("pr", key, mode, probe=client.measure) else: EXECUTE("pr", key, mode, REPETITIONS) finally: @@ -141,6 +146,9 @@ def ready(): def execute(key, mode, baseline, experiment="paired"): + sizing = experiment == "client-pilot" + if sizing: + client_pilot.schedule(baseline, f"{key}-{mode}") diagnostic = experiment in {"noise-pilot", "noise-profile"} kind = experiment.removeprefix("noise-") if diagnostic else None if diagnostic and (f"{key}-{mode}" != noise.registration(kind)["configuration"] or baseline == "legacy"): @@ -155,13 +163,19 @@ def execute(key, mode, baseline, experiment="paired"): raise ValueError("paired comparison candidate differs from JY admission") output = Path(os.environ["JIANYANG_ARTIFACT_DIR"]).resolve() output.mkdir(parents=True, exist_ok=True) + if sizing: + doctor = command([str(ROOT / "scripts/inferencekit.sh"), "doctor", "--json"], + timeout=180, capture_stdout=True, + overrides={"INFERENCEKIT_RUNS_DIR": str(output / "doctor-records")}) + (output / "doctor.json").write_text(doctor) peers = json.loads(os.environ["JIANYANG_PEERS"]) if mode == "split" else [] role = os.environ.get("JIANYANG_ROLE", "leader") node = next((p["node"] for p in peers if p["role"] == role), platform.node()) with baseline_tree(baseline) as main: identities = prepare(main, baseline, candidate, output) local = host(role, node) - designs = noise.schedule(baseline, kind) if diagnostic else schedule(baseline, candidate) + designs = (client_pilot.schedule(baseline, f"{key}-{mode}") if sizing else + noise.schedule(baseline, kind) if diagnostic else schedule(baseline, candidate)) if role == "worker": leader = next(p["host"] for p in peers if p["role"] == "leader") origin = f"http://[{leader}]:9913" if ":" in leader else f"http://{leader}:9913" @@ -184,17 +198,24 @@ def execute(key, mode, baseline, experiment="paired"): evidence.update(protocol=registered["protocol"], rounds=len(registered["arms"]), repetitions=registered["repetitions_per_condition_shape"], diagnostic_only=True, registration=registered) + if sizing: + registered = client_pilot.registration() + evidence.update(protocol=registered["protocol"], rounds=registered["pairs"], + sizing_only=True, registration=registered) try: for index, design in enumerate(designs): if coordinator: coordinator.state["index"] = index + started = time.monotonic() directory = run_arm(design, main, baseline, key, mode, output) if coordinator: coordinator.wait(lambda s: s["done"] == index) coordinate = read_json(ROOT / "ci/inference-artifacts.json")[key] coordinate = f'{coordinate["repo"]}@{coordinate["revision"]}' evidence["runs"].append({**design, "placements": placements, "quality": "passed", - "samples": (read_json(directory / f"noise-{kind}.json") if diagnostic + "arm_duration_s": time.monotonic() - started, + "samples": (client.verify(directory, coordinate) if sizing else + read_json(directory / f"noise-{kind}.json") if diagnostic else samples(directory, coordinate))}) # Preserve the existing standalone nightly smoke receipts too. if design["experiment"] == "ab" and design["arm"] == "b": @@ -202,12 +223,15 @@ def execute(key, mode, baseline, experiment="paired"): "provenance.json", "split-admissions.json", "split-peer.json"): if (directory / name).is_file(): shutil.copyfile(directory / name, output / name) - if not diagnostic: + if sizing: + evidence["summary"] = client_pilot.summarize(evidence) + elif not diagnostic: evidence["summary"] = summarize(evidence, candidate, baseline, f"{key}-{mode}") else: evidence["status"] = "diagnostic-complete" finally: - write_json(output / (f"noise-{kind}.json" if diagnostic else "paired-probe.json"), evidence) + write_json(output / ("client-pilot.json" if sizing else + f"noise-{kind}.json" if diagnostic else "paired-probe.json"), evidence) if __name__ == "__main__": @@ -215,7 +239,7 @@ def execute(key, mode, baseline, experiment="paired"): parser.add_argument("model") parser.add_argument("mode", choices=("standalone", "split")) parser.add_argument("baseline") - parser.add_argument("experiment", nargs="?", choices=("paired", "noise-pilot", "noise-profile"), default="paired") + parser.add_argument("experiment", nargs="?", choices=("paired", "noise-pilot", "noise-profile", "client-pilot"), default="paired") args = parser.parse_args() try: with cancel_on_signal(), time_budget(14400): diff --git a/scripts/lib/inference_client.py b/scripts/lib/inference_client.py new file mode 100644 index 00000000..f38bebff --- /dev/null +++ b/scripts/lib/inference_client.py @@ -0,0 +1,182 @@ +"""Pinned streaming-client acquisition and independent raw-record validation. + +InferenceKit's one-round intervals are not qualification intervals. Independent +fresh server pairs are the units for the enclosing registered experiment. +""" + +import json +import math +import os +from pathlib import Path +from statistics import median + +from .ci_artifacts import digest, read_json, write_json +from .ci_process import command +from .inference_checks import ENDPOINT +from .inference_probe import PARAGRAPHS, payload + +ROOT = Path(__file__).resolve().parents[2] +LABEL = "qualification" +WORKLOAD = "DGX Spark client warm uncached v1" +REPETITIONS = 3 + + +def prompts(model): + result = [] + for repetition in range(REPETITIONS): + for shape in range(len(PARAGRAPHS)): + for phase in ("warm0", "warm1", "measured"): + warm = phase != "measured" + body = payload(model, shape, warm) + text = body["messages"][0]["content"].split("\n", 1)[1] + salt = len(result) + body["messages"][0]["content"] = f'{"W" if warm else "M"}{salt:03d}\n{text}' + result.append({"id": f"r{repetition}-s{shape}-{phase}", + "bucket": f'{"warm" if warm else "shape"}-{shape}', + "messages": body["messages"], "max_tokens": body["max_tokens"], + "chat_template_kwargs": body["chat_template_kwargs"]}) + return result + + +def expected_body(model, prompt): + return {"model": model, "messages": prompt["messages"], "max_tokens": prompt["max_tokens"], + "chat_template_kwargs": prompt["chat_template_kwargs"], "temperature": 0, + "seed": 42, "ignore_eos": True, "stream": True, + "stream_options": {"include_usage": True}} + + +def positive(value): + return type(value) in (int, float) and math.isfinite(value) and value > 0 + + +def validate_request(row, response, request, model, prompt): + count = prompt["max_tokens"] + if request != expected_body(model, prompt): + raise ValueError("client request differs from registered workload") + if (row["id"] != prompt["id"] or row["bucket"] != prompt["bucket"] or row["round"] != 0 + or row["salt"] is not None or row["ok"] is not True or row["status"] != 200 + or row["error"] is not None or row["count_mismatch"] is not None + or row["n_tokens"] != count or row["n_usage"] != count + or row["token_count_method"] != "usage"): + raise ValueError("client requires successful full output counted by terminal usage") + if any(type(row[k]) is not int for k in ("round", "n_tokens", "n_usage", "n_token_events", + "t_send_ns", "t_end_ns")): + raise ValueError("invalid client token counts or clock values") + usage = response["usage"] + if (response["id"] != row["id"] or response["bucket"] != row["bucket"] + or response["round"] != 0 or response["salt"] is not None + or response["error"] is not None or response["n_tokens"] != count + or response["max_tokens"] != count or response["token_count_method"] != "usage" + or response["finish_reason"] != "length" or row["finish_reason"] != "length" + or not isinstance(response["text"], str) or not response["text"].strip() + or response.get("reasoning") or response["token_ids"] is not None + or type(usage["completion_tokens"]) is not int or usage["completion_tokens"] != count + or type(usage["prompt_tokens"]) is not int or usage["prompt_tokens"] <= 0 + or type(usage["prompt_tokens_details"]["cached_tokens"]) is not int + or usage["prompt_tokens_details"]["cached_tokens"] != 0): + raise ValueError("client requires uncached prompts, complete text and length termination") + timing = response["timings"] + events = timing["event_ms"] + ids = timing["event_token_ids"] + if (not events or len(events) != row["n_token_events"] or len(ids) != len(events) + or any(i is not None for i in ids) or not all(positive(t) for t in events) + or events != sorted(events) or events[-1] <= events[0] + or not positive(row["t_send_ns"]) or timing["t_send_ns"] != row["t_send_ns"] + or not positive(row["t_end_ns"] - row["t_send_ns"]) + or not all(positive(row[k]) for k in ("ttft_ms", "tpot_ms", "e2e_ms"))): + raise ValueError("invalid client event timeline") + # InferenceKit timestamps content-bearing events, not role/usage chunks. + # Without streamed IDs its TPOT assumes the first content event has one + # token. Coalesced events are allowed, and event count never counts tokens. + reconstructed = {"ttft_ms": events[0], "tpot_ms": (events[-1] - events[0]) / (count - 1)} + if (any(abs(row[k] - v) > 0.0002 for k, v in reconstructed.items()) + or events[-1] > row["e2e_ms"] + 0.0002 + or row["e2e_ms"] > (row["t_end_ns"] - row["t_send_ns"]) / 1e6 + 0.0002): + raise ValueError("client timings disagree with raw event timeline") + return usage["prompt_tokens"] + + +def verify(output, model): + records = list((output / "inferencekit").glob("ev_*/evidence.json")) + if len(records) != 1: + raise ValueError("client requires exactly one immutable InferenceKit record") + record = read_json(records[0]) + if (record["kind"] != "serve_benchmark" or record["provenance"]["tool_version"] != "0.1.1" + or record["data"]["extends"] is not None): + raise ValueError("client tool identity or acquisition differs") + root = records[0].parent + if {a["role"] for a in record["artifacts"]} != {"requests", "outputs_index"}: + raise ValueError("client requires request rows and hashed input/output index") + for artifact in record["artifacts"]: + path = root / artifact["path"] + if not path.resolve().is_relative_to(root.resolve()) or digest(path) != artifact["sha256"]: + raise ValueError("client artifact checksum mismatch") + index = read_json(root / "outputs" / LABEL / "index.json") + design = prompts(model) + expected = {f'{p["bucket"]}/{p["id"]}.json' for p in design} + if set(index["files"]) != expected or set(index["inputs"]) != expected: + raise ValueError("client input/output roster incomplete") + rows = [json.loads(line) for line in (root / "requests.jsonl").read_text().splitlines()] + if len(rows) != len(design): + raise ValueError("client request roster incomplete") + counts, samples = {}, [] + previous_end = 0 + for prompt, row in zip(design, rows): + relative = f'{prompt["bucket"]}/{prompt["id"]}.json' + documents = [] + for kind, key in (("inputs", "inputs"), ("outputs", "files")): + path = root / kind / LABEL / relative + if digest(path) != index[key][relative]: + raise ValueError("client input/output checksum mismatch") + documents.append(read_json(path)) + request, response = documents + shape = int(prompt["bucket"].split("-")[1]) + count = validate_request(row, response, request, model, prompt) + if count != counts.setdefault(shape, count) or row["t_send_ns"] < previous_end: + raise ValueError("client prompt shape changed or requests overlap") + previous_end = row["t_end_ns"] + if prompt["bucket"].startswith("shape-"): + samples.append({"shape": shape, "id": row["id"], "ttft_ms": row["ttft_ms"], + "tpot_ms": row["tpot_ms"], "e2e_ms": row["e2e_ms"], "tokens": row["n_tokens"]}) + summaries = [] + for shape in range(len(PARAGRAPHS)): + selected = [s for s in samples if s["shape"] == shape] + summaries.append({"shape": shape, "ttft_ms": median(s["ttft_ms"] for s in selected), + "tpot_ms": median(s["tpot_ms"] for s in selected), + "request_tok_s": sum(s["tokens"] for s in selected) * 1000 / + sum(s["e2e_ms"] for s in selected)}) + return {"workload": WORKLOAD, "evidence_id": record["evidence_id"], "status": "passed", + "samples": samples, "summaries": summaries, + "limitations": ["One client process; each HTTP request opens a new socket; connection included", + "TPOT normalizes first content event as one token; not exact inter-token latency", + "Request throughput excludes warmups and other shapes; not loaded capacity", + "Server phase timings are separate diagnostics"], + "tool_limitations": record["limitations"]} + + +def measure(model, output): + design = prompts(model) + prompt_file = output / "client-prompts.jsonl" + prompt_file.write_text("".join(json.dumps(p) + "\n" for p in design)) + evidence = {"workload": WORKLOAD, "status": "incomplete"} + try: + stdout = command([str(ROOT / "scripts/inferencekit.sh"), "bench", "serve", + "--base-url", ENDPOINT, "--model", model, "--prompts", str(prompt_file), + "--api", "chat", "--engine-kind", "generic", "--mode", "single", + "--rounds", "1", "--warmup", "0", "--token-ids", "off", + "--extra-body", json.dumps({"temperature": 0, "seed": 42, "ignore_eos": True}), + "--timeout-s", "180", "--label", LABEL, "--run-dir", str(output / "client"), + "--gpu-name", "NVIDIA GB10", "--gpu-count", + "2" if os.environ.get("JIANYANG_PEERS") else "1", + "--engine-version", os.environ.get("JIANYANG_COMMIT", "offline-fixture"), + "--json"], + timeout=5400, capture_stdout=True, + overrides={"INFERENCEKIT_RUNS_DIR": str(output / "inferencekit")}) + (output / "client-tool.json").write_text(stdout) + evidence = verify(output, model) + evidence["prompts_sha256"] = digest(prompt_file) + except BaseException as error: + evidence.update(status="failed", error=str(error)) + raise + finally: + write_json(output / "client-probe.json", evidence) diff --git a/scripts/lib/inference_client_pilot.py b/scripts/lib/inference_client_pilot.py new file mode 100644 index 00000000..29445b83 --- /dev/null +++ b/scripts/lib/inference_client_pilot.py @@ -0,0 +1,42 @@ +"""Independent main/main release-client sizing; deliberately no final verdict.""" + +import math +from statistics import fmean, stdev + +from .ci_artifacts import read_json +from .inference_client import ROOT + +REGISTRATION = ROOT / "ci/inference-client-pilot.json" + + +def registration(): + return read_json(REGISTRATION) + + +def schedule(baseline, configuration): + design = registration() + if baseline != design["baseline_sha"] or configuration not in design["configurations"]: + raise ValueError("client pilot requires registered baseline and configuration") + return [{"experiment": "client", "round": pair, "arm": arm, "source_sha": baseline} + for pair in range(design["pairs"]) + for arm in (("a", "b") if pair % 2 == 0 else ("b", "a"))] + + +def summarize(evidence): + designs = schedule(evidence["baseline_sha"], evidence["configuration"]) + if (evidence["registration"] != registration() or len(evidence["runs"]) != len(designs) + or any(any(run.get(k) != v for k, v in design.items()) + or run["placements"] != evidence["placements"] or run["quality"] != "passed" + or run["samples"]["status"] != "passed" + for run, design in zip(evidence["runs"], designs))): + raise ValueError("client pilot incomplete, reordered or changed allocation") + values = {(r["round"], r["arm"]): r["samples"]["summaries"] for r in evidence["runs"]} + results = [] + for shape in range(3): + for metric in ("ttft_ms", "tpot_ms", "request_tok_s"): + logs = [math.log(values[pair, "b"][shape][metric] / values[pair, "a"][shape][metric]) + for pair in range(registration()["pairs"])] + results.append({"shape": shape, "metric": metric, "paired_log_ratios": logs, + "log_ratio_mean": fmean(logs), "log_ratio_sd": stdev(logs)}) + return {"status": "sizing-only", "independent_pairs": registration()["pairs"], + "endpoints": results, "final_round_count": None, "performance_verdict": "NOT RUN"} diff --git a/scripts/tests/inference_client.py b/scripts/tests/inference_client.py new file mode 100644 index 00000000..5e5915a3 --- /dev/null +++ b/scripts/tests/inference_client.py @@ -0,0 +1,148 @@ +"""Offline streaming evidence guards; no model or hardware qualification.""" + +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 inference_client as client +from lib import inference_client_pilot as pilot +from lib.ci_artifacts import digest, write_json + +MODEL = "fixture@" + "a" * 40 + + +def response(prompt, position=0): + n = prompt["max_tokens"] + start = 1_000_000_000 + position * 300_000_000 + # Deliberately only two content events for 64/128 generated tokens. + row = {"id": prompt["id"], "bucket": prompt["bucket"], "round": 0, "salt": None, + "ok": True, "status": 200, "error": None, "count_mismatch": None, + "n_tokens": n, "n_usage": n, "token_count_method": "usage", "finish_reason": "length", + "n_token_events": 2, "t_send_ns": start, "t_end_ns": start + 210_000_000, + "ttft_ms": 10, "tpot_ms": 190 / (n - 1), "e2e_ms": 205} + doc = {"id": row["id"], "bucket": row["bucket"], "round": 0, "salt": None, + "error": None, "max_tokens": n, "n_tokens": n, "token_count_method": "usage", + "finish_reason": "length", "text": "coalesced output", "token_ids": None, + "usage": {"completion_tokens": n, "prompt_tokens": 200 + int(prompt["bucket"][-1]), + "prompt_tokens_details": {"cached_tokens": 0}}, + "timings": {"t_send_ns": start, "event_ms": [10, 200], "event_token_ids": [None, None]}} + return row, doc + + +def fixture(output): + root = output / "inferencekit/ev_fixture" + index = {"label": client.LABEL, "files": {}, "inputs": {}} + rows = [] + for position, prompt in enumerate(client.prompts(MODEL)): + row, doc = response(prompt, position) + rows.append(row) + relative = f'{prompt["bucket"]}/{prompt["id"]}.json' + for kind, key, value in (("inputs", "inputs", client.expected_body(MODEL, prompt)), + ("outputs", "files", doc)): + path = root / kind / client.LABEL / relative + path.parent.mkdir(parents=True, exist_ok=True) + write_json(path, value) + index[key][relative] = digest(path) + write_json(root / "outputs" / client.LABEL / "index.json", index) + (root / "requests.jsonl").write_text("".join(json.dumps(r) + "\n" for r in rows)) + paths = [("requests", root / "requests.jsonl"), + ("outputs_index", root / "outputs" / client.LABEL / "index.json")] + write_json(root / "evidence.json", {"evidence_id": "ev_fixture", "kind": "serve_benchmark", + "provenance": {"tool_version": "0.1.1"}, "data": {"extends": None}, "limitations": [], + "artifacts": [{"role": role, "path": str(path.relative_to(root)), "sha256": digest(path)} + for role, path in paths]}) + return root + + +class ClientTests(unittest.TestCase): + def test_workload_cycles_shapes_and_has_two_unique_warmups_before_each_measurement(self): + prompts = client.prompts(MODEL) + self.assertEqual(len(prompts), 27) + self.assertEqual([p["max_tokens"] for p in prompts], [64, 64, 128] * 9) + prefixes = [p["messages"][0]["content"].splitlines()[0] for p in prompts] + self.assertEqual(len(set(prefixes)), 27) + self.assertEqual({len(p) for p in prefixes}, {4}) + self.assertEqual([p["bucket"] for p in prompts[2::3]], ["shape-0", "shape-1", "shape-2"] * 3) + + def test_reconstructs_timing_from_coalesced_content_and_usage_not_event_counts(self): + p = client.prompts(MODEL)[2] + row, doc = response(p) + self.assertEqual(client.validate_request(row, doc, client.expected_body(MODEL, p), MODEL, p), 200) + self.assertEqual(row["n_token_events"], 2) + self.assertEqual(row["n_tokens"], 128) + + def test_rejects_missing_completion_cache_hits_count_fallback_and_bad_timing(self): + p = client.prompts(MODEL)[2] + changes = [lambda r, d: d.update(finish_reason=None), + lambda r, d: d["usage"].update(completion_tokens=127), + lambda r, d: d["usage"]["prompt_tokens_details"].update(cached_tokens=1), + lambda r, d: r.update(token_count_method="sse_events"), + lambda r, d: r.update(ok=False, error="stream ended early"), + lambda r, d: d["timings"].update(event_ms=[200, 10]), + lambda r, d: r.update(tpot_ms=99), + lambda r, d: r.update(e2e_ms=100)] + for change in changes: + with self.subTest(change=change): + row, doc = response(p) + change(row, doc) + with self.assertRaises(ValueError): + client.validate_request(row, doc, client.expected_body(MODEL, p), MODEL, p) + + def test_raw_verification_excludes_warmups_and_requires_complete_hashes(self): + with TemporaryDirectory() as temporary: + output = Path(temporary) + root = fixture(output) + result = client.verify(output, MODEL) + self.assertEqual(len(result["samples"]), 9) + self.assertAlmostEqual(result["summaries"][0]["request_tok_s"], 128000 / 205) + path = root / "outputs/qualification/shape-0/r0-s0-measured.json" + path.write_text("{}") + with self.assertRaisesRegex(ValueError, "checksum"): + client.verify(output, MODEL) + + def test_failures_retain_status_and_partial_tool_files(self): + with TemporaryDirectory() as temporary, patch.object(client, "command", side_effect=RuntimeError("partial")): + output = Path(temporary) + with self.assertRaisesRegex(RuntimeError, "partial"): + client.measure(MODEL, output) + self.assertTrue((output / "client-prompts.jsonl").is_file()) + self.assertEqual(json.loads((output / "client-probe.json").read_text())["status"], "failed") + + def test_sizing_has_eight_independent_balanced_main_pairs_and_never_a_final_verdict(self): + registration = pilot.registration() + config = registration["configurations"][0] + designs = pilot.schedule(registration["baseline_sha"], config) + self.assertEqual(len(designs), 16) + self.assertEqual([d["arm"] for d in designs[:4]], ["a", "b", "b", "a"]) + evidence = {"baseline_sha": registration["baseline_sha"], "configuration": config, + "registration": registration, "placements": [{"node": "fixture"}], "runs": []} + for design in designs: + evidence["runs"].append({**design, "placements": evidence["placements"], "quality": "passed", + "samples": {"status": "passed", "summaries": [ + {"ttft_ms": 100, "tpot_ms": 10, "request_tok_s": 50}] * 3}}) + result = pilot.summarize(evidence) + self.assertEqual(result["performance_verdict"], "NOT RUN") + self.assertEqual(result["independent_pairs"], 8) + self.assertEqual(len(result["endpoints"]), 9) + evidence["runs"].pop() + with self.assertRaisesRegex(ValueError, "incomplete"): + pilot.summarize(evidence) + + def test_sizing_arm_retains_native_gates_and_archive(self): + run = run_path(str(client.ROOT / "scripts/inference-paired.py"))["run_arm"] + design = pilot.schedule(pilot.registration()["baseline_sha"], "qwen3-coder-30b-a3b-split")[0] + with TemporaryDirectory() as temporary: + output = Path(temporary) + with patch.dict(run.__globals__, EXECUTE=lambda *args, **kwargs: self.assertIs(kwargs["probe"], client.measure)): + run(design, output, design["source_sha"], "fixture", "split", output) + self.assertTrue((output / "client-0-a-evidence.tar.gz").is_file()) + execute = run_path(str(client.ROOT / "scripts/inference-paired.py"))["execute"] + with self.assertRaisesRegex(ValueError, "registered baseline"): + execute("qwen35-4b", "standalone", "legacy", "client-pilot") + + +if __name__ == "__main__": + unittest.main() From 49a7d69c3a6323ede20f0d3e97ad4563922383c5 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sun, 29 Nov 2026 02:24:11 +1100 Subject: [PATCH 11/22] Gate client qualification on registered precision and power --- .gi/templates.yaml | 12 ++ ci/README.md | 52 ++++++++ ci/automation.just | 7 ++ ci/inference-client-final.json | 69 +++++++++++ ci/inference-client-noise.json | 13 ++ scripts/inference-client-plan.py | 30 +++++ scripts/inference-paired.py | 45 +++++-- scripts/lib/inference_client_decision.py | 70 +++++++++++ scripts/lib/inference_client_final.py | 137 +++++++++++++++++++++ scripts/lib/inference_client_noise.py | 134 ++++++++++++++++++++ scripts/lib/inference_client_power.py | 112 +++++++++++++++++ scripts/lib/inference_client_report.py | 42 +++++++ scripts/tests/inference_client_decision.py | 132 ++++++++++++++++++++ scripts/tests/inference_client_noise.py | 72 +++++++++++ scripts/tests/inference_client_power.py | 57 +++++++++ 15 files changed, 977 insertions(+), 7 deletions(-) create mode 100644 ci/inference-client-final.json create mode 100644 ci/inference-client-noise.json create mode 100644 scripts/inference-client-plan.py create mode 100644 scripts/lib/inference_client_decision.py create mode 100644 scripts/lib/inference_client_final.py create mode 100644 scripts/lib/inference_client_noise.py create mode 100644 scripts/lib/inference_client_power.py create mode 100644 scripts/lib/inference_client_report.py create mode 100644 scripts/tests/inference_client_decision.py create mode 100644 scripts/tests/inference_client_noise.py create mode 100644 scripts/tests/inference_client_power.py diff --git a/.gi/templates.yaml b/.gi/templates.yaml index 5593ac83..9a3e0c31 100644 --- a/.gi/templates.yaml +++ b/.gi/templates.yaml @@ -660,6 +660,14 @@ { "value": "client-pilot", "label": "client-pilot" + }, + { + "value": "client-final", + "label": "client-final" + }, + { + "value": "client-noise", + "label": "client-noise" } ], "default": "paired" @@ -946,6 +954,10 @@ { "value": "client-pilot", "label": "client-pilot" + }, + { + "value": "client-final", + "label": "client-final" } ], "default": "paired" diff --git a/ci/README.md b/ci/README.md index 40112cd5..f70e778d 100644 --- a/ci/README.md +++ b/ci/README.md @@ -337,6 +337,58 @@ Final acquisition remains unregistered until pilot variance, covariance and arm durations establish a feasible fixed count under the four-hour lease. The 2% material effect and 1% maximum pointwise interval half-width remain unchanged. +The opt-in `client-final` implementation has its own registration in +`ci/inference-client-final.json`. It currently refuses acquisition: both counts +and power plans are unset. A final registration must embed a feasible power plan +with a fixed even count of at least sixteen pairs per phase and at least 90% +modeled joint power for parity and a 0.5% candidate loss, including every declared +variance sensitivity. A plan exceeding the four-hour lease is rejected before +starting server arms. Sizing data never contribute pairs to final qualification. + +The prospective planner runs through +`just inference-client-plan `. +It uses conservative marginal failure bounds rather than fitting a covariance +matrix to eight pairs. Under independent Gaussian pilot log ratios, an upper +standard deviation of three times the observed value has a nine-endpoint union +miss bound of approximately 2.10% (the df=7 chi-square relation; see the +[NIST standard-deviation interval derivation](https://www.itl.nist.gov/div898/handbook/prc/section2/prc231.htm)). +The planning model includes that uncertainty, A/B standard deviations of 1, 1.5 +and 2 times the upper A/A estimate, and a conservative CI-width proxy of +`2.5*SD/sqrt(pairs)`. A/A remains centered at parity in both candidate scenarios. +The union bound allows arbitrary dependence among endpoints and between A/A +and A/B. It still assumes independent paired rounds and the stated normal model; +it does not prove power under heavy tails or serial drift. The planner retains +all pilot vectors, assumptions, scenario powers and duration allowances. + +Final time blocks contain one A/A pair and one A/B pair, with balanced phase +positions randomized from the recorded seed and alternating nominal arm order. +Pointwise paired percentile intervals use 100,000 resamples of fresh paired +server blocks, never nested requests. Each endpoint's complete A/A interval must +lie inside `[0.99, 1.01]`. Its A/B ratio-scale half-width must be at most 1%. +An A/B interval inside `[0.98, 1.02]` earns `within_tolerance`; otherwise the +native metric direction determines non-regression or a material change beyond +2%. Every client endpoint must pass. Invalid calibration or unresolved margins +cannot pass; a calibrated clear regression fails even if its interval is wide. +Matching content-event framing and constant prompt token shapes are required. + +After the measured client window, each final arm collects three separate +non-streaming server-phase probe repetitions. All phase ratios and intervals, +including losses, are retained as diagnostics outside the client verdict. A +client pass does not establish server-phase non-regression. Historical v1 +inconclusive phase results remain unchanged. The default `paired` rollout and +protected legacy CI remain separate until the new registered protocol is +validated and explicitly activated. + +`client-noise` is a separate, bounded standalone diagnostic registered in +`ci/inference-client-noise.json`. Two fresh pinned-main arms send the original +client-pilot request bodies through a diagnostic curl stream capture. Complete +SSE, including native terminal phase timings, is retained alongside monotonic +request boundaries and one-second GPU/CPU frequency, thread-placement and +cgroup quota/throttling counters. This acquisition is not the pinned client's +final timing path and cannot qualify performance or contribute final pairs. +Its purpose is to distinguish native generation variability from delivery +variability before selecting a change; correlations alone do not prove a cause. + Scheduled PR-profile smoke rows run the same design with main in both arms; their paired receipts retain the noise check in Actions artifacts. The twelve AgentX workloads and their saved historical baseline policy are separate. diff --git a/ci/automation.just b/ci/automation.just index b35cb514..08e0b1bd 100644 --- a/ci/automation.just +++ b/ci/automation.just @@ -19,12 +19,19 @@ inference-contracts: @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_probe.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_noise.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client.py + @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client_decision.py + @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client_power.py + @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client_noise.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_pairs.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_paired_execution.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/jy_read_recovery.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_markdown.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_nightly.py +[positional-arguments] +inference-client-plan pilot output: + @"{{ automation_python }}" scripts/inference-client-plan.py "$@" + inference-publication-test: @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_publication.py diff --git a/ci/inference-client-final.json b/ci/inference-client-final.json new file mode 100644 index 00000000..fa22c087 --- /dev/null +++ b/ci/inference-client-final.json @@ -0,0 +1,69 @@ +{ + "protocol": "DGX Spark release client paired qualification v1", + "status": "awaiting sizing pilots; final acquisition prohibited", + "baseline_sha": "cc2a27435e798649a9cb938d600d39722e4a2263", + "configurations": { + "qwen3-coder-30b-a3b-split": { + "pairs_per_phase": null, + "planning_evidence": null + }, + "qwen35-4b-standalone": { + "pairs_per_phase": null, + "planning_evidence": null + } + }, + "scope": "Warm uncached concurrency-one client performance, source-built release/static CUDA; server phases diagnostic", + "client_workload": "DGX Spark client warm uncached v1", + "primary_metrics": { + "ttft_ms": "lower", + "tpot_ms": "lower", + "request_tok_s": "higher" + }, + "shapes": [ + 0, + 1, + 2 + ], + "material_effect": 0.02, + "maximum_pointwise_ci95_ratio_half_width": 0.01, + "placebo_ci95_band": [ + 0.99, + 1.01 + ], + "estimator": "Geometric mean of within-pair candidate/main arm-summary ratios", + "interval": "Pointwise paired percentile bootstrap; resample fresh paired server blocks, never nested requests", + "resamples": 100000, + "seed": 20261129, + "schedule": "Each time block contains an A/A pair and an A/B pair; randomize balanced phase positions using recorded seed; alternate a,b and b,a within each phase", + "framing_gate": "TPOT requires matching per-request content-event counts across each pair; both arms use terminal usage, no token IDs, and disclose one-token-first-content assumption", + "decision": "Every primary endpoint needs A/A equivalence in the placebo band, A/B required precision and within-tolerance/non-regression. A calibrated clear regression fails even if imprecise. Uncalibrated or unresolved endpoints cannot pass.", + "phase_diagnostics": "After client timing only: three separate warmed non-streaming probe repetitions; retain and report all per-shape server-phase ratios and intervals, including losses; excluded from client gate", + "invalid_run_policy": "Any missing role archive, identity, quality, cache/token, stream, framing or acquisition proof invalidates the affected claim. Preserve all data. No dropping samples, outcome-based extensions or threshold changes.", + "power_requirement": "At least 90% modeled joint probability of all A/A calibration and A/B precision/non-regression gates under parity and a 0.5% candidate loss; conservative variance/dependence sensitivity before fixing count", + "budget": { + "max_usd": 0, + "max_duration_s": 14400, + "no_preemption": true + }, + "historical_evidence": "Prior paired-probe v1 labels remain unchanged; this registration never relabels historical inconclusive observations", + "power_planning": { + "minimum_pairs": 16, + "pilot_pairs": 8, + "sd_upper_factor": 3, + "ab_sd_factors": [ + 1, + 1.5, + 2 + ], + "candidate_loss_scenarios": [ + 0, + 0.005 + ], + "ci_width_planning_factor": 2.5, + "variance_assumption": "Independent Gaussian pilot log ratios; uncertainty union bound over nine endpoints", + "endpoint_dependence": "Arbitrary; marginal failure probabilities added by union bound", + "joint_power_target": 0.9, + "lease_seconds": 14400, + "setup_build_upload_reserve_seconds": 4200 + } +} diff --git a/ci/inference-client-noise.json b/ci/inference-client-noise.json new file mode 100644 index 00000000..ee16d45b --- /dev/null +++ b/ci/inference-client-noise.json @@ -0,0 +1,13 @@ +{ + "protocol": "DGX Spark standalone streaming noise diagnostic v1", + "purpose": "Distinguish native generation variability from client delivery variability and correlate it with clocks, scheduling and CPU quota; no candidate or power verdict", + "baseline_sha": "cc2a27435e798649a9cb938d600d39722e4a2263", + "configuration": "qwen35-4b-standalone", + "arms": 2, + "workload": "Exact client-pilot request bodies and order: three cycled shapes, three repetitions, two64-token warmups before128-token measurement", + "acquisition": "Diagnostic curl streaming capture retains complete SSE including native terminal timings; not the pinned client's final timing path", + "hypotheses": ["Native predicted_ms varies with client elapsed time: engine/host variability", "Native predicted_ms is stable while client elapsed varies: delivery/client path", "GPU clocks, CPU placement/frequency or cgroup throttling covary with slow requests"], + "telemetry": "One-second GPU/host samples; monotonic request boundaries, CPU thread placement/frequency and cgroup CPU counters; standard native logging, phase tracing off", + "analysis": "Retain every raw stream; identical request IDs/text/token counts and complete usage/length/DONE required. Correlation alone does not establish a causal fix; no historical verdict changes.", + "budget": {"approved": true, "max_usd": 0, "max_duration_s": 14400, "controller_duration_s": 3600, "no_preemption": true} +} diff --git a/scripts/inference-client-plan.py b/scripts/inference-client-plan.py new file mode 100644 index 00000000..ca76df16 --- /dev/null +++ b/scripts/inference-client-plan.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 +"""Size a final comparison from an independently audited client pilot.""" + +import argparse +import sys +from pathlib import Path + +from lib.ci_artifacts import digest, read_json, write_json +from lib.inference_client_power import plan + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("pilot", type=Path) + parser.add_argument("output", type=Path) + args = parser.parse_args() + proof = args.pilot / "raw-evidence-verified.json" + evidence = args.pilot / "client-pilot.json" + result = plan(read_json(evidence), read_json(proof)) + result.update(pilot_receipt_sha256=digest(evidence), independent_audit_sha256=digest(proof)) + write_json(args.output, result) + print(f'{result["configuration"]}: {result["status"]}; {result["pairs_per_phase"]} pairs per phase; ' + f'estimated {result["estimated_duration_s"] / 3600:.2f}h / 4h lease') + + +if __name__ == "__main__": + try: + main() + except (OSError, KeyError, ValueError) as error: + sys.exit(str(error)) diff --git a/scripts/inference-paired.py b/scripts/inference-paired.py index 296dd72a..a19e1dde 100644 --- a/scripts/inference-paired.py +++ b/scripts/inference-paired.py @@ -24,6 +24,9 @@ from lib import inference_noise as noise from lib import inference_client as client from lib import inference_client_pilot as client_pilot +from lib import inference_client_final as client_final +from lib.inference_client_report import render as client_report +from lib import inference_client_noise as client_noise ROOT = Path(__file__).resolve().parents[1] EXECUTE = run_path(str(ROOT / "scripts/inference-execute.py"))["execute"] @@ -115,6 +118,10 @@ def run_arm(design, main, baseline, key, mode, output): phase_profile=kind == "profile") elif design["experiment"] == "client": EXECUTE("pr", key, mode, probe=client.measure) + elif design["experiment"] in {"client-aa", "client-ab"}: + EXECUTE("pr", key, mode, probe=client_final.measure) + elif design["experiment"] == "client-noise": + EXECUTE("pr", key, mode, probe=client_noise.measure) else: EXECUTE("pr", key, mode, REPETITIONS) finally: @@ -146,6 +153,12 @@ def ready(): def execute(key, mode, baseline, experiment="paired"): + streamed_noise = experiment == "client-noise" + if streamed_noise: + client_noise.schedule(baseline, f"{key}-{mode}") + final = experiment == "client-final" + if final: + client_final.schedule(baseline, "pending", f"{key}-{mode}") sizing = experiment == "client-pilot" if sizing: client_pilot.schedule(baseline, f"{key}-{mode}") @@ -163,7 +176,7 @@ def execute(key, mode, baseline, experiment="paired"): raise ValueError("paired comparison candidate differs from JY admission") output = Path(os.environ["JIANYANG_ARTIFACT_DIR"]).resolve() output.mkdir(parents=True, exist_ok=True) - if sizing: + if sizing or final: doctor = command([str(ROOT / "scripts/inferencekit.sh"), "doctor", "--json"], timeout=180, capture_stdout=True, overrides={"INFERENCEKIT_RUNS_DIR": str(output / "doctor-records")}) @@ -174,7 +187,9 @@ def execute(key, mode, baseline, experiment="paired"): with baseline_tree(baseline) as main: identities = prepare(main, baseline, candidate, output) local = host(role, node) - designs = (client_pilot.schedule(baseline, f"{key}-{mode}") if sizing else + designs = (client_noise.schedule(baseline, f"{key}-{mode}") if streamed_noise else + client_final.schedule(baseline, candidate, f"{key}-{mode}") if final else + client_pilot.schedule(baseline, f"{key}-{mode}") if sizing else noise.schedule(baseline, kind) if diagnostic else schedule(baseline, candidate)) if role == "worker": leader = next(p["host"] for p in peers if p["role"] == "leader") @@ -202,6 +217,14 @@ def execute(key, mode, baseline, experiment="paired"): registered = client_pilot.registration() evidence.update(protocol=registered["protocol"], rounds=registered["pairs"], sizing_only=True, registration=registered) + if final: + registered = client_final.registration() + evidence.update(protocol=registered["protocol"], registration=registered, + rounds=registered["configurations"][f"{key}-{mode}"]["pairs_per_phase"]) + if streamed_noise: + registered = client_noise.registration() + evidence.update(protocol=registered["protocol"], registration=registered, + rounds=registered["arms"], diagnostic_only=True) try: for index, design in enumerate(designs): if coordinator: @@ -214,7 +237,9 @@ def execute(key, mode, baseline, experiment="paired"): coordinate = f'{coordinate["repo"]}@{coordinate["revision"]}' evidence["runs"].append({**design, "placements": placements, "quality": "passed", "arm_duration_s": time.monotonic() - started, - "samples": (client.verify(directory, coordinate) if sizing else + "samples": (read_json(directory / "client-noise.json") if streamed_noise else + client_final.verify(coordinate, directory) if final else + client.verify(directory, coordinate) if sizing else read_json(directory / f"noise-{kind}.json") if diagnostic else samples(directory, coordinate))}) # Preserve the existing standalone nightly smoke receipts too. @@ -223,14 +248,20 @@ def execute(key, mode, baseline, experiment="paired"): "provenance.json", "split-admissions.json", "split-peer.json"): if (directory / name).is_file(): shutil.copyfile(directory / name, output / name) - if sizing: + if streamed_noise: + evidence["status"] = "diagnostic-complete" + elif final: + evidence["summary"] = client_final.summarize(evidence) + (output / "client-final.md").write_text(client_report(evidence)) + elif sizing: evidence["summary"] = client_pilot.summarize(evidence) elif not diagnostic: evidence["summary"] = summarize(evidence, candidate, baseline, f"{key}-{mode}") else: evidence["status"] = "diagnostic-complete" finally: - write_json(output / ("client-pilot.json" if sizing else + write_json(output / ("client-noise.json" if streamed_noise else + "client-final.json" if final else "client-pilot.json" if sizing else f"noise-{kind}.json" if diagnostic else "paired-probe.json"), evidence) @@ -239,10 +270,10 @@ def execute(key, mode, baseline, experiment="paired"): parser.add_argument("model") parser.add_argument("mode", choices=("standalone", "split")) parser.add_argument("baseline") - parser.add_argument("experiment", nargs="?", choices=("paired", "noise-pilot", "noise-profile", "client-pilot"), default="paired") + parser.add_argument("experiment", nargs="?", choices=("paired", "noise-pilot", "noise-profile", "client-pilot", "client-final", "client-noise"), default="paired") args = parser.parse_args() try: - with cancel_on_signal(), time_budget(14400): + with cancel_on_signal(), time_budget(3600 if args.experiment == "client-noise" else 14400): execute(args.model, args.mode, args.baseline, args.experiment) except (OSError, ValueError, KeyError, RuntimeError, subprocess.SubprocessError, KeyboardInterrupt) as error: sys.exit(str(error)) diff --git a/scripts/lib/inference_client_decision.py b/scripts/lib/inference_client_decision.py new file mode 100644 index 00000000..8536b5e2 --- /dev/null +++ b/scripts/lib/inference_client_decision.py @@ -0,0 +1,70 @@ +"""Prospective client decisions; historical paired-probe v1 stays unchanged.""" + +import math +import random +from statistics import fmean + +EFFECT = 0.02 +PRECISION = 0.01 +PLACEBO = (0.99, 1.01) +RESAMPLES = 100_000 +SEED = 20261129 + + +def paired_interval(log_ratios, resamples=RESAMPLES, seed=SEED): + """Percentile bootstrap over independent paired server blocks, never requests.""" + if (len(log_ratios) < 4 or type(resamples) is not int or resamples < 1000 + or any(type(v) not in (int, float) or not math.isfinite(v) for v in log_ratios)): + raise ValueError("client interval requires finite independent paired blocks") + rng = random.Random(seed) + size = len(log_ratios) + draws = sorted(fmean(log_ratios[min(int(rng.random() * size), size - 1)] for _ in range(size)) + for _ in range(resamples)) + low = draws[int(0.025 * (resamples - 1))] + high = draws[math.ceil(0.975 * (resamples - 1))] + return {"ratio": math.exp(fmean(log_ratios)), "ci95": [math.exp(low), math.exp(high)], + "independent_pairs": size, "resamples": resamples, "seed": seed, + "estimator": "geometric mean of within-pair candidate/main ratios"} + + +def decide(interval, calibration, direction): + if direction not in {"higher", "lower"}: + raise ValueError("unknown client metric direction") + low, high = interval["ci95"] + aa_low, aa_high = calibration["ci95"] + if (not all(type(v) in (int, float) and math.isfinite(v) and v > 0 + for v in (low, high, aa_low, aa_high)) or low > high or aa_low > aa_high): + raise ValueError("invalid client ratio interval") + half_width = (high - low) / 2 + calibrated = PLACEBO[0] <= aa_low <= aa_high <= PLACEBO[1] + precise = half_width <= PRECISION or math.isclose(half_width, PRECISION, rel_tol=0, abs_tol=1e-12) + regression = high < 1 - EFFECT if direction == "higher" else low > 1 + EFFECT + improvement = low > 1 + EFFECT if direction == "higher" else high < 1 - EFFECT + within = 1 - EFFECT <= low <= high <= 1 + EFFECT + non_regression = low >= 1 - EFFECT if direction == "higher" else high <= 1 + EFFECT + # A clear contradiction takes precedence over insufficient precision. An + # invalid placebo never permits an A/B claim, including a regression claim. + if not calibrated: + verdict, comparison = "UNPROVEN", "invalid_calibration" + elif regression: + verdict, comparison = "FAIL", "material_regression" + elif not precise: + verdict, comparison = "UNPROVEN", "insufficient_precision" + elif within: + verdict, comparison = "PASS", "within_tolerance" + elif improvement: + verdict, comparison = "PASS", "material_improvement" + elif non_regression: + verdict, comparison = "PASS", "non_regression" + else: + verdict, comparison = "UNPROVEN", "margin_unresolved" + return {"claim_verdict": verdict, "comparison": comparison, "calibrated": calibrated, + "precision_met": precise, "ratio_half_width": half_width, + "effect": EFFECT, "maximum_half_width": PRECISION, "placebo_band": list(PLACEBO)} + + +def all_endpoints(decisions): + if len(decisions) != 9: + raise ValueError("client claim requires every registered shape and endpoint") + verdicts = {d["claim_verdict"] for d in decisions} + return "FAIL" if "FAIL" in verdicts else "PASS" if verdicts == {"PASS"} else "UNPROVEN" diff --git a/scripts/lib/inference_client_final.py b/scripts/lib/inference_client_final.py new file mode 100644 index 00000000..351b0ae6 --- /dev/null +++ b/scripts/lib/inference_client_final.py @@ -0,0 +1,137 @@ +"""Registered final acquisition; refuses to run until sizing and count are frozen.""" + +import math +import random +from statistics import fmean + +from .ci_artifacts import read_json, write_json +from .inference_client import ROOT, measure as client_measure, verify as client_verify +from .inference_client_decision import EFFECT, PLACEBO, PRECISION, RESAMPLES, all_endpoints, decide, paired_interval +from .inference_probe import measure as phase_measure, validate_evidence + +REGISTRATION = ROOT / "ci/inference-client-final.json" + + +def registration(): + return read_json(REGISTRATION) + + +def schedule(baseline, candidate, configuration, design=None): + design = registration() if design is None else design + config = design["configurations"].get(configuration, {}) + pairs = config.get("pairs_per_phase") + fixed = {"material_effect": EFFECT, "maximum_pointwise_ci95_ratio_half_width": PRECISION, + "placebo_ci95_band": list(PLACEBO), "resamples": RESAMPLES, + "primary_metrics": {"ttft_ms": "lower", "tpot_ms": "lower", "request_tok_s": "higher"}, + "shapes": [0, 1, 2]} + if any(design.get(k) != v for k, v in fixed.items()): + raise ValueError("final client decision policy differs from registration") + if (design["status"] != "registered" or baseline != design["baseline_sha"] + or type(pairs) is not int or pairs < 16 or pairs % 2 or not config.get("planning_evidence")): + raise ValueError("final client count and power plan must be registered before acquisition") + plan = config["planning_evidence"] + scenarios = {(s["candidate_loss"], s["ab_sd_factor"]): s["modeled_joint_power_lower_bound"] + for s in plan["scenarios"]} + if (plan["status"] != "feasible" or plan["pairs_per_phase"] != pairs + or not 0 < plan["estimated_duration_s"] <= plan["maximum_duration_s"] <= 14400 + or set(scenarios) != {(loss, factor) for loss in (0, .005) for factor in (1, 1.5, 2)} + or min(scenarios.values()) < .9): + raise ValueError("final client power plan is insufficient or exceeds the lease") + rng = random.Random(design["seed"]) + phase_orders = sorted([(rng.random(), i % 2) for i in range(pairs)]) + result = [] + for block, (_, phase_first) in enumerate(phase_orders): + for phase in (("aa", "ab") if phase_first == 0 else ("ab", "aa")): + for arm in (("a", "b") if block % 2 == 0 else ("b", "a")): + result.append({"experiment": f"client-{phase}", "round": block, "arm": arm, + "source_sha": candidate if phase == "ab" and arm == "b" else baseline}) + return result + + +def measure(model, output): + client_measure(model, output) + # These requests cannot enter client timing or replace its independent + # pairs. They expose server-phase changes without silently hiding a loss. + for repetition in range(3): + directory = output / f"phase-{repetition}" + directory.mkdir() + phase_measure(model, directory, repetition) + write_json(output / "phase-diagnostics.json", phases(model, output)) + + +def phases(model, output): + values = [] + for repetition in range(3): + path = output / f"phase-{repetition}" / "throughput-probe.json" + responses = validate_evidence(read_json(path), model) + values.extend({"shape": shape, "prompt_tokens": r["usage"]["prompt_tokens"], + "prefill_ms": r["timings"]["prompt_ms"], + "decode_ms": r["timings"]["predicted_ms"]} for shape, r in enumerate(responses)) + result = [] + for shape in range(3): + selected = [v for v in values if v["shape"] == shape] + if len({v["prompt_tokens"] for v in selected}) != 1: + raise ValueError("phase diagnostic input shape changed") + result.append({"shape": shape, "prompt_tokens": selected[0]["prompt_tokens"], + **{metric: fmean(v[metric] for v in selected) for metric in ("prefill_ms", "decode_ms")}}) + return result + + +def verify(model, output): + result = client_verify(output, model) + root = next((output / "inferencekit").glob("ev_*/evidence.json")).parent + rows = [read_json(path) for path in sorted((root / "outputs/qualification").glob("shape-*/*.json"))] + framing = {r["id"]: len(r["timings"]["event_ms"]) for r in rows} + input_tokens = {r["bucket"]: r["usage"]["prompt_tokens"] for r in rows} + phase_results = phases(model, output) + if phase_results != read_json(output / "phase-diagnostics.json"): + raise ValueError("phase diagnostic receipt differs from raw responses") + return {"client": result, "framing": framing, "input_tokens": input_tokens, "phases": phase_results} + + +def summarize(evidence, design=None, resamples=None): + design = registration() if design is None else design + expected = schedule(evidence["baseline_sha"], evidence["source_sha"], evidence["configuration"], design) + runs = evidence["runs"] + if (evidence["registration"] != design or len(runs) != len(expected) + or any(any(r.get(k) != v for k, v in d.items()) + or r["placements"] != evidence["placements"] or r["quality"] != "passed" + or r["samples"]["client"]["status"] != "passed" + for r, d in zip(runs, expected))): + raise ValueError("final client acquisition is incomplete, reordered or changed allocation") + count = design["configurations"][evidence["configuration"]]["pairs_per_phase"] + by_pair = {(r["experiment"], r["round"], r["arm"]): r["samples"] for r in runs} + if len({tuple(sorted(r["samples"]["input_tokens"].items())) for r in runs}) != 1: + raise ValueError("client prompt token shapes changed between source arms") + decisions, diagnostics = [], [] + for shape in design["shapes"]: + for metric, direction in design["primary_metrics"].items(): + intervals = {} + framing_ok = True + for phase in ("aa", "ab"): + logs = [] + for block in range(count): + a, b = (by_pair[f"client-{phase}", block, arm] for arm in ("a", "b")) + framing_ok &= a["framing"] == b["framing"] + values = [v["client"]["summaries"][shape][metric] for v in (a, b)] + logs.append(math.log(values[1] / values[0])) + intervals[phase] = paired_interval(logs, resamples or design["resamples"], design["seed"]) + decision = decide(intervals["ab"], intervals["aa"], direction) + if metric == "tpot_ms" and not framing_ok: + decision.update(claim_verdict="UNPROVEN", comparison="incompatible_event_framing") + absolute = {arm: math.exp(fmean(math.log(by_pair["client-ab", block, arm]["client"]["summaries"][shape][metric]) + for block in range(count))) for arm in ("a", "b")} + decisions.append({"shape": shape, "metric": metric, "direction": direction, + "main": absolute["a"], "candidate": absolute["b"], + "aa": intervals["aa"], "ab": intervals["ab"], **decision}) + for metric in ("prefill_ms", "decode_ms"): + if len({r["samples"]["phases"][shape]["prompt_tokens"] for r in runs}) != 1: + raise ValueError("phase diagnostic input tokens changed between arms") + ratios = {phase: [math.log(by_pair[f"client-{phase}", r, "b"]["phases"][shape][metric] / + by_pair[f"client-{phase}", r, "a"]["phases"][shape][metric]) + for r in range(count)] for phase in ("aa", "ab")} + diagnostics.append({"shape": shape, "metric": metric, "scope": "server phase diagnostic", + **{phase: paired_interval(values, resamples or design["resamples"], design["seed"]) + for phase, values in ratios.items()}}) + return {"claim_verdict": all_endpoints(decisions), "client_endpoints": decisions, + "server_phase_diagnostics": diagnostics, "scope": design["scope"]} diff --git a/scripts/lib/inference_client_noise.py b/scripts/lib/inference_client_noise.py new file mode 100644 index 00000000..771ed329 --- /dev/null +++ b/scripts/lib/inference_client_noise.py @@ -0,0 +1,134 @@ +"""Bounded streamed native-timing/host diagnostic, never final qualification.""" + +import json +import math +import threading +import time +from pathlib import Path + +from .ci_artifacts import read_json, write_json +from .ci_process import command +from .ci_smoke import curl +from .inference_checks import ENDPOINT +from .inference_client import ROOT, expected_body, prompts +from .inference_noise import diagnostics + +REGISTRATION = ROOT / "ci/inference-client-noise.json" + + +def registration(): + return read_json(REGISTRATION) + + +def schedule(baseline, configuration): + design = registration() + if baseline != design["baseline_sha"] or configuration != design["configuration"]: + raise ValueError("client noise diagnostic requires its registered main/configuration") + return [{"experiment": "client-noise", "round": arm, "arm": "a", "source_sha": baseline} + for arm in range(design["arms"])] + + +def parse(raw, request): + text, finish, usage, timing, done = [], None, None, None, False + for line in raw.splitlines(): + if not line.startswith("data: "): + continue + if line == "data: [DONE]": + done = True + continue + item = json.loads(line[6:]) + if item.get("error") is not None: + raise ValueError("diagnostic stream returned an error") + if item.get("usage") is not None: + usage, timing = item["usage"], item.get("timings") + for choice in item.get("choices", []): + content = choice.get("delta", {}).get("content") + if isinstance(content, str): + text.append(content) + finish = choice.get("finish_reason") or finish + if (not done or finish != "length" or not "".join(text).strip() or not usage or not timing + or usage["completion_tokens"] != request["max_tokens"] + or timing["predicted_n"] != request["max_tokens"] + or usage["prompt_tokens_details"]["cached_tokens"] != 0 + or usage["prompt_tokens"] != timing["prompt_n"]): + raise ValueError("diagnostic requires complete uncached stream and native timings") + if not all(type(timing[k]) in (int, float) and math.isfinite(timing[k]) and timing[k] > 0 + for k in ("prompt_ms", "predicted_ms")): + raise ValueError("diagnostic requires positive native phase timings") + return {"text": "".join(text), "usage": usage, "timings": timing} + + +def host_record(): + def optional(path): + try: + return path.read_text().strip() + except OSError as error: + return {"unavailable": str(error)} + rows = [r for r in command(["ps", "-eL", "-o", "pid=,tid=,psr=,pcpu=,comm="], + timeout=5, capture_stdout=True).splitlines() if r.strip()] + pids = {r.split()[0] for r in rows if r.split()[-1] == "skippy"} + group = optional(Path("/proc/self/cgroup")) + root = Path("/sys/fs/cgroup") + relative = next((line[3:] for line in group.splitlines() if line.startswith("0::")), "") if isinstance(group, str) else "" + directory = root / relative.lstrip("/") + groups = {} + while directory.is_relative_to(root): + if directory.is_dir(): + groups[str(directory)] = {name: optional(directory / name) for name in + ("cpu.max", "cpu.stat", "cpu.pressure", "cpuset.cpus.effective")} + if directory == root: + break + directory = directory.parent + return {"monotonic_ns": time.perf_counter_ns(), "wall_time_ns": time.time_ns(), + "server_threads": [r.strip() for r in rows if r.split()[0] in pids], + "cpu_frequencies": {p.parent.parent.name: optional(p) for p in + Path("/sys/devices/system/cpu").glob("cpu*/cpufreq/scaling_cur_freq")}, + "cgroup_ancestors": groups, "process_cgroup": group} + + +def measure(model, output): + telemetry = output / "telemetry" + telemetry.mkdir() + evidence = {"registration": registration(), "diagnostic_only": True, "status": "incomplete", "samples": []} + done, errors = threading.Event(), [] + def sample(): + try: + with (telemetry / "cpu.jsonl").open("w") as stream: + while not done.is_set(): + stream.write(json.dumps(host_record()) + "\n") + stream.flush() + done.wait(1) + except BaseException as error: + errors.append(str(error)) + counts = {} + try: + with diagnostics(telemetry): + thread = threading.Thread(target=sample, daemon=True) + thread.start() + try: + for prompt in prompts(model): + request = expected_body(model, prompt) + row = {"id": prompt["id"], "bucket": prompt["bucket"], "request": request, + "started_ns": time.perf_counter_ns(), "started_wall_ns": time.time_ns()} + evidence["samples"].append(row) + row["raw_sse"] = curl(["--no-buffer", "-H", "Content-Type: application/json", "--data-binary", + json.dumps(request), ENDPOINT + "/v1/chat/completions"], 180) + row["completed_ns"] = time.perf_counter_ns() + row["parsed"] = parse(row["raw_sse"], request) + shape = prompt["bucket"].split("-")[-1] + count = row["parsed"]["usage"]["prompt_tokens"] + if count != counts.setdefault(shape, count): + raise ValueError("diagnostic prompt shape changed") + finally: + done.set() + thread.join(timeout=10) + if thread.is_alive(): + raise RuntimeError("CPU diagnostic sampler did not stop") + if errors: + raise RuntimeError("CPU diagnostic capture failed: " + "; ".join(errors)) + evidence["status"] = "diagnostic-complete" + except BaseException as error: + evidence.update(status="failed", error=str(error)) + raise + finally: + write_json(output / "client-noise.json", evidence) diff --git a/scripts/lib/inference_client_power.py b/scripts/lib/inference_client_power.py new file mode 100644 index 00000000..aa72c09c --- /dev/null +++ b/scripts/lib/inference_client_power.py @@ -0,0 +1,112 @@ +"""Conservative prospective normal-model sizing, separate from final inference.""" + +import math +from statistics import NormalDist, stdev + +from .inference_client_decision import EFFECT, PLACEBO, PRECISION + +SD_FACTOR = 3 +CI_WIDTH_FACTOR = 2.5 +AB_SD_FACTORS = (1, 1.5, 2) +MINIMUM_PAIRS = 16 +TARGET = 0.90 + + +def variance_miss_bound(): + # Eight independent Gaussian pilot ratios give df=7. With an upper SD of + # 3*s, the miss probability is P(chi-square_7 < 7/9). This closed form is + # the half-integer incomplete gamma recurrence. Union bound over 9 metrics. + x = 7 / SD_FACTOR ** 2 + tail = (math.erf(math.sqrt(x / 2)) - math.exp(-x / 2) * math.sqrt(2 * x / math.pi) + * (1 + x / 3 + x * x / 15)) + return 9 * tail + + +def endpoint_probabilities(sd, pairs, direction, loss, ab_sd_factor): + se_aa = sd * SD_FACTOR / math.sqrt(pairs) + se_ab = se_aa * ab_sd_factor + width_aa, width_ab = CI_WIDTH_FACTOR * se_aa, CI_WIDTH_FACTOR * se_ab + normal = NormalDist() + lower = math.log(PLACEBO[0]) + width_aa + upper = math.log(PLACEBO[1]) - width_aa + aa = max(0, normal.cdf(upper / se_aa) - normal.cdf(lower / se_aa)) + mean = math.log(1 - loss if direction == "higher" else 1 + loss) + # exp(mean_hat)*sinh(log half-width) is the ratio-scale half-width. + precision_upper = math.log(PRECISION / math.sinh(width_ab)) if width_ab < 700 else -math.inf + if direction == "higher": + lo = math.log(1 - EFFECT) + width_ab + hi = precision_upper + ab = max(0, normal.cdf((hi - mean) / se_ab) - normal.cdf((lo - mean) / se_ab)) + else: + hi = min(math.log(1 + EFFECT) - width_ab, precision_upper) + ab = normal.cdf((hi - mean) / se_ab) + return aa, ab + + +def joint_power(endpoints, pairs, loss, ab_sd_factor): + # This union bound permits arbitrary endpoint and A/A–A/B dependence; it + # does not estimate a fragile 9x9 covariance matrix from eight observations. + failures = variance_miss_bound() + for endpoint in endpoints: + sd = max(stdev(endpoint["paired_log_ratios"]), 0.0001) + direction = "higher" if endpoint["metric"] == "request_tok_s" else "lower" + aa, ab = endpoint_probabilities(sd, pairs, direction, loss, ab_sd_factor) + failures += (1 - aa) + (1 - ab) + return max(0, 1 - failures) + + +def plan(evidence, proof): + endpoints = proof["summary"]["endpoints"] + if (proof.get("all_raw_quality_identity_gates") != "verified" or proof.get("independent_pairs") != 8 + or proof["source_sha"] != evidence["source_sha"] + or proof["baseline_sha"] != evidence["baseline_sha"] + or proof["configuration"] != evidence["configuration"] + or len(endpoints) != 9 or any(len(e["paired_log_ratios"]) != 8 for e in endpoints)): + raise ValueError("power planning requires a complete independently audited eight-pair pilot") + scenarios = [(loss, factor) for loss in (0, .005) for factor in AB_SD_FACTORS] + def powered(pairs): + return min(joint_power(endpoints, pairs, *s) for s in scenarios) >= TARGET + upper = MINIMUM_PAIRS + while upper < 100_000 and not powered(upper): + upper = min(upper * 2, 100_000) + if not powered(upper): + raise ValueError("power target exceeds the bounded planning range") + lower = MINIMUM_PAIRS // 2 + upper //= 2 + while lower < upper: + middle = (lower + upper) // 2 + if powered(middle * 2): + upper = middle + else: + lower = middle + 1 + pairs = lower * 2 + runs = evidence["runs"] + arm_seconds = max(r["arm_duration_s"] for r in runs) + # Final-only phase diagnostics add 9 warmups and 9 measured responses. + # Twice the measured client window allows a full-length warmup for each. + phase_seconds = max(2 * sum(s["e2e_ms"] for s in r["samples"]["samples"]) / 1000 for r in runs) + reserve_seconds = 3600 + 600 # both source builds, setup, upload and cleanup + duration = reserve_seconds + 4 * pairs * (arm_seconds + phase_seconds) + return {"status": "feasible" if duration <= 14400 else "lease_shortfall", + "configuration": evidence["configuration"], "pilot_source_sha": evidence["source_sha"], + "baseline_sha": evidence["baseline_sha"], "pairs_per_phase": pairs, + "total_fresh_arms": pairs * 4, "estimated_duration_s": duration, + "maximum_duration_s": 14400, "max_usd": 0, + "arm_duration_upper_s": arm_seconds, "phase_diagnostic_allowance_s": phase_seconds, + "setup_build_upload_reserve_s": reserve_seconds, + "scenarios": [{"candidate_loss": loss, "ab_sd_factor": factor, + "modeled_joint_power_lower_bound": joint_power(endpoints, pairs, loss, factor)} + for loss, factor in scenarios], + "pilot_variance_miss_union_bound": variance_miss_bound(), + "sd_upper_factor": SD_FACTOR, "ci_width_planning_factor": CI_WIDTH_FACTOR, + "minimum_log_sd": 0.0001, "minimum_pairs": MINIMUM_PAIRS, + "assumptions": ["Eight independent Gaussian pilot log ratios per endpoint", + "Fresh final pairs follow that normal model within the inflated SD envelopes", + "Final CI log half-width planning proxy is 2.5*SD/sqrt(pairs)", + "No endpoint dependence assumption: failures are added by union bound", + "A/A centered at parity; A/B parity and 0.5% loss both required", + "Normal model is an estimate, not proof of power under heavy tails or serial drift"], + "sources": ["https://www.itl.nist.gov/div898/handbook/prc/section2/prc231.htm", + "InferenceKit benchmarking references/statistics.md round-sizing heuristic"], + "independent_endpoint_vectors": endpoints, + "acquisition_permission": "Freeze count/analysis/placement policy before fresh final acquisition; a lease shortfall forbids dispatch"} diff --git a/scripts/lib/inference_client_report.py b/scripts/lib/inference_client_report.py new file mode 100644 index 00000000..4df5adbd --- /dev/null +++ b/scripts/lib/inference_client_report.py @@ -0,0 +1,42 @@ +"""Fixed client/phase tables for the prospectively registered final protocol.""" + +from .inference_probe import PARAGRAPHS + + +def ratio(interval): + low, high = interval["ci95"] + return f'{interval["ratio"]:.4f} [{low:.4f}, {high:.4f}]' + + +def render(evidence): + summary = evidence["summary"] + lines = [f'### Registered client qualification: {evidence["configuration"]}', "", + f'Main `{evidence["baseline_sha"]}` · candidate `{evidence["source_sha"]}`', "", + f'Client non-regression claim: **{summary["claim_verdict"]}**. {summary["scope"]}.', "", + "Ratios are candidate/main in each metric's native direction. Intervals are pointwise 95%,", + "bootstrapped over fresh paired server blocks. Nested requests are not independent pairs.", "", + "| Paragraphs | Client metric | Main | Candidate | A/B ratio [CI95] | A/A ratio [CI95] | Half-width | Registered decision |", + "| ---: | --- | ---: | ---: | --- | --- | ---: | --- |"] + names = {"ttft_ms": "TTFT ms (lower)", "tpot_ms": "TPOT ms (lower)", + "request_tok_s": "Output tok/active request-second (higher)"} + for endpoint in summary["client_endpoints"]: + lines.append(f'| {PARAGRAPHS[endpoint["shape"]]} | {names[endpoint["metric"]]} | ' + f'{endpoint["main"]:.3f} | {endpoint["candidate"]:.3f} | ' + f'{ratio(endpoint["ab"])} | {ratio(endpoint["aa"])} | ' + f'{endpoint["ratio_half_width"] * 100:.3f}% | ' + f'{endpoint["claim_verdict"]}: {endpoint["comparison"]} |') + lines += ["", "Absolute values are geometric means of per-arm summaries (median TTFT/TPOT;", + "output rate is measured output tokens / summed measured request seconds for that shape).", + "Warmups and other shapes are excluded. This is concurrency-one service rate, not capacity.", + "TTFT includes connection setup. TPOT assumes one token in the first content event;", + "the client process persists but each HTTP request opens a new connection.", "", + "#### Fresh server-phase diagnostics", "", + "Collected after client timing. These phase intervals are outside the client claim;", + "a client pass does not prove server-phase non-regression. Historical inconclusive", + "server-phase verdicts remain unchanged.", "", + "| Paragraphs | Server phase latency | A/B ratio [CI95] | A/A ratio [CI95] |", + "| ---: | --- | --- | --- |"] + for endpoint in summary["server_phase_diagnostics"]: + lines.append(f'| {PARAGRAPHS[endpoint["shape"]]} | {endpoint["metric"]} (lower) | ' + f'{ratio(endpoint["ab"])} | {ratio(endpoint["aa"])} |') + return "\n".join(lines) + "\n" diff --git a/scripts/tests/inference_client_decision.py b/scripts/tests/inference_client_decision.py new file mode 100644 index 00000000..9101d289 --- /dev/null +++ b/scripts/tests/inference_client_decision.py @@ -0,0 +1,132 @@ +"""Prospective statistical decisions; no historical labels or hardware claims.""" + +import math +import copy +import unittest + +from lib.inference_client_decision import all_endpoints, decide, paired_interval +from lib import inference_client_final as final +from lib.inference_client_report import render + + +def ci(low, high): + return {"ci95": [low, high]} + + +def registered_design(): + design = final.registration() + design["status"] = "registered" + plan = {"status": "feasible", "pairs_per_phase": 16, "estimated_duration_s": 7200, + "maximum_duration_s": 14400, "scenarios": [ + {"candidate_loss": loss, "ab_sd_factor": factor, "modeled_joint_power_lower_bound": .95} + for loss in (0, .005) for factor in (1, 1.5, 2)]} + design["configurations"]["qwen35-4b-standalone"].update(pairs_per_phase=16, planning_evidence=plan) + return design + + +class DecisionTests(unittest.TestCase): + def test_exact_equality_is_a_precise_within_tolerance_result(self): + interval = paired_interval([0] * 8, resamples=1000) + self.assertEqual(interval["ci95"], [1, 1]) + for direction in ("higher", "lower"): + result = decide(interval, interval, direction) + self.assertEqual((result["claim_verdict"], result["comparison"]), ("PASS", "within_tolerance")) + + def test_material_boundaries_use_each_metric_native_direction(self): + for interval, direction, verdict, comparison in ( + (ci(1.03, 1.04), "higher", "PASS", "material_improvement"), + (ci(1.03, 1.04), "lower", "FAIL", "material_regression"), + (ci(.96, .97), "higher", "FAIL", "material_regression"), + (ci(.96, .97), "lower", "PASS", "material_improvement"), + (ci(1.015, 1.025), "higher", "PASS", "non_regression"), + (ci(1.015, 1.025), "lower", "UNPROVEN", "margin_unresolved"), + (ci(.975, .985), "lower", "PASS", "non_regression"), + (ci(.975, .985), "higher", "UNPROVEN", "margin_unresolved")): + with self.subTest(interval=interval, direction=direction): + result = decide(interval, ci(.999, 1.001), direction) + self.assertEqual((result["claim_verdict"], result["comparison"]), (verdict, comparison)) + + def test_width_and_biased_placebo_cannot_pass_even_when_point_estimate_is_a_tie(self): + result = decide(ci(.98, 1.02), ci(.999, 1.001), "higher") + self.assertEqual(result["comparison"], "insufficient_precision") + for placebo in (ci(.989, 1), ci(1, 1.011), ci(1.02, 1.02)): + self.assertEqual(decide(ci(1, 1), placebo, "higher")["comparison"], "invalid_calibration") + # A placebo interval need not include exact equality to establish its + # prospectively registered practical equivalence band. + self.assertEqual(decide(ci(1, 1), ci(1.002, 1.004), "higher")["claim_verdict"], "PASS") + self.assertEqual(decide(ci(.99, 1.01), ci(1, 1), "higher")["claim_verdict"], "PASS") + + def test_clear_regression_is_reported_even_when_interval_is_wide(self): + result = decide(ci(.8, .95), ci(1, 1), "higher") + self.assertEqual(result["claim_verdict"], "FAIL") + self.assertFalse(result["precision_met"]) + + def test_bootstrap_preserves_pairs_and_does_not_multiply_nested_requests(self): + values = [math.log(v) for v in (.99, 1, 1.01, 1.02, .98, 1.01, 1, .99)] + first = paired_interval(values, resamples=1000) + self.assertEqual(first, paired_interval(values, resamples=1000)) + self.assertEqual(first["independent_pairs"], 8) + self.assertLess(first["ci95"][0], first["ratio"]) + self.assertGreater(first["ci95"][1], first["ratio"]) + with self.assertRaises(ValueError): + paired_interval([0, 0, 0], resamples=1000) + + def test_every_endpoint_must_pass_and_one_loss_cannot_be_outvoted(self): + passed = decide(ci(.998, 1.002), ci(.999, 1.001), "higher") + failed = decide(ci(.96, .97), ci(1, 1), "higher") + unresolved = decide(ci(.975, .985), ci(1, 1), "higher") + self.assertEqual(all_endpoints([passed] * 9), "PASS") + self.assertEqual(all_endpoints([passed] * 8 + [unresolved]), "UNPROVEN") + self.assertEqual(all_endpoints([passed] * 8 + [failed]), "FAIL") + with self.assertRaises(ValueError): + all_endpoints([passed]) + + def test_final_acquisition_refuses_unregistered_count_and_balances_every_pair(self): + design = final.registration() + config = "qwen35-4b-standalone" + with self.assertRaisesRegex(ValueError, "registered before acquisition"): + final.schedule(design["baseline_sha"], "b" * 40, config) + design = registered_design() + arms = final.schedule(design["baseline_sha"], "b" * 40, config, design) + self.assertEqual(len(arms), 64) + self.assertEqual(arms, final.schedule(design["baseline_sha"], "b" * 40, config, design)) + for block in range(16): + selected = [a for a in arms if a["round"] == block] + self.assertEqual({a["experiment"] for a in selected}, {"client-aa", "client-ab"}) + self.assertEqual([a["arm"] for a in selected], ["a", "b", "a", "b"] if block % 2 == 0 else ["b", "a", "b", "a"]) + self.assertEqual(sum(a["source_sha"] == "b" * 40 for a in arms), 16) + design["configurations"][config]["planning_evidence"]["status"] = "lease_shortfall" + with self.assertRaisesRegex(ValueError, "exceeds the lease"): + final.schedule(design["baseline_sha"], "b" * 40, config, design) + + def test_final_summary_reports_phase_losses_without_changing_client_scope(self): + design = registered_design() + config = "qwen35-4b-standalone" + baseline, candidate = design["baseline_sha"], "b" * 40 + evidence = {"source_sha": candidate, "baseline_sha": baseline, "configuration": config, + "placements": [{"node": "offline fixture"}], "registration": design, "runs": []} + for arm in final.schedule(baseline, candidate, config, design): + phase_slow = 1.1 if arm["experiment"] == "client-ab" and arm["arm"] == "b" else 1 + evidence["runs"].append({**arm, "placements": evidence["placements"], "quality": "passed", + "samples": {"client": {"status": "passed", "summaries": [ + {"ttft_ms": 100, "tpot_ms": 10, "request_tok_s": 50}] * 3}, + "framing": {"id": 128}, "input_tokens": {"shape-0": 200}, "phases": [ + {"prefill_ms": 100 * phase_slow, "decode_ms": 200, "prompt_tokens": 200}] * 3}}) + result = final.summarize(evidence, design, resamples=1000) + self.assertEqual(result["claim_verdict"], "PASS") + self.assertEqual(len(result["client_endpoints"]), 9) + self.assertAlmostEqual(result["server_phase_diagnostics"][0]["ab"]["ratio"], 1.1) + evidence["summary"] = result + report = render(evidence) + self.assertIn("Client non-regression claim: **PASS**", report) + self.assertIn("1.1000 [1.1000, 1.1000]", report) + self.assertIn("client pass does not prove server-phase non-regression", report) + changed = copy.deepcopy(evidence) + changed["runs"][0]["samples"]["framing"] = {"id": 64} + result = final.summarize(changed, design, resamples=1000) + self.assertEqual(result["claim_verdict"], "UNPROVEN") + self.assertTrue(any(r["comparison"] == "incompatible_event_framing" for r in result["client_endpoints"])) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/inference_client_noise.py b/scripts/tests/inference_client_noise.py new file mode 100644 index 00000000..6005f4f9 --- /dev/null +++ b/scripts/tests/inference_client_noise.py @@ -0,0 +1,72 @@ +"""Offline streamed-native diagnostic guards; no profiler or device claim.""" + +import json +import unittest +from contextlib import nullcontext +from pathlib import Path +from tempfile import TemporaryDirectory +from unittest.mock import patch + +from lib import inference_client_noise as noise +from lib.inference_client import prompts, expected_body + +MODEL = "fixture@" + "a" * 40 + + +def stream(request): + n = request["max_tokens"] + shape = request["messages"][0]["content"].count("Record ") + chunks = [{"choices": [{"delta": {"role": "assistant"}}]}, + {"choices": [{"delta": {"content": "answer"}}]}, + {"choices": [], "usage": {"prompt_tokens": shape, "completion_tokens": n, + "prompt_tokens_details": {"cached_tokens": 0}}, + "timings": {"prompt_n": shape, "predicted_n": n, "prompt_ms": 20, "predicted_ms": 100}}, + {"choices": [{"delta": {}, "finish_reason": "length"}]}] + return "".join("data: " + json.dumps(chunk) + "\n\n" for chunk in chunks) + "data: [DONE]\n\n" + + +class NoiseTests(unittest.TestCase): + def test_raw_stream_retains_native_phase_and_complete_usage(self): + request = expected_body(MODEL, prompts(MODEL)[2]) + result = noise.parse(stream(request), request) + self.assertEqual(result["timings"]["predicted_n"], 128) + self.assertEqual(result["text"], "answer") + + def test_missing_done_cache_hits_truncation_and_missing_native_timing_fail(self): + request = expected_body(MODEL, prompts(MODEL)[2]) + raw = stream(request) + for bad in (raw.replace("data: [DONE]\n\n", ""), raw.replace('"cached_tokens": 0', '"cached_tokens": 1'), + raw.replace('"completion_tokens": 128', '"completion_tokens": 127'), + raw.replace('"timings": {', '"missing_timings": {')): + with self.assertRaises(ValueError): + noise.parse(bad, request) + + def test_own_registration_is_main_only_and_never_a_final_verdict(self): + registration = noise.registration() + arms = noise.schedule(registration["baseline_sha"], registration["configuration"]) + self.assertEqual(len(arms), 2) + self.assertTrue(all(a["source_sha"] == registration["baseline_sha"] for a in arms)) + with self.assertRaises(ValueError): + noise.schedule("b" * 40, registration["configuration"]) + + def test_instrumented_capture_retains_all_original_client_request_bodies_and_raw_streams(self): + def curl(args, timeout): + request = json.loads(args[args.index("--data-binary") + 1]) + return stream(request) + with TemporaryDirectory() as temporary, patch.object(noise, "curl", side_effect=curl), \ + patch.object(noise, "host_record", return_value={"monotonic_ns": 1}), \ + patch.object(noise, "diagnostics", return_value=nullcontext()): + output = Path(temporary) + noise.measure(MODEL, output) + result = json.loads((output / "client-noise.json").read_text()) + self.assertEqual(result["status"], "diagnostic-complete") + self.assertTrue(result["diagnostic_only"]) + self.assertEqual(len(result["samples"]), 27) + self.assertTrue(all("raw_sse" in s for s in result["samples"])) + self.assertTrue(all(s["completed_ns"] >= s["started_ns"] for s in result["samples"])) + self.assertEqual([s["request"] for s in result["samples"]], + [expected_body(MODEL, p) for p in prompts(MODEL)]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/inference_client_power.py b/scripts/tests/inference_client_power.py new file mode 100644 index 00000000..2bf2abb2 --- /dev/null +++ b/scripts/tests/inference_client_power.py @@ -0,0 +1,57 @@ +"""Power-planning model guards; synthetic fixtures never establish qualification.""" + +import copy +import unittest + +from lib.inference_client_power import joint_power, plan, variance_miss_bound + + +def fixture(sd_scale=1): + endpoints = [{"shape": shape, "metric": metric, + "paired_log_ratios": [v * sd_scale for v in (-.001, .001, -.002, .002, -.001, .001, -.002, .002)]} + for shape in range(3) for metric in ("ttft_ms", "tpot_ms", "request_tok_s")] + evidence = {"source_sha": "b" * 40, "baseline_sha": "a" * 40, "configuration": "fixture", + "runs": [{"arm_duration_s": 60, "samples": {"samples": [{"e2e_ms": 10}] * 9}}] * 16} + proof = {"source_sha": evidence["source_sha"], "baseline_sha": evidence["baseline_sha"], + "configuration": "fixture", "independent_pairs": 8, + "all_raw_quality_identity_gates": "verified", "summary": {"endpoints": endpoints}} + return evidence, proof + + +class PowerTests(unittest.TestCase): + def test_variance_bound_accounts_for_all_nine_small_pilot_estimates(self): + self.assertAlmostEqual(variance_miss_bound(), .021022385195764715) + + def test_count_meets_all_registered_loss_and_noise_sensitivities(self): + evidence, proof = fixture() + result = plan(evidence, proof) + self.assertEqual(result["status"], "feasible") + self.assertEqual(result["pairs_per_phase"] % 2, 0) + self.assertGreaterEqual(min(s["modeled_joint_power_lower_bound"] for s in result["scenarios"]), .9) + endpoints = proof["summary"]["endpoints"] + if result["pairs_per_phase"] > 16: + self.assertLess(joint_power(endpoints, result["pairs_per_phase"] - 2, .005, 2), .9) + + def test_noisy_data_reports_budget_shortfall_instead_of_weakening_gate(self): + evidence, proof = fixture(5) + result = plan(evidence, proof) + self.assertEqual(result["status"], "lease_shortfall") + self.assertGreater(result["estimated_duration_s"], 14400) + self.assertGreaterEqual(min(s["modeled_joint_power_lower_bound"] for s in result["scenarios"]), .9) + + def test_power_decreases_with_candidate_loss_and_increased_ab_variance(self): + _, proof = fixture() + endpoints = proof["summary"]["endpoints"] + self.assertGreater(joint_power(endpoints, 40, 0, 1), joint_power(endpoints, 40, .005, 2)) + + def test_missing_independent_audit_or_pairs_cannot_size_a_final_run(self): + evidence, proof = fixture() + for key, value in (("independent_pairs", 7), ("all_raw_quality_identity_gates", "pending")): + altered = copy.deepcopy(proof) + altered[key] = value + with self.assertRaisesRegex(ValueError, "independently audited"): + plan(evidence, altered) + + +if __name__ == "__main__": + unittest.main() From f706d3f753fc3865a6480ea98416324239abf139 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sun, 29 Nov 2026 02:42:31 +1100 Subject: [PATCH 12/22] Reject invalid client power and executable provenance --- scripts/lib/inference_client_final.py | 24 +++++++++++++++++++++- scripts/tests/inference_client_decision.py | 17 +++++++++++++-- 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/scripts/lib/inference_client_final.py b/scripts/lib/inference_client_final.py index 351b0ae6..43125e75 100644 --- a/scripts/lib/inference_client_final.py +++ b/scripts/lib/inference_client_final.py @@ -2,6 +2,7 @@ import math import random +import re from statistics import fmean from .ci_artifacts import read_json, write_json @@ -33,9 +34,13 @@ def schedule(baseline, candidate, configuration, design=None): scenarios = {(s["candidate_loss"], s["ab_sd_factor"]): s["modeled_joint_power_lower_bound"] for s in plan["scenarios"]} if (plan["status"] != "feasible" or plan["pairs_per_phase"] != pairs + or type(plan["estimated_duration_s"]) not in (int, float) + or not math.isfinite(plan["estimated_duration_s"]) or not 0 < plan["estimated_duration_s"] <= plan["maximum_duration_s"] <= 14400 + or len(plan["scenarios"]) != 6 or set(scenarios) != {(loss, factor) for loss in (0, .005) for factor in (1, 1.5, 2)} - or min(scenarios.values()) < .9): + or any(type(p) not in (int, float) or not math.isfinite(p) or not .9 <= p <= 1 + for p in scenarios.values())): raise ValueError("final client power plan is insufficient or exceeds the lease") rng = random.Random(design["seed"]) phase_orders = sorted([(rng.random(), i % 2) for i in range(pairs)]) @@ -91,6 +96,23 @@ def verify(model, output): def summarize(evidence, design=None, resamples=None): design = registration() if design is None else design + roles = {"leader", "worker"} if evidence["configuration"].endswith("-split") else {"leader"} + placements, builds = evidence["placements"], evidence["builds"] + if (evidence["schema_version"] != 1 or evidence["protocol"] != design["protocol"] + or any(not re.fullmatch(r"[0-9a-f]{40}", evidence[k]) for k in ("source_sha", "baseline_sha")) + or len(placements) != len(roles) or {p["role"] for p in placements} != roles + or len({p["node"] for p in placements}) != len(roles) + or len(builds) != len(roles) or {b["role"] for b in builds} != roles): + raise ValueError("final client identity, placement or role provenance is incomplete") + policies = [] + for build in builds: + for name, sha in (("main", evidence["baseline_sha"]), ("candidate", evidence["source_sha"])): + identity = build[name] + if identity["stack_commit"] != sha or not re.fullmatch(r"[0-9a-f]{64}", identity["cli_sha256"]): + raise ValueError("final client executable source identity mismatch") + policies.append(identity["build_inputs"]["policy"]) + if any(p != policies[0] or p["cargo_profile"] != "release" or p["native_link"] != "static" for p in policies): + raise ValueError("final client builds require identical release/static policies on every role") expected = schedule(evidence["baseline_sha"], evidence["source_sha"], evidence["configuration"], design) runs = evidence["runs"] if (evidence["registration"] != design or len(runs) != len(expected) diff --git a/scripts/tests/inference_client_decision.py b/scripts/tests/inference_client_decision.py index 9101d289..b77c6634 100644 --- a/scripts/tests/inference_client_decision.py +++ b/scripts/tests/inference_client_decision.py @@ -98,13 +98,22 @@ def test_final_acquisition_refuses_unregistered_count_and_balances_every_pair(se design["configurations"][config]["planning_evidence"]["status"] = "lease_shortfall" with self.assertRaisesRegex(ValueError, "exceeds the lease"): final.schedule(design["baseline_sha"], "b" * 40, config, design) + design = registered_design() + design["configurations"][config]["planning_evidence"]["scenarios"][0]["modeled_joint_power_lower_bound"] = float("nan") + with self.assertRaisesRegex(ValueError, "power plan"): + final.schedule(design["baseline_sha"], "b" * 40, config, design) def test_final_summary_reports_phase_losses_without_changing_client_scope(self): design = registered_design() config = "qwen35-4b-standalone" baseline, candidate = design["baseline_sha"], "b" * 40 - evidence = {"source_sha": candidate, "baseline_sha": baseline, "configuration": config, - "placements": [{"node": "offline fixture"}], "registration": design, "runs": []} + policy = {"cargo_profile": "release", "native_link": "static"} + evidence = {"schema_version": 1, "protocol": design["protocol"], + "source_sha": candidate, "baseline_sha": baseline, "configuration": config, + "placements": [{"role": "leader", "node": "offline fixture"}], + "builds": [{"role": "leader", **{name: {"stack_commit": sha, "cli_sha256": "c" * 64, + "build_inputs": {"policy": policy}} for name, sha in (("main", baseline), ("candidate", candidate))}}], + "registration": design, "runs": []} for arm in final.schedule(baseline, candidate, config, design): phase_slow = 1.1 if arm["experiment"] == "client-ab" and arm["arm"] == "b" else 1 evidence["runs"].append({**arm, "placements": evidence["placements"], "quality": "passed", @@ -126,6 +135,10 @@ def test_final_summary_reports_phase_losses_without_changing_client_scope(self): result = final.summarize(changed, design, resamples=1000) self.assertEqual(result["claim_verdict"], "UNPROVEN") self.assertTrue(any(r["comparison"] == "incompatible_event_framing" for r in result["client_endpoints"])) + changed = copy.deepcopy(evidence) + changed["builds"][0]["main"]["stack_commit"] = candidate + with self.assertRaisesRegex(ValueError, "source identity"): + final.summarize(changed, design, resamples=1000) if __name__ == "__main__": From e43b9572794d9c44762f5bd6d2ace09e9717786d Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sun, 29 Nov 2026 03:10:30 +1100 Subject: [PATCH 13/22] Probe scheduler affinity with a verified within-server crossover --- .gi/templates.yaml | 4 + ci/README.md | 15 ++++ ci/automation.just | 3 + ci/inference-client-affinity.json | 16 ++++ scripts/inference-execute.py | 6 +- scripts/inference-paired.py | 24 ++++-- scripts/lib/inference_client_affinity.py | 85 +++++++++++++++++++ scripts/lib/inference_client_noise.py | 18 +++- scripts/lib/inference_stream_capture.py | 52 ++++++++++++ scripts/lib/inference_thread_affinity.py | 99 ++++++++++++++++++++++ scripts/tests/inference_client_affinity.py | 54 ++++++++++++ scripts/tests/inference_stream_capture.py | 48 +++++++++++ scripts/tests/inference_thread_affinity.py | 71 ++++++++++++++++ 13 files changed, 483 insertions(+), 12 deletions(-) create mode 100644 ci/inference-client-affinity.json create mode 100644 scripts/lib/inference_client_affinity.py create mode 100644 scripts/lib/inference_stream_capture.py create mode 100644 scripts/lib/inference_thread_affinity.py create mode 100644 scripts/tests/inference_client_affinity.py create mode 100644 scripts/tests/inference_stream_capture.py create mode 100644 scripts/tests/inference_thread_affinity.py diff --git a/.gi/templates.yaml b/.gi/templates.yaml index 9a3e0c31..f953aab8 100644 --- a/.gi/templates.yaml +++ b/.gi/templates.yaml @@ -668,6 +668,10 @@ { "value": "client-noise", "label": "client-noise" + }, + { + "value": "client-affinity", + "label": "client-affinity" } ], "default": "paired" diff --git a/ci/README.md b/ci/README.md index f70e778d..e4972925 100644 --- a/ci/README.md +++ b/ci/README.md @@ -389,6 +389,21 @@ final timing path and cannot qualify performance or contribute final pairs. Its purpose is to distinguish native generation variability from delivery variability before selecting a change; correlations alone do not prove a cause. +`client-affinity`, registered in `ci/inference-client-affinity.json`, is a +two-server within-process crossover on the original standalone host. Its three +existing workload repetitions use stock/pinned/stock in one server and +pinned/stock/pinned in the other, switching before normal warmups. Two additional +largest-shape warmups identify the owned scheduler TID by interval CPU-time +deltas, process identity and start time; a truncated thread name or lowest TID +does not establish identity. Only that thread's CPU mask changes. Other masks +and the native iteration worker-pool count must remain unchanged, inherited +pinning invalidates the diagnostic, and original affinity is restored on exit. +Per-request scheduler runtime, run-queue wait and migration deltas accompany +raw SSE, native timings and diagnostic receive-event timestamps. This is a +placement experiment, not final client qualification; stock staying on CPU9 +produces no useful placement contrast, and two startups cannot establish lower +between-start variance. No persistent machine or GPU policy changes occur. + Scheduled PR-profile smoke rows run the same design with main in both arms; their paired receipts retain the noise check in Actions artifacts. The twelve AgentX workloads and their saved historical baseline policy are separate. diff --git a/ci/automation.just b/ci/automation.just index 08e0b1bd..41999eea 100644 --- a/ci/automation.just +++ b/ci/automation.just @@ -22,6 +22,9 @@ inference-contracts: @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client_decision.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client_power.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client_noise.py + @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_thread_affinity.py + @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_stream_capture.py + @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client_affinity.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_pairs.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_paired_execution.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/jy_read_recovery.py diff --git a/ci/inference-client-affinity.json b/ci/inference-client-affinity.json new file mode 100644 index 00000000..8aad30b8 --- /dev/null +++ b/ci/inference-client-affinity.json @@ -0,0 +1,16 @@ +{ + "protocol": "DGX Spark scheduler affinity crossover diagnostic v1", + "baseline_sha": "cc2a27435e798649a9cb938d600d39722e4a2263", + "configuration": "qwen35-4b-standalone", + "node": "spark-000586", + "hostname": "spark-a29c", + "cpu": 9, + "arms": [["stock", "pinned", "stock"], ["pinned", "stock", "pinned"]], + "purpose": "Test whether changing only the hot scheduler thread placement changes native decode and event spacing within the same warmed server; no performance qualification", + "identification": "Unique dominant skippy-iteration thread by server PID, start ticks and CPU-time deltas in each of two extra64-token largest-shape warmups; reject ambiguity; never select by name or TID order alone", + "workload": "Original27 client-pilot request bodies once per server, in original cycled order; switch before each repetition's normal warmups", + "intervention": "Only identified TID mask changes to CPU9; original mask restored for stock blocks and on every exit. Preserve other masks; detect new threads inheriting pinned mask and invalidate capture", + "records": ["all raw SSE and native terminal timings", "diagnostic content-event receive timestamps", "per-request scheduler runtime/runqueue/migration deltas", "thread IDs/start times/masks/counts", "GPU/CPU/cgroup telemetry"], + "interpretation": "Repeatable changes following both reversals implicate this placement policy on this host, not a specific CPU mechanism. No stock placement contrast is uninformative. Two servers do not establish lower between-start variance; no samples enter final qualification.", + "budget": {"approved": true, "max_usd": 0, "max_duration_s": 14400, "controller_duration_s": 3600, "no_preemption": true} +} diff --git a/scripts/inference-execute.py b/scripts/inference-execute.py index f134e0f1..053a518a 100644 --- a/scripts/inference-execute.py +++ b/scripts/inference-execute.py @@ -98,7 +98,7 @@ def server_command(worker, phase_profile=False): return args -def execute(profile, key, mode, repetitions=1, probe=None, phase_profile=False): +def execute(profile, key, mode, repetitions=1, probe=None, phase_profile=False, server_probe=None): sha, gpu = authority() result = plan(profile, sha) if not any(row["id"] == f"{key}-{mode}" for row in result["rows"]): @@ -151,7 +151,9 @@ def execute(profile, key, mode, repetitions=1, probe=None, phase_profile=False): score(coordinate, output, profile) if profile == "pr": streaming(coordinate, output) - if probe is not None: + if server_probe is not None: + server_probe(coordinate, output, server.pid) + elif probe is not None: probe(coordinate, output) else: for repetition in range(repetitions): diff --git a/scripts/inference-paired.py b/scripts/inference-paired.py index a19e1dde..13beb00e 100644 --- a/scripts/inference-paired.py +++ b/scripts/inference-paired.py @@ -13,6 +13,7 @@ import tempfile import time from contextlib import contextmanager, nullcontext +from functools import partial from pathlib import Path from runpy import run_path @@ -27,6 +28,7 @@ from lib import inference_client_final as client_final from lib.inference_client_report import render as client_report from lib import inference_client_noise as client_noise +from lib import inference_client_affinity as client_affinity ROOT = Path(__file__).resolve().parents[1] EXECUTE = run_path(str(ROOT / "scripts/inference-execute.py"))["execute"] @@ -122,6 +124,8 @@ def run_arm(design, main, baseline, key, mode, output): EXECUTE("pr", key, mode, probe=client_final.measure) elif design["experiment"] == "client-noise": EXECUTE("pr", key, mode, probe=client_noise.measure) + elif design["experiment"] == "client-affinity": + EXECUTE("pr", key, mode, server_probe=partial(client_affinity.measure, arm=design["round"])) else: EXECUTE("pr", key, mode, REPETITIONS) finally: @@ -153,6 +157,9 @@ def ready(): def execute(key, mode, baseline, experiment="paired"): + affinity = experiment == "client-affinity" + if affinity: + client_affinity.schedule(baseline, f"{key}-{mode}") streamed_noise = experiment == "client-noise" if streamed_noise: client_noise.schedule(baseline, f"{key}-{mode}") @@ -187,7 +194,8 @@ def execute(key, mode, baseline, experiment="paired"): with baseline_tree(baseline) as main: identities = prepare(main, baseline, candidate, output) local = host(role, node) - designs = (client_noise.schedule(baseline, f"{key}-{mode}") if streamed_noise else + designs = (client_affinity.schedule(baseline, f"{key}-{mode}") if affinity else + client_noise.schedule(baseline, f"{key}-{mode}") if streamed_noise else client_final.schedule(baseline, candidate, f"{key}-{mode}") if final else client_pilot.schedule(baseline, f"{key}-{mode}") if sizing else noise.schedule(baseline, kind) if diagnostic else schedule(baseline, candidate)) @@ -225,6 +233,10 @@ def execute(key, mode, baseline, experiment="paired"): registered = client_noise.registration() evidence.update(protocol=registered["protocol"], registration=registered, rounds=registered["arms"], diagnostic_only=True) + if affinity: + registered = client_affinity.registration() + evidence.update(protocol=registered["protocol"], registration=registered, + rounds=len(registered["arms"]), diagnostic_only=True) try: for index, design in enumerate(designs): if coordinator: @@ -237,7 +249,7 @@ def execute(key, mode, baseline, experiment="paired"): coordinate = f'{coordinate["repo"]}@{coordinate["revision"]}' evidence["runs"].append({**design, "placements": placements, "quality": "passed", "arm_duration_s": time.monotonic() - started, - "samples": (read_json(directory / "client-noise.json") if streamed_noise else + "samples": (read_json(directory / "client-noise.json") if streamed_noise or affinity else client_final.verify(coordinate, directory) if final else client.verify(directory, coordinate) if sizing else read_json(directory / f"noise-{kind}.json") if diagnostic @@ -248,7 +260,7 @@ def execute(key, mode, baseline, experiment="paired"): "provenance.json", "split-admissions.json", "split-peer.json"): if (directory / name).is_file(): shutil.copyfile(directory / name, output / name) - if streamed_noise: + if streamed_noise or affinity: evidence["status"] = "diagnostic-complete" elif final: evidence["summary"] = client_final.summarize(evidence) @@ -260,7 +272,7 @@ def execute(key, mode, baseline, experiment="paired"): else: evidence["status"] = "diagnostic-complete" finally: - write_json(output / ("client-noise.json" if streamed_noise else + write_json(output / ("client-affinity.json" if affinity else "client-noise.json" if streamed_noise else "client-final.json" if final else "client-pilot.json" if sizing else f"noise-{kind}.json" if diagnostic else "paired-probe.json"), evidence) @@ -270,10 +282,10 @@ def execute(key, mode, baseline, experiment="paired"): parser.add_argument("model") parser.add_argument("mode", choices=("standalone", "split")) parser.add_argument("baseline") - parser.add_argument("experiment", nargs="?", choices=("paired", "noise-pilot", "noise-profile", "client-pilot", "client-final", "client-noise"), default="paired") + parser.add_argument("experiment", nargs="?", choices=("paired", "noise-pilot", "noise-profile", "client-pilot", "client-final", "client-noise", "client-affinity"), default="paired") args = parser.parse_args() try: - with cancel_on_signal(), time_budget(3600 if args.experiment == "client-noise" else 14400): + with cancel_on_signal(), time_budget(3600 if args.experiment in {"client-noise", "client-affinity"} else 14400): execute(args.model, args.mode, args.baseline, args.experiment) except (OSError, ValueError, KeyError, RuntimeError, subprocess.SubprocessError, KeyboardInterrupt) as error: sys.exit(str(error)) diff --git a/scripts/lib/inference_client_affinity.py b/scripts/lib/inference_client_affinity.py new file mode 100644 index 00000000..d86ddf3f --- /dev/null +++ b/scripts/lib/inference_client_affinity.py @@ -0,0 +1,85 @@ +"""Main-only within-server affinity crossover, with verified restoration.""" + +import platform + +from .ci_artifacts import read_json, write_json +from .inference_client import ROOT, expected_body, prompts +from .inference_client_noise import measure as noise_measure, parse +from .inference_stream_capture import capture_stream +from .inference_thread_affinity import Affinity, identify, snapshot + +REGISTRATION = ROOT / "ci/inference-client-affinity.json" + + +def registration(): + return read_json(REGISTRATION) + + +def schedule(baseline, configuration): + design = registration() + if baseline != design["baseline_sha"] or configuration != design["configuration"]: + raise ValueError("affinity crossover requires its registered main/configuration") + return [{"experiment": "client-affinity", "round": arm, "arm": "a", "source_sha": baseline} + for arm in range(len(design["arms"]))] + + +class Observer: + def __init__(self, affinity, conditions, proof): + self.affinity, self.conditions, self.proof = affinity, conditions, proof + self.repetition = None + self.previous = None + + def before(self, prompt): + repetition = int(prompt["id"].split("-")[0][1:]) + if repetition != self.repetition: + transition = self.affinity.switch(self.conditions[repetition]) + self.proof["transitions"].append({"repetition": repetition, **transition}) + self.repetition = repetition + current = self.affinity.checked() + self.previous = current[self.affinity.tid] + return {"condition": self.affinity.condition, "thread_count": len(current), "target": self.previous} + + def after(self): + current = self.affinity.checked() + target = current[self.affinity.tid] + delta = {key: target[key] - self.previous[key] if target[key] is not None and self.previous[key] is not None else None + for key in ("cpu_ticks", "runtime_ns", "runqueue_ns", "timeslices", "migrations")} + return {"condition": self.affinity.condition, "thread_count": len(current), "target": target, "delta": delta} + + +def measure(model, output, server_pid, arm): + design = registration() + if platform.node() != design["hostname"]: + raise ValueError("affinity crossover requires the original pilot host") + proof = {"registration": design, "server_pid": server_pid, "arm": arm, + "identification": [], "transitions": [], "restoration": "not modified"} + windows, affinity = [], None + try: + for index in range(2): + warmup = next(p for p in prompts(model) if p["bucket"] == "warm-2") + request = expected_body(model, warmup) + text = request["messages"][0]["content"].split("\n", 1)[1] + request["messages"][0]["content"] = f"I{900 + index}\n{text}" + before = snapshot(server_pid) + response = capture_stream(request) + parsed = parse(response["raw_sse"], request) + after = snapshot(server_pid) + windows.append((before, after)) + proof["identification"].append({"request": request, **response, "parsed": parsed, + "before": before, "after": after}) + tid = identify(windows) + affinity = Affinity(server_pid, tid, design["cpu"]) + proof.update(target_tid=tid, target_start_ticks=affinity.target["start_ticks"], original_threads=affinity.initial) + observer = Observer(affinity, design["arms"][arm], proof) + noise_measure(model, output, registered=design, observer=observer, sender=capture_stream) + proof["status"] = "diagnostic-complete" + except BaseException as error: + proof.update(status="failed", error=str(error)) + raise + finally: + try: + if affinity is not None: + proof["restored_threads"] = affinity.restore() + proof["restoration"] = "verified" + finally: + write_json(output / "affinity-proof.json", proof) diff --git a/scripts/lib/inference_client_noise.py b/scripts/lib/inference_client_noise.py index 771ed329..05fa0486 100644 --- a/scripts/lib/inference_client_noise.py +++ b/scripts/lib/inference_client_noise.py @@ -86,10 +86,10 @@ def optional(path): "cgroup_ancestors": groups, "process_cgroup": group} -def measure(model, output): +def measure(model, output, *, registered=None, observer=None, sender=None): telemetry = output / "telemetry" telemetry.mkdir() - evidence = {"registration": registration(), "diagnostic_only": True, "status": "incomplete", "samples": []} + evidence = {"registration": registered or registration(), "diagnostic_only": True, "status": "incomplete", "samples": []} done, errors = threading.Event(), [] def sample(): try: @@ -108,12 +108,22 @@ def sample(): try: for prompt in prompts(model): request = expected_body(model, prompt) + before = observer.before(prompt) if observer is not None else None row = {"id": prompt["id"], "bucket": prompt["bucket"], "request": request, "started_ns": time.perf_counter_ns(), "started_wall_ns": time.time_ns()} + if before is not None: + row["affinity_before"] = before evidence["samples"].append(row) - row["raw_sse"] = curl(["--no-buffer", "-H", "Content-Type: application/json", "--data-binary", - json.dumps(request), ENDPOINT + "/v1/chat/completions"], 180) + if sender is None: + row["raw_sse"] = curl(["--no-buffer", "-H", "Content-Type: application/json", "--data-binary", + json.dumps(request), ENDPOINT + "/v1/chat/completions"], 180) + else: + row.update(sender(request)) row["completed_ns"] = time.perf_counter_ns() + if row.get("event_parse_errors"): + raise ValueError("diagnostic content-event capture could not parse the stream") + if observer is not None: + row["affinity_after"] = observer.after() row["parsed"] = parse(row["raw_sse"], request) shape = prompt["bucket"].split("-")[-1] count = row["parsed"]["usage"]["prompt_tokens"] diff --git a/scripts/lib/inference_stream_capture.py b/scripts/lib/inference_stream_capture.py new file mode 100644 index 00000000..f554bccf --- /dev/null +++ b/scripts/lib/inference_stream_capture.py @@ -0,0 +1,52 @@ +"""Timestamp diagnostic curl content events; never the final benchmark client.""" + +import json +import os +import selectors +import subprocess +import time + +from .ci_process import DEADLINE, start, stop +from .inference_checks import ENDPOINT + + +def capture_stream(request): + args = ["curl", "--fail", "--silent", "--show-error", "--noproxy", "*", "--no-buffer", + "--max-time", "180", "-H", "Content-Type: application/json", "--data-binary", + json.dumps(request), ENDPOINT + "/v1/chat/completions"] + child = start(args, stdout=subprocess.PIPE) + raw, pending, events, errors = bytearray(), b"", [], [] + deadline = min(time.monotonic() + 182, DEADLINE.get() or float("inf")) + try: + with selectors.DefaultSelector() as selector: + selector.register(child.stdout, selectors.EVENT_READ) + while True: + if not selector.select(max(0, deadline - time.monotonic())): + raise subprocess.TimeoutExpired(args, 182) + chunk = os.read(child.stdout.fileno(), 65536) + stamp = time.perf_counter_ns() + if not chunk: + break + raw.extend(chunk) + if len(raw) > 8 * 1024 * 1024: + raise ValueError("diagnostic stream exceeds bounded capture") + pending += chunk + lines = pending.split(b"\n") + pending = lines.pop() + for line in lines: + if not line.startswith(b"data: ") or line.strip() == b"data: [DONE]": + continue + try: + item = json.loads(line[6:]) + except ValueError as error: + errors.append(str(error)) + continue + if any(isinstance(c.get("delta", {}).get("content"), str) + and c["delta"]["content"] for c in item.get("choices", [])): + events.append(stamp) + if child.wait(timeout=max(0, deadline - time.monotonic())): + raise subprocess.CalledProcessError(child.returncode, args) + return {"raw_sse": raw.decode("utf-8"), "content_event_ns": events, "event_parse_errors": errors} + finally: + stop(child) + child.stdout.close() diff --git a/scripts/lib/inference_thread_affinity.py b/scripts/lib/inference_thread_affinity.py new file mode 100644 index 00000000..15264d84 --- /dev/null +++ b/scripts/lib/inference_thread_affinity.py @@ -0,0 +1,99 @@ +"""Identify and temporarily bind only the owned server's hot scheduler thread.""" + +import os +from pathlib import Path + + +def snapshot(pid): + result = {} + for directory in (Path("/proc") / str(pid) / "task").iterdir(): + try: + fields = (directory / "stat").read_text().rsplit(")", 1)[1].split() + sched = (directory / "schedstat").read_text().split() + migration = next((line.partition(":")[2].strip() for line in + (directory / "sched").read_text().splitlines() + if line.strip().startswith("se.nr_migrations")), None) + tid = int(directory.name) + result[tid] = {"comm": (directory / "comm").read_text().strip(), + "cpu_ticks": int(fields[11]) + int(fields[12]), + "start_ticks": int(fields[19]), "last_cpu": int(fields[36]), + "runtime_ns": int(sched[0]), "runqueue_ns": int(sched[1]), + "timeslices": int(sched[2]), "migrations": int(migration) if migration else None, + "affinity": sorted(os.sched_getaffinity(tid))} + except FileNotFoundError: + continue # A non-target helper may exit while procfs is read. + if pid not in result: + raise ValueError("owned server process disappeared during affinity diagnostic") + return result + + +def identify(windows): + winners = [] + for before, after in windows: + candidates = [] + for tid, row in after.items(): + old = before.get(tid) + if (old and row["comm"] == "skippy-iteratio" and row["start_ticks"] == old["start_ticks"]): + candidates.append((row["cpu_ticks"] - old["cpu_ticks"], tid)) + candidates.sort(reverse=True) + if (not candidates or candidates[0][0] < max(1, os.sysconf("SC_CLK_TCK") // 20) + or len(candidates) > 1 and candidates[0][0] <= 2 * candidates[1][0]): + raise ValueError("warmup CPU deltas do not uniquely identify the scheduler") + winners.append(candidates[0][1]) + if len(winners) != 2 or len(set(winners)) != 1: + raise ValueError("scheduler identity differs across the two identification warmups") + return winners[0] + + +class Affinity: + def __init__(self, pid, tid, cpu): + self.pid, self.tid, self.cpu = pid, tid, cpu + self.initial = snapshot(pid) + self.target = self.initial[tid] + self.original = set(self.target["affinity"]) + if cpu not in self.original or len(self.original) <= 1: + raise ValueError("diagnostic needs CPU9 available and a genuine stock affinity contrast") + self.condition = "stock" + + def checked(self): + current = snapshot(self.pid) + target = current.get(self.tid) + if not target or target["start_ticks"] != self.target["start_ticks"]: + raise ValueError("scheduler TID disappeared or was reused") + for tid, row in current.items(): + if tid == self.tid: + expected = self.original if self.condition == "stock" else {self.cpu} + elif tid in self.initial: + expected = set(self.initial[tid]["affinity"]) + else: + expected = self.original + if set(row["affinity"]) != expected: + raise ValueError("another thread inherited or changed affinity; diagnostic confounded") + if sum(r["comm"] == "skippy-iteratio" for r in current.values()) != sum( + r["comm"] == "skippy-iteratio" for r in self.initial.values()): + raise ValueError("native iteration worker-pool count changed during affinity diagnostic") + return current + + def switch(self, condition): + if condition not in {"stock", "pinned"}: + raise ValueError("unknown affinity diagnostic condition") + before = self.checked() + mask = self.original if condition == "stock" else {self.cpu} + os.sched_setaffinity(self.tid, mask) + self.condition = condition + after = self.checked() + return {"condition": condition, "before": before, "after": after} + + def restore(self): + current = snapshot(self.pid) + target = current.get(self.tid) + if not target or target["start_ticks"] != self.target["start_ticks"]: + raise ValueError("cannot verify scheduler identity for affinity restoration") + # Restore any newly created threads that inherited the experimental + # mask before failing the diagnostic; all belong to this owned server. + for tid, row in current.items(): + if tid not in self.initial and set(row["affinity"]) == {self.cpu}: + os.sched_setaffinity(tid, self.original) + os.sched_setaffinity(self.tid, self.original) + self.condition = "stock" + return self.checked() diff --git a/scripts/tests/inference_client_affinity.py b/scripts/tests/inference_client_affinity.py new file mode 100644 index 00000000..49ab67d4 --- /dev/null +++ b/scripts/tests/inference_client_affinity.py @@ -0,0 +1,54 @@ +"""Offline crossover orchestration and failure cleanup guards.""" + +import json +import unittest +from pathlib import Path +from tempfile import TemporaryDirectory +from unittest.mock import Mock, patch + +from lib import inference_client_affinity as crossover + + +def threads(ticks): + return {100: {"comm": "skippy", "cpu_ticks": 0, "start_ticks": 1}, + 110: {"comm": "skippy-iteratio", "cpu_ticks": ticks, "start_ticks": 2}} + + +def stream(request): + n = request["max_tokens"] + usage = {"prompt_tokens": 100, "completion_tokens": n, "prompt_tokens_details": {"cached_tokens": 0}} + timing = {"prompt_n": 100, "predicted_n": n, "prompt_ms": 10, "predicted_ms": 100} + rows = [{"choices": [{"delta": {"content": "answer"}, "finish_reason": "length"}]}, + {"choices": [], "usage": usage, "timings": timing}] + return {"raw_sse": "".join('data: '+json.dumps(r)+'\n\n' for r in rows)+"data: [DONE]\n\n"} + + +class CrossoverTests(unittest.TestCase): + def test_registered_two_server_three_repetition_crossover_is_balanced(self): + design = crossover.registration() + self.assertEqual(design["arms"], [["stock", "pinned", "stock"], ["pinned", "stock", "pinned"]]) + self.assertEqual(len(crossover.schedule(design["baseline_sha"], design["configuration"])), 2) + with self.assertRaises(ValueError): + crossover.schedule("b" * 40, design["configuration"]) + + def test_restores_owned_thread_even_when_measurement_fails(self): + design = crossover.registration() + affinity = Mock(tid=110, target={"start_ticks": 2}, initial=threads(160)) + affinity.restore.return_value = threads(160) + with TemporaryDirectory() as temporary, patch.object(crossover.platform, "node", return_value=design["hostname"]), \ + patch.object(crossover, "snapshot", side_effect=[threads(0), threads(80), threads(80), threads(160)]), \ + patch.object(crossover, "capture_stream", side_effect=stream), \ + patch.object(crossover, "Affinity", return_value=affinity), \ + patch.object(crossover, "noise_measure", side_effect=RuntimeError("injected")): + output = Path(temporary) + with self.assertRaisesRegex(RuntimeError, "injected"): + crossover.measure("fixture@"+'a'*40, output, 100, 0) + proof = json.loads((output / "affinity-proof.json").read_text()) + self.assertEqual(proof["status"], "failed") + self.assertEqual(proof["restoration"], "verified") + self.assertEqual(len(proof["identification"]), 2) + affinity.restore.assert_called_once() + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/inference_stream_capture.py b/scripts/tests/inference_stream_capture.py new file mode 100644 index 00000000..b7dde946 --- /dev/null +++ b/scripts/tests/inference_stream_capture.py @@ -0,0 +1,48 @@ +"""Real local curl capture with synthetic SSE; no model or hardware qualification.""" + +import json +import threading +import unittest +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from unittest.mock import patch + +from lib import inference_stream_capture as capture + + +class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_POST(self): + self.rfile.read(int(self.headers["Content-Length"])) + chunks = [{"choices": [{"delta": {"role": "assistant"}}]}, + {"choices": [{"delta": {"content": "first"}}]}, + {"choices": [{"delta": {"content": "last"}}]}] + body = ("".join("data: " + json.dumps(c) + "\n\n" for c in chunks) + "data: [DONE]\n\n").encode() + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + +class StreamTests(unittest.TestCase): + def test_coalesced_content_events_are_timestamped_and_role_events_excluded(self): + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + with patch.object(capture, "ENDPOINT", f"http://127.0.0.1:{server.server_port}"): + result = capture.capture_stream({"fixture": True}) + self.assertEqual(len(result["content_event_ns"]), 2) + self.assertEqual(result["content_event_ns"], sorted(result["content_event_ns"])) + self.assertIn("data: [DONE]", result["raw_sse"]) + self.assertEqual(result["event_parse_errors"], []) + finally: + server.shutdown() + server.server_close() + thread.join(timeout=5) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/inference_thread_affinity.py b/scripts/tests/inference_thread_affinity.py new file mode 100644 index 00000000..e48fcf0d --- /dev/null +++ b/scripts/tests/inference_thread_affinity.py @@ -0,0 +1,71 @@ +"""Offline scheduler selection/manipulation guards; no affinity changes on the host.""" + +import copy +import unittest +from unittest.mock import patch + +from lib import inference_thread_affinity as affinity + + +def threads(ticks=0): + return {100: {"comm": "skippy", "cpu_ticks": 0, "start_ticks": 1, "affinity": [0, 9]}, + 101: {"comm": "skippy-iteratio", "cpu_ticks": 0, "start_ticks": 2, "affinity": [0, 9]}, + 110: {"comm": "skippy-iteratio", "cpu_ticks": ticks, "start_ticks": 3, "affinity": [0, 9]}} + + +class AffinityTests(unittest.TestCase): + def test_identifies_by_two_dominant_cpu_deltas_not_lowest_matching_tid(self): + with patch.object(affinity.os, "sysconf", return_value=100): + self.assertEqual(affinity.identify([(threads(0), threads(80)), (threads(80), threads(160))]), 110) + bad = threads(160) + bad[101]["cpu_ticks"] = 70 + with self.assertRaisesRegex(ValueError, "uniquely"): + affinity.identify([(threads(0), threads(80)), (threads(80), bad)]) + + def test_reused_tid_or_inconsistent_winner_is_not_an_identity(self): + after = threads(80) + after[110]["start_ticks"] = 999 + with self.assertRaises(ValueError): + affinity.identify([(threads(), after), (threads(), threads(80))]) + + def test_changes_only_target_mask_and_restores_stock(self): + current = threads() + def change(tid, mask): + current[tid]["affinity"] = sorted(mask) + with patch.object(affinity, "snapshot", side_effect=lambda pid: copy.deepcopy(current)), \ + patch.object(affinity.os, "sched_setaffinity", side_effect=change, create=True) as setter: + controller = affinity.Affinity(100, 110, 9) + result = controller.switch("pinned") + self.assertEqual(result["after"][110]["affinity"], [9]) + self.assertEqual(result["after"][101]["affinity"], [0, 9]) + controller.switch("stock") + controller.restore() + self.assertEqual(current[110]["affinity"], [0, 9]) + self.assertTrue(all(call.args[0] == 110 for call in setter.call_args_list)) + + def test_new_threads_inheriting_mask_invalidate_then_are_restored(self): + current = threads() + def change(tid, mask): + current[tid]["affinity"] = sorted(mask) + with patch.object(affinity, "snapshot", side_effect=lambda pid: copy.deepcopy(current)), \ + patch.object(affinity.os, "sched_setaffinity", side_effect=change, create=True): + controller = affinity.Affinity(100, 110, 9) + controller.switch("pinned") + current[120] = {"comm": "helper", "cpu_ticks": 0, "start_ticks": 4, "affinity": [9]} + with self.assertRaisesRegex(ValueError, "confounded"): + controller.checked() + controller.restore() + self.assertEqual(current[120]["affinity"], [0, 9]) + self.assertEqual(current[110]["affinity"], [0, 9]) + + def test_cannot_manipulate_a_reused_target(self): + current = threads() + with patch.object(affinity, "snapshot", side_effect=lambda pid: copy.deepcopy(current)): + controller = affinity.Affinity(100, 110, 9) + current[110]["start_ticks"] = 999 + with self.assertRaisesRegex(ValueError, "reused"): + controller.checked() + + +if __name__ == "__main__": + unittest.main() From 10c23c244c1de14558bfedddf1d9608b9dafe70c Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sun, 29 Nov 2026 03:37:33 +1100 Subject: [PATCH 14/22] Preserve arm-order balance and reject unvalidated power admission --- ci/README.md | 60 ++++++++------- ci/inference-client-final.json | 16 ++-- scripts/inference-client-plan.py | 4 +- scripts/inference-paired.py | 2 + scripts/lib/inference_client_decision.py | 23 +++--- scripts/lib/inference_client_final.py | 34 ++++++++- scripts/lib/inference_client_power.py | 7 +- scripts/lib/inference_client_registration.py | 53 ++++++++++++++ scripts/tests/inference_client_decision.py | 77 ++++++++++++++++++-- scripts/tests/inference_client_power.py | 7 +- 10 files changed, 222 insertions(+), 61 deletions(-) create mode 100644 scripts/lib/inference_client_registration.py diff --git a/ci/README.md b/ci/README.md index e4972925..6a3e92bc 100644 --- a/ci/README.md +++ b/ci/README.md @@ -340,36 +340,44 @@ material effect and 1% maximum pointwise interval half-width remain unchanged. The opt-in `client-final` implementation has its own registration in `ci/inference-client-final.json`. It currently refuses acquisition: both counts and power plans are unset. A final registration must embed a feasible power plan -with a fixed even count of at least sixteen pairs per phase and at least 90% +with a fixed count of at least sixteen pairs per phase, in multiples of four, and at least 90% modeled joint power for parity and a 0.5% candidate loss, including every declared variance sensitivity. A plan exceeding the four-hour lease is rejected before starting server arms. Sizing data never contribute pairs to final qualification. -The prospective planner runs through -`just inference-client-plan `. -It uses conservative marginal failure bounds rather than fitting a covariance -matrix to eight pairs. Under independent Gaussian pilot log ratios, an upper -standard deviation of three times the observed value has a nine-endpoint union -miss bound of approximately 2.10% (the df=7 chi-square relation; see the -[NIST standard-deviation interval derivation](https://www.itl.nist.gov/div898/handbook/prc/section2/prc231.htm)). -The planning model includes that uncertainty, A/B standard deviations of 1, 1.5 -and 2 times the upper A/A estimate, and a conservative CI-width proxy of -`2.5*SD/sqrt(pairs)`. A/A remains centered at parity in both candidate scenarios. -The union bound allows arbitrary dependence among endpoints and between A/A -and A/B. It still assumes independent paired rounds and the stated normal model; -it does not prove power under heavy tails or serial drift. The planner retains -all pilot vectors, assumptions, scenario powers and duration allowances. - -Final time blocks contain one A/A pair and one A/B pair, with balanced phase -positions randomized from the recorded seed and alternating nominal arm order. -Pointwise paired percentile intervals use 100,000 resamples of fresh paired -server blocks, never nested requests. Each endpoint's complete A/A interval must -lie inside `[0.99, 1.01]`. Its A/B ratio-scale half-width must be at most 1%. -An A/B interval inside `[0.98, 1.02]` earns `within_tolerance`; otherwise the -native metric direction determines non-regression or a material change beyond -2%. Every client endpoint must pass. Invalid calibration or unresolved margins -cannot pass; a calibrated clear regression fails even if its interval is wide. -Matching content-event framing and constant prompt token shapes are required. +The earlier `just inference-client-plan` implementation is a retained +fixed-width heuristic only. Its `2.5*SD/sqrt(pairs)` width proxy does not simulate +the realized bootstrap interval and did not preserve the observed split arm-order +effect. Its scores are **inadmissible** for final registration; historical +estimates remain available without becoming power guarantees. Final acquisition +is hard-disabled until simulation validation of the actual registered interval +procedure is implemented. Counts remain unset. + +Power evidence must bind the configuration, baseline, pilot source, exact pilot +and independent-audit file digests, nine distinct endpoint cells, and the reserved +placement. Registration rejects mismatches before server arms start. The actual +allocation must match that registered placement. The controller/collector wiring +for the new receipt also remains pending, so a directly launched native success +cannot close the acceptance criterion. + +Final time blocks contain one A/A pair and one A/B pair. The count is a multiple +of four, and A/A-first versus A/B-first positions are balanced separately within +each AB/BA arm-order stratum. Pointwise percentile intervals use 100,000 paired +resamples **within those fixed equal strata**; order counts cannot fluctuate and +nested requests never become independent units. The equally weighted order +means cancel a constant position effect in both the point estimate and every +resample. This prospective correction does not relabel historical results and +still requires fresh validation. + +Each endpoint's complete A/A interval must lie inside `[0.99, 1.01]`. Its A/B +ratio-scale half-width must be at most 1%. An A/B interval strictly inside +`(0.98, 1.02)` earns `within_tolerance`; native metric direction determines strict +non-regression or a material change beyond 2%. Touching the adverse material +boundary does not establish non-regression. Every endpoint must pass. Invalid +calibration or unresolved margins cannot pass; a calibrated clear regression +fails even if imprecise. Framing compatibility is checked per shape, so a +mismatch invalidates that shape's TPOT while the aggregate still requires all +endpoints. Constant prompt token shapes and complete provenance remain required. After the measured client window, each final arm collects three separate non-streaming server-phase probe repetitions. All phase ratios and intervals, diff --git a/ci/inference-client-final.json b/ci/inference-client-final.json index fa22c087..b1676f2d 100644 --- a/ci/inference-client-final.json +++ b/ci/inference-client-final.json @@ -1,6 +1,6 @@ { - "protocol": "DGX Spark release client paired qualification v1", - "status": "awaiting sizing pilots; final acquisition prohibited", + "protocol": "DGX Spark release client paired qualification v2", + "status": "awaiting validated order-aware power and precision resolution; final acquisition prohibited", "baseline_sha": "cc2a27435e798649a9cb938d600d39722e4a2263", "configurations": { "qwen3-coder-30b-a3b-split": { @@ -31,12 +31,12 @@ 1.01 ], "estimator": "Geometric mean of within-pair candidate/main arm-summary ratios", - "interval": "Pointwise paired percentile bootstrap; resample fresh paired server blocks, never nested requests", + "interval": "Pointwise paired percentile bootstrap with fixed equal AB/BA strata; never vary order counts or resample nested requests", "resamples": 100000, "seed": 20261129, - "schedule": "Each time block contains an A/A pair and an A/B pair; randomize balanced phase positions using recorded seed; alternate a,b and b,a within each phase", + "schedule": "Alternate AB/BA pair order; randomize balanced A/A-first vs A/B-first positions separately within each order stratum; count must be a multiple of four", "framing_gate": "TPOT requires matching per-request content-event counts across each pair; both arms use terminal usage, no token IDs, and disclose one-token-first-content assumption", - "decision": "Every primary endpoint needs A/A equivalence in the placebo band, A/B required precision and within-tolerance/non-regression. A calibrated clear regression fails even if imprecise. Uncalibrated or unresolved endpoints cannot pass.", + "decision": "Strict A/B material-margin interiors for within-tolerance/non-regression; closed A/A placebo band; all primary endpoints must pass. Historical labels unchanged.", "phase_diagnostics": "After client timing only: three separate warmed non-streaming probe repetitions; retain and report all per-shape server-phase ratios and intervals, including losses; excluded from client gate", "invalid_run_policy": "Any missing role archive, identity, quality, cache/token, stream, framing or acquisition proof invalidates the affected claim. Preserve all data. No dropping samples, outcome-based extensions or threshold changes.", "power_requirement": "At least 90% modeled joint probability of all A/A calibration and A/B precision/non-regression gates under parity and a 0.5% candidate loss; conservative variance/dependence sensitivity before fixing count", @@ -59,11 +59,13 @@ 0, 0.005 ], - "ci_width_planning_factor": 2.5, + "historical_inadmissible_ci_width_proxy_factor": 2.5, "variance_assumption": "Independent Gaussian pilot log ratios; uncertainty union bound over nine endpoints", "endpoint_dependence": "Arbitrary; marginal failure probabilities added by union bound", "joint_power_target": 0.9, "lease_seconds": 14400, - "setup_build_upload_reserve_seconds": 4200 + "setup_build_upload_reserve_seconds": 4200, + "method": "order-stratified-bootstrap-simulation-v1", + "validation_status": "NOT IMPLEMENTED: fixed-width proxy scores are inadmissible; final acquisition hard-disabled" } } diff --git a/scripts/inference-client-plan.py b/scripts/inference-client-plan.py index ca76df16..ba031fe3 100644 --- a/scripts/inference-client-plan.py +++ b/scripts/inference-client-plan.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Size a final comparison from an independently audited client pilot.""" +"""Report a legacy fixed-width heuristic from an audited pilot; not admission evidence.""" import argparse import sys @@ -20,7 +20,7 @@ def main(): result.update(pilot_receipt_sha256=digest(evidence), independent_audit_sha256=digest(proof)) write_json(args.output, result) print(f'{result["configuration"]}: {result["status"]}; {result["pairs_per_phase"]} pairs per phase; ' - f'estimated {result["estimated_duration_s"] / 3600:.2f}h / 4h lease') + f'estimated {result["estimated_duration_s"] / 3600:.2f}h / 4h lease; INADMISSIBLE for final registration') if __name__ == "__main__": diff --git a/scripts/inference-paired.py b/scripts/inference-paired.py index 13beb00e..024c729c 100644 --- a/scripts/inference-paired.py +++ b/scripts/inference-paired.py @@ -191,6 +191,8 @@ def execute(key, mode, baseline, experiment="paired"): peers = json.loads(os.environ["JIANYANG_PEERS"]) if mode == "split" else [] role = os.environ.get("JIANYANG_ROLE", "leader") node = next((p["node"] for p in peers if p["role"] == role), platform.node()) + if final: + client_final.validate_placement([host(role, node)], client_final.registration()["configurations"][f"{key}-{mode}"]) with baseline_tree(baseline) as main: identities = prepare(main, baseline, candidate, output) local = host(role, node) diff --git a/scripts/lib/inference_client_decision.py b/scripts/lib/inference_client_decision.py index 8536b5e2..d72896e6 100644 --- a/scripts/lib/inference_client_decision.py +++ b/scripts/lib/inference_client_decision.py @@ -11,20 +11,25 @@ SEED = 20261129 -def paired_interval(log_ratios, resamples=RESAMPLES, seed=SEED): - """Percentile bootstrap over independent paired server blocks, never requests.""" - if (len(log_ratios) < 4 or type(resamples) is not int or resamples < 1000 +def paired_interval(log_ratios, resamples=RESAMPLES, seed=SEED, orders=None): + """Resample pairs within fixed AB/BA strata, preserving balanced arm order.""" + if (len(log_ratios) < 4 or len(log_ratios) % 2 or type(resamples) is not int or resamples < 1000 or any(type(v) not in (int, float) or not math.isfinite(v) for v in log_ratios)): raise ValueError("client interval requires finite independent paired blocks") + orders = orders if orders is not None else ["ab" if i % 2 == 0 else "ba" for i in range(len(log_ratios))] + if len(orders) != len(log_ratios) or set(orders) != {"ab", "ba"} or orders.count("ab") != orders.count("ba"): + raise ValueError("client interval requires equally represented AB and BA strata") + groups = [[v for v, order in zip(log_ratios, orders) if order == name] for name in ("ab", "ba")] rng = random.Random(seed) - size = len(log_ratios) - draws = sorted(fmean(log_ratios[min(int(rng.random() * size), size - 1)] for _ in range(size)) + size = len(groups[0]) + draws = sorted(fmean(v[min(int(rng.random() * size), size - 1)] for v in groups for _ in range(size)) for _ in range(resamples)) low = draws[int(0.025 * (resamples - 1))] high = draws[math.ceil(0.975 * (resamples - 1))] return {"ratio": math.exp(fmean(log_ratios)), "ci95": [math.exp(low), math.exp(high)], - "independent_pairs": size, "resamples": resamples, "seed": seed, - "estimator": "geometric mean of within-pair candidate/main ratios"} + "independent_pairs": len(log_ratios), "resamples": resamples, "seed": seed, + "orders": orders, "resampling": "fixed balanced AB/BA strata", + "estimator": "equally weighted AB/BA means of within-pair log ratios"} def decide(interval, calibration, direction): @@ -40,8 +45,8 @@ def decide(interval, calibration, direction): precise = half_width <= PRECISION or math.isclose(half_width, PRECISION, rel_tol=0, abs_tol=1e-12) regression = high < 1 - EFFECT if direction == "higher" else low > 1 + EFFECT improvement = low > 1 + EFFECT if direction == "higher" else high < 1 - EFFECT - within = 1 - EFFECT <= low <= high <= 1 + EFFECT - non_regression = low >= 1 - EFFECT if direction == "higher" else high <= 1 + EFFECT + within = 1 - EFFECT < low <= high < 1 + EFFECT + non_regression = low > 1 - EFFECT if direction == "higher" else high < 1 + EFFECT # A clear contradiction takes precedence over insufficient precision. An # invalid placebo never permits an A/B claim, including a regression claim. if not calibrated: diff --git a/scripts/lib/inference_client_final.py b/scripts/lib/inference_client_final.py index 43125e75..7a057b14 100644 --- a/scripts/lib/inference_client_final.py +++ b/scripts/lib/inference_client_final.py @@ -9,6 +9,7 @@ from .inference_client import ROOT, measure as client_measure, verify as client_verify from .inference_client_decision import EFFECT, PLACEBO, PRECISION, RESAMPLES, all_endpoints, decide, paired_interval from .inference_probe import measure as phase_measure, validate_evidence +from .inference_client_registration import validate_power_evidence, validate_placement REGISTRATION = ROOT / "ci/inference-client-final.json" @@ -28,9 +29,10 @@ def schedule(baseline, candidate, configuration, design=None): if any(design.get(k) != v for k, v in fixed.items()): raise ValueError("final client decision policy differs from registration") if (design["status"] != "registered" or baseline != design["baseline_sha"] - or type(pairs) is not int or pairs < 16 or pairs % 2 or not config.get("planning_evidence")): + or type(pairs) is not int or pairs < 16 or pairs % 4 or not config.get("planning_evidence")): raise ValueError("final client count and power plan must be registered before acquisition") plan = config["planning_evidence"] + validate_power_evidence(ROOT, configuration, baseline, config) scenarios = {(s["candidate_loss"], s["ab_sd_factor"]): s["modeled_joint_power_lower_bound"] for s in plan["scenarios"]} if (plan["status"] != "feasible" or plan["pairs_per_phase"] != pairs @@ -43,9 +45,13 @@ def schedule(baseline, candidate, configuration, design=None): for p in scenarios.values())): raise ValueError("final client power plan is insufficient or exceeds the lease") rng = random.Random(design["seed"]) - phase_orders = sorted([(rng.random(), i % 2) for i in range(pairs)]) + phase_orders = {} + for order in range(2): + shuffled = sorted((rng.random(), i % 2) for i in range(pairs // 2)) + phase_orders.update({2 * i + order: first for i, (_, first) in enumerate(shuffled)}) result = [] - for block, (_, phase_first) in enumerate(phase_orders): + for block in range(pairs): + phase_first = phase_orders[block] for phase in (("aa", "ab") if phase_first == 0 else ("ab", "aa")): for arm in (("a", "b") if block % 2 == 0 else ("b", "a")): result.append({"experiment": f"client-{phase}", "round": block, "arm": arm, @@ -94,6 +100,22 @@ def verify(model, output): return {"client": result, "framing": framing, "input_tokens": input_tokens, "phases": phase_results} +def validate_samples(samples, design): + summaries = samples["client"]["summaries"] + shapes = design["shapes"] + if (len(summaries) != len(shapes) or [s["shape"] for s in summaries] != shapes + or len(samples["phases"]) != len(shapes) or [s["shape"] for s in samples["phases"]] != shapes + or set(samples["input_tokens"]) != {f"shape-{s}" for s in shapes} + or any(type(n) is not int or n <= 0 for n in samples["input_tokens"].values()) + or set(samples["framing"]) != {f"r{r}-s{s}-measured" for r in range(3) for s in shapes} + or any(type(n) is not int or n < 2 for n in samples["framing"].values())): + raise ValueError("final client samples lack complete shape/token/framing evidence") + for summary in summaries: + if any(type(summary[m]) not in (int, float) or not math.isfinite(summary[m]) or summary[m] <= 0 + for m in design["primary_metrics"]): + raise ValueError("final client summary metric must be positive and finite") + + def summarize(evidence, design=None, resamples=None): design = registration() if design is None else design roles = {"leader", "worker"} if evidence["configuration"].endswith("-split") else {"leader"} @@ -114,6 +136,7 @@ def summarize(evidence, design=None, resamples=None): if any(p != policies[0] or p["cargo_profile"] != "release" or p["native_link"] != "static" for p in policies): raise ValueError("final client builds require identical release/static policies on every role") expected = schedule(evidence["baseline_sha"], evidence["source_sha"], evidence["configuration"], design) + validate_placement(placements, design["configurations"][evidence["configuration"]]) runs = evidence["runs"] if (evidence["registration"] != design or len(runs) != len(expected) or any(any(r.get(k) != v for k, v in d.items()) @@ -122,6 +145,8 @@ def summarize(evidence, design=None, resamples=None): for r, d in zip(runs, expected))): raise ValueError("final client acquisition is incomplete, reordered or changed allocation") count = design["configurations"][evidence["configuration"]]["pairs_per_phase"] + for run in runs: + validate_samples(run["samples"], design) by_pair = {(r["experiment"], r["round"], r["arm"]): r["samples"] for r in runs} if len({tuple(sorted(r["samples"]["input_tokens"].items())) for r in runs}) != 1: raise ValueError("client prompt token shapes changed between source arms") @@ -134,7 +159,8 @@ def summarize(evidence, design=None, resamples=None): logs = [] for block in range(count): a, b = (by_pair[f"client-{phase}", block, arm] for arm in ("a", "b")) - framing_ok &= a["framing"] == b["framing"] + relevant = lambda v: {k: n for k, n in v["framing"].items() if f"-s{shape}-" in k} + framing_ok &= relevant(a) == relevant(b) values = [v["client"]["summaries"][shape][metric] for v in (a, b)] logs.append(math.log(values[1] / values[0])) intervals[phase] = paired_interval(logs, resamples or design["resamples"], design["seed"]) diff --git a/scripts/lib/inference_client_power.py b/scripts/lib/inference_client_power.py index aa72c09c..b84995ce 100644 --- a/scripts/lib/inference_client_power.py +++ b/scripts/lib/inference_client_power.py @@ -1,4 +1,4 @@ -"""Conservative prospective normal-model sizing, separate from final inference.""" +"""Legacy fixed-width sizing heuristic; never admissible final power evidence.""" import math from statistics import NormalDist, stdev @@ -87,7 +87,8 @@ def powered(pairs): phase_seconds = max(2 * sum(s["e2e_ms"] for s in r["samples"]["samples"]) / 1000 for r in runs) reserve_seconds = 3600 + 600 # both source builds, setup, upload and cleanup duration = reserve_seconds + 4 * pairs * (arm_seconds + phase_seconds) - return {"status": "feasible" if duration <= 14400 else "lease_shortfall", + return {"status": "heuristic_only" if duration <= 14400 else "lease_shortfall", + "method": "fixed-width-proxy-v1", "eligible_for_registration": False, "configuration": evidence["configuration"], "pilot_source_sha": evidence["source_sha"], "baseline_sha": evidence["baseline_sha"], "pairs_per_phase": pairs, "total_fresh_arms": pairs * 4, "estimated_duration_s": duration, @@ -95,7 +96,7 @@ def powered(pairs): "arm_duration_upper_s": arm_seconds, "phase_diagnostic_allowance_s": phase_seconds, "setup_build_upload_reserve_s": reserve_seconds, "scenarios": [{"candidate_loss": loss, "ab_sd_factor": factor, - "modeled_joint_power_lower_bound": joint_power(endpoints, pairs, loss, factor)} + "fixed_width_proxy_score": joint_power(endpoints, pairs, loss, factor)} for loss, factor in scenarios], "pilot_variance_miss_union_bound": variance_miss_bound(), "sd_upper_factor": SD_FACTOR, "ci_width_planning_factor": CI_WIDTH_FACTOR, diff --git a/scripts/lib/inference_client_registration.py b/scripts/lib/inference_client_registration.py new file mode 100644 index 00000000..5001755f --- /dev/null +++ b/scripts/lib/inference_client_registration.py @@ -0,0 +1,53 @@ +"""Bind prospective final power evidence to its audited pilot and placement.""" + +import re + +from .ci_artifacts import digest, read_json + +POWER_METHOD = "order-stratified-bootstrap-simulation-v1" + + +def validate_simulation(plan): + # The former fixed-width score omitted random realized interval widths. + # Keep acquisition disabled until the actual registered interval procedure + # has an independently checked simulation validator. No config flag bypass. + raise ValueError("final bootstrap power simulation validation is not implemented; acquisition prohibited") + + +def validate_power_evidence(root, configuration, baseline, config): + plan = config["planning_evidence"] + if (plan.get("method") != POWER_METHOD or plan.get("eligible_for_registration") is not True + or plan.get("configuration") != configuration or plan.get("baseline_sha") != baseline): + raise ValueError("final power evidence has wrong method, configuration or baseline") + documents = {} + for name, field in (("pilot", "pilot_receipt_sha256"), ("audit", "independent_audit_sha256")): + ref = config["power_receipts"][name] + path = (root / ref["path"]).resolve() + if (not path.is_relative_to(root.resolve()) or not re.fullmatch(r"[0-9a-f]{64}", ref["sha256"]) + or ref["sha256"] != plan[field] or digest(path) != ref["sha256"]): + raise ValueError("final power pilot/audit receipt digest mismatch") + documents[name] = read_json(path) + pilot, audit = documents["pilot"], documents["audit"] + if (any(d.get("configuration") != configuration or d.get("baseline_sha") != baseline + or d.get("source_sha") != plan.get("pilot_source_sha") for d in documents.values()) + or audit.get("all_raw_quality_identity_gates") != "verified" + or audit.get("independent_pairs") != 8 + or pilot.get("placements") != config.get("placements") + or plan.get("placements") != config.get("placements") + or audit.get("reserved_nodes") != config.get("reserved_nodes") + or plan.get("reserved_nodes") != config.get("reserved_nodes")): + raise ValueError("final power pilot/audit identity or placement mismatch") + endpoints = audit["summary"]["endpoints"] + expected = {(s, m) for s in range(3) for m in ("ttft_ms", "tpot_ms", "request_tok_s")} + if (len(endpoints) != 9 or {(e["shape"], e["metric"]) for e in endpoints} != expected + or any(len(e["paired_log_ratios"]) != 8 for e in endpoints)): + raise ValueError("final power pilot lacks nine distinct complete endpoint cells") + validate_simulation(plan) + + +def validate_placement(placements, config): + expected = {p["role"]: p for p in config["placements"]} + for placement in placements: + planned = expected.get(placement["role"], {}) + if any(placement.get(k) != planned.get(k) for k in ("role", "node", "hostname")): + raise ValueError("final allocation differs from the registered power pilot placement") diff --git a/scripts/tests/inference_client_decision.py b/scripts/tests/inference_client_decision.py index b77c6634..0da5f887 100644 --- a/scripts/tests/inference_client_decision.py +++ b/scripts/tests/inference_client_decision.py @@ -3,10 +3,15 @@ import math import copy import unittest +from pathlib import Path +from tempfile import TemporaryDirectory +from unittest.mock import patch from lib.inference_client_decision import all_endpoints, decide, paired_interval from lib import inference_client_final as final from lib.inference_client_report import render +from lib.ci_artifacts import digest, write_json +from lib import inference_client_registration as registration def ci(low, high): @@ -16,15 +21,39 @@ def ci(low, high): def registered_design(): design = final.registration() design["status"] = "registered" - plan = {"status": "feasible", "pairs_per_phase": 16, "estimated_duration_s": 7200, + config = "qwen35-4b-standalone" + placements = [{"role": "leader", "node": "offline fixture", "hostname": "offline fixture"}] + nodes = {"leader": "offline fixture"} + pilot = {"source_sha": "c" * 40, "baseline_sha": design["baseline_sha"], + "configuration": config, "placements": placements} + audit = {**pilot, "reserved_nodes": nodes, "independent_pairs": 8, + "all_raw_quality_identity_gates": "verified", "summary": {"endpoints": [ + {"shape": s, "metric": m, "paired_log_ratios": [0] * 8} + for s in range(3) for m in ("ttft_ms", "tpot_ms", "request_tok_s")]}} + refs = {} + for name, document in (("pilot", pilot), ("audit", audit)): + path = final.ROOT / (name + ".json") + write_json(path, document) + refs[name] = {"path": path.name, "sha256": digest(path)} + plan = {"status": "feasible", "method": "order-stratified-bootstrap-simulation-v1", + "eligible_for_registration": True, "configuration": config, "baseline_sha": design["baseline_sha"], + "pilot_source_sha": pilot["source_sha"], "placements": placements, "reserved_nodes": nodes, + "pilot_receipt_sha256": refs["pilot"]["sha256"], "independent_audit_sha256": refs["audit"]["sha256"], + "pairs_per_phase": 16, "estimated_duration_s": 7200, "maximum_duration_s": 14400, "scenarios": [ {"candidate_loss": loss, "ab_sd_factor": factor, "modeled_joint_power_lower_bound": .95} for loss in (0, .005) for factor in (1, 1.5, 2)]} - design["configurations"]["qwen35-4b-standalone"].update(pairs_per_phase=16, planning_evidence=plan) + design["configurations"][config].update(pairs_per_phase=16, planning_evidence=plan, + placements=placements, reserved_nodes=nodes, power_receipts=refs) return design class DecisionTests(unittest.TestCase): + def setUp(self): + directory = self.enterContext(TemporaryDirectory()) + self.enterContext(patch.object(final, "ROOT", Path(directory))) + self.enterContext(patch.object(registration, "validate_simulation", return_value=None)) + def test_exact_equality_is_a_precise_within_tolerance_result(self): interval = paired_interval([0] * 8, resamples=1000) self.assertEqual(interval["ci95"], [1, 1]) @@ -71,6 +100,18 @@ def test_bootstrap_preserves_pairs_and_does_not_multiply_nested_requests(self): with self.assertRaises(ValueError): paired_interval([0, 0, 0], resamples=1000) + def test_constant_position_penalty_is_cancelled_in_every_balanced_resample(self): + penalty = math.log(1.06) + result = paired_interval([penalty, -penalty] * 8, resamples=1000) + self.assertEqual(result["ratio"], 1) + self.assertEqual(result["ci95"], [1, 1]) + with self.assertRaisesRegex(ValueError, "strata"): + paired_interval([0] * 8, resamples=1000, orders=["ab"] * 8) + + def test_touching_loss_margin_does_not_establish_strict_non_regression(self): + self.assertEqual(decide(ci(.98, 1), ci(1, 1), "higher")["claim_verdict"], "UNPROVEN") + self.assertEqual(decide(ci(1, 1.02), ci(1, 1), "lower")["claim_verdict"], "UNPROVEN") + def test_every_endpoint_must_pass_and_one_loss_cannot_be_outvoted(self): passed = decide(ci(.998, 1.002), ci(.999, 1.001), "higher") failed = decide(ci(.96, .97), ci(1, 1), "higher") @@ -110,7 +151,7 @@ def test_final_summary_reports_phase_losses_without_changing_client_scope(self): policy = {"cargo_profile": "release", "native_link": "static"} evidence = {"schema_version": 1, "protocol": design["protocol"], "source_sha": candidate, "baseline_sha": baseline, "configuration": config, - "placements": [{"role": "leader", "node": "offline fixture"}], + "placements": design["configurations"][config]["placements"], "builds": [{"role": "leader", **{name: {"stack_commit": sha, "cli_sha256": "c" * 64, "build_inputs": {"policy": policy}} for name, sha in (("main", baseline), ("candidate", candidate))}}], "registration": design, "runs": []} @@ -118,9 +159,11 @@ def test_final_summary_reports_phase_losses_without_changing_client_scope(self): phase_slow = 1.1 if arm["experiment"] == "client-ab" and arm["arm"] == "b" else 1 evidence["runs"].append({**arm, "placements": evidence["placements"], "quality": "passed", "samples": {"client": {"status": "passed", "summaries": [ - {"ttft_ms": 100, "tpot_ms": 10, "request_tok_s": 50}] * 3}, - "framing": {"id": 128}, "input_tokens": {"shape-0": 200}, "phases": [ - {"prefill_ms": 100 * phase_slow, "decode_ms": 200, "prompt_tokens": 200}] * 3}}) + {"shape": s, "ttft_ms": 100, "tpot_ms": 10, "request_tok_s": 50} for s in range(3)]}, + "framing": {f"r{r}-s{s}-measured": 128 for r in range(3) for s in range(3)}, + "input_tokens": {f"shape-{s}": 200 for s in range(3)}, "phases": [ + {"shape": s, "prefill_ms": 100 * phase_slow, "decode_ms": 200, + "prompt_tokens": 200} for s in range(3)]}}) result = final.summarize(evidence, design, resamples=1000) self.assertEqual(result["claim_verdict"], "PASS") self.assertEqual(len(result["client_endpoints"]), 9) @@ -131,15 +174,35 @@ def test_final_summary_reports_phase_losses_without_changing_client_scope(self): self.assertIn("1.1000 [1.1000, 1.1000]", report) self.assertIn("client pass does not prove server-phase non-regression", report) changed = copy.deepcopy(evidence) - changed["runs"][0]["samples"]["framing"] = {"id": 64} + changed["runs"][0]["samples"]["framing"]["r0-s0-measured"] = 64 result = final.summarize(changed, design, resamples=1000) self.assertEqual(result["claim_verdict"], "UNPROVEN") self.assertTrue(any(r["comparison"] == "incompatible_event_framing" for r in result["client_endpoints"])) + self.assertTrue(all(r["claim_verdict"] == "PASS" for r in result["client_endpoints"] + if r["metric"] == "tpot_ms" and r["shape"] != 0)) changed = copy.deepcopy(evidence) changed["builds"][0]["main"]["stack_commit"] = candidate with self.assertRaisesRegex(ValueError, "source identity"): final.summarize(changed, design, resamples=1000) + def test_power_receipts_reject_wrong_baseline_configuration_or_tampering(self): + for field, value in (("configuration", "other"), ("baseline_sha", "d" * 40)): + design = registered_design() + config = design["configurations"]["qwen35-4b-standalone"] + config["planning_evidence"][field] = value + with self.assertRaisesRegex(ValueError, "configuration or baseline"): + final.schedule(design["baseline_sha"], "b" * 40, "qwen35-4b-standalone", design) + design = registered_design() + (final.ROOT / "pilot.json").write_text("{}") + with self.assertRaisesRegex(ValueError, "digest"): + final.schedule(design["baseline_sha"], "b" * 40, "qwen35-4b-standalone", design) + + +class ProductionFenceTests(unittest.TestCase): + def test_actual_simulation_validation_is_required_before_any_real_final_admission(self): + with self.assertRaisesRegex(ValueError, "not implemented; acquisition prohibited"): + registration.validate_simulation({"method": "order-stratified-bootstrap-simulation-v1"}) + if __name__ == "__main__": unittest.main() diff --git a/scripts/tests/inference_client_power.py b/scripts/tests/inference_client_power.py index 2bf2abb2..cd6092bf 100644 --- a/scripts/tests/inference_client_power.py +++ b/scripts/tests/inference_client_power.py @@ -25,9 +25,10 @@ def test_variance_bound_accounts_for_all_nine_small_pilot_estimates(self): def test_count_meets_all_registered_loss_and_noise_sensitivities(self): evidence, proof = fixture() result = plan(evidence, proof) - self.assertEqual(result["status"], "feasible") + self.assertEqual(result["status"], "heuristic_only") + self.assertFalse(result["eligible_for_registration"]) self.assertEqual(result["pairs_per_phase"] % 2, 0) - self.assertGreaterEqual(min(s["modeled_joint_power_lower_bound"] for s in result["scenarios"]), .9) + self.assertGreaterEqual(min(s["fixed_width_proxy_score"] for s in result["scenarios"]), .9) endpoints = proof["summary"]["endpoints"] if result["pairs_per_phase"] > 16: self.assertLess(joint_power(endpoints, result["pairs_per_phase"] - 2, .005, 2), .9) @@ -37,7 +38,7 @@ def test_noisy_data_reports_budget_shortfall_instead_of_weakening_gate(self): result = plan(evidence, proof) self.assertEqual(result["status"], "lease_shortfall") self.assertGreater(result["estimated_duration_s"], 14400) - self.assertGreaterEqual(min(s["modeled_joint_power_lower_bound"] for s in result["scenarios"]), .9) + self.assertGreaterEqual(min(s["fixed_width_proxy_score"] for s in result["scenarios"]), .9) def test_power_decreases_with_candidate_loss_and_increased_ab_variance(self): _, proof = fixture() From b9cd921a30618c70ea1ec0e0540ea70b771952db Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sun, 29 Nov 2026 03:54:57 +1100 Subject: [PATCH 15/22] Add bounded private graph timeline diagnostics for main-only noise --- .gi/templates.yaml | 4 + ci/README.md | 13 ++ ci/automation.just | 1 + ci/inference-client-timeline.json | 16 +++ scripts/inference-execute.py | 9 +- scripts/inference-paired.py | 25 +++- scripts/lib/inference_client_timeline.py | 146 +++++++++++++++++++++ scripts/lib/inference_timeline_summary.py | 36 +++++ scripts/tests/inference_client_timeline.py | 104 +++++++++++++++ 9 files changed, 345 insertions(+), 9 deletions(-) create mode 100644 ci/inference-client-timeline.json create mode 100644 scripts/lib/inference_client_timeline.py create mode 100644 scripts/lib/inference_timeline_summary.py create mode 100644 scripts/tests/inference_client_timeline.py diff --git a/.gi/templates.yaml b/.gi/templates.yaml index f953aab8..80026d4a 100644 --- a/.gi/templates.yaml +++ b/.gi/templates.yaml @@ -672,6 +672,10 @@ { "value": "client-affinity", "label": "client-affinity" + }, + { + "value": "client-timeline", + "label": "client-timeline" } ], "default": "paired" diff --git a/ci/README.md b/ci/README.md index 6a3e92bc..b8ffe0eb 100644 --- a/ci/README.md +++ b/ci/README.md @@ -1204,3 +1204,16 @@ Enable the llama schedule only after source regeneration, full candidate CI, bounded repair and exact-commit PR publication work in acceptance pilots. No hosted/hardware capacity or secret configuration is implied by these files. + +The opt-in `client-timeline` diagnostic uses two fresh main servers on the original +standalone pilot host. It checks installed Nsight help, launches only the owned +server through `env -i`, warms it before interactive graph-level collection, and +caps collection at 120 seconds. It preserves the original cycled client bodies. +CPU sampling/context switches and GPU counters are disabled; no host policy or +privilege changes are made. The pinned InferenceKit analyzer runs on the allocated +host. Since it may not support graph-only activities, a separate bounded numeric +GPU/API interval export retains graph data without arbitrary profiler strings. +Raw `.nsys-rep` and SQLite files live outside the artifact directory, are analyzed +locally and removed before cleanup; they are never uploaded without user review. +These traces can diagnose host launch gaps versus GPU graph spans, but cannot +rank kernels inside graphs, establish an unprofiled speedup, or enter final pairs. diff --git a/ci/automation.just b/ci/automation.just index 41999eea..c13c780a 100644 --- a/ci/automation.just +++ b/ci/automation.just @@ -25,6 +25,7 @@ inference-contracts: @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_thread_affinity.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_stream_capture.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client_affinity.py + @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client_timeline.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_pairs.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_paired_execution.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/jy_read_recovery.py diff --git a/ci/inference-client-timeline.json b/ci/inference-client-timeline.json new file mode 100644 index 00000000..8353626a --- /dev/null +++ b/ci/inference-client-timeline.json @@ -0,0 +1,16 @@ +{ + "protocol": "DGX Spark main-only graph timeline diagnostic v1", + "baseline_sha": "cc2a27435e798649a9cb938d600d39722e4a2263", + "configuration": "qwen35-4b-standalone", + "node": "spark-000586", + "hostname": "spark-a29c", + "arms": 2, + "purpose": "Distinguish longer GPU graph execution from larger host launch gaps behind repeatable main/main decode variation; diagnostic only", + "capture": "Interactive nsys launch/start/stop, graph granularity, cuda+osrt, no CPU sampling/context switches or GPU counters; quality and two extra largest-shape warmups before start; <=120 seconds capture", + "workload": "Original27 cycled client-pilot request bodies once per server, three shapes and three repetitions, two64-token warmups and128 measured tokens each", + "environment": "env -i with PATH HOME LANG HF_HUB_OFFLINE and optional LD_LIBRARY_PATH CUDA_VISIBLE_DEVICES only; offline admitted model; no job credentials", + "raw_profile_policy": "Analyze on allocated host in private temporary directory outside artifact root, retain only bounded numeric activity/API intervals and reports, remove raw profiles before cleanup; never upload profiles without user review", + "interpretation": "No candidate speed claim. Trace durations include profiling overhead; no summed-kernel ranking; graph-only capture cannot attribute individual graph kernels. If neither arm reproduces slow delivery, causal noise attribution remains unproven.", + "reference": "https://docs.nvidia.com/nsight-systems/UserGuide/ (interactive CLI and CUDA graph trace; checked2026-11-28; installed help must validate flags)", + "budget": {"approved": true, "max_usd": 0, "max_duration_s": 14400, "controller_duration_s": 3600, "no_preemption": true} +} diff --git a/scripts/inference-execute.py b/scripts/inference-execute.py index 053a518a..8fbef1f2 100644 --- a/scripts/inference-execute.py +++ b/scripts/inference-execute.py @@ -98,7 +98,7 @@ def server_command(worker, phase_profile=False): return args -def execute(profile, key, mode, repetitions=1, probe=None, phase_profile=False, server_probe=None): +def execute(profile, key, mode, repetitions=1, probe=None, phase_profile=False, server_probe=None, server_command_wrapper=None, server_stop=None): sha, gpu = authority() result = plan(profile, sha) if not any(row["id"] == f"{key}-{mode}" for row in result["rows"]): @@ -137,7 +137,7 @@ def execute(profile, key, mode, repetitions=1, probe=None, phase_profile=False, port_available(peer.host, 9401) if not worker: port_available("127.0.0.1", 9337) - server = start(args, stdin=subprocess.DEVNULL, stdout=stream, stderr=stream) + server = start(server_command_wrapper(args) if server_command_wrapper else args, stdin=subprocess.DEVNULL, stdout=stream, stderr=stream) try: if worker: peer.worker_ready(server, read_json(output / "stage.json")) @@ -178,7 +178,10 @@ def execute(profile, key, mode, repetitions=1, probe=None, phase_profile=False, if mode == "split" else None), }) finally: - stop(server) + if server_stop is not None: + server_stop(server) + else: + stop(server) if __name__ == "__main__": diff --git a/scripts/inference-paired.py b/scripts/inference-paired.py index 024c729c..899573ee 100644 --- a/scripts/inference-paired.py +++ b/scripts/inference-paired.py @@ -29,6 +29,7 @@ from lib.inference_client_report import render as client_report from lib import inference_client_noise as client_noise from lib import inference_client_affinity as client_affinity +from lib import inference_client_timeline as client_timeline ROOT = Path(__file__).resolve().parents[1] EXECUTE = run_path(str(ROOT / "scripts/inference-execute.py"))["execute"] @@ -124,6 +125,10 @@ def run_arm(design, main, baseline, key, mode, output): EXECUTE("pr", key, mode, probe=client_final.measure) elif design["experiment"] == "client-noise": EXECUTE("pr", key, mode, probe=client_noise.measure) + elif design["experiment"] == "client-timeline": + with client_timeline.Timeline(directory) as timeline: + EXECUTE("pr", key, mode, probe=timeline.measure, server_command_wrapper=timeline.wrap, + server_stop=timeline.close_server) elif design["experiment"] == "client-affinity": EXECUTE("pr", key, mode, server_probe=partial(client_affinity.measure, arm=design["round"])) else: @@ -157,6 +162,9 @@ def ready(): def execute(key, mode, baseline, experiment="paired"): + timeline = experiment == "client-timeline" + if timeline: + client_timeline.schedule(baseline, f"{key}-{mode}") affinity = experiment == "client-affinity" if affinity: client_affinity.schedule(baseline, f"{key}-{mode}") @@ -196,7 +204,8 @@ def execute(key, mode, baseline, experiment="paired"): with baseline_tree(baseline) as main: identities = prepare(main, baseline, candidate, output) local = host(role, node) - designs = (client_affinity.schedule(baseline, f"{key}-{mode}") if affinity else + designs = (client_timeline.schedule(baseline, f"{key}-{mode}") if timeline else + client_affinity.schedule(baseline, f"{key}-{mode}") if affinity else client_noise.schedule(baseline, f"{key}-{mode}") if streamed_noise else client_final.schedule(baseline, candidate, f"{key}-{mode}") if final else client_pilot.schedule(baseline, f"{key}-{mode}") if sizing else @@ -235,6 +244,10 @@ def execute(key, mode, baseline, experiment="paired"): registered = client_noise.registration() evidence.update(protocol=registered["protocol"], registration=registered, rounds=registered["arms"], diagnostic_only=True) + if timeline: + registered = client_timeline.registration() + evidence.update(protocol=registered["protocol"], registration=registered, + rounds=registered["arms"], diagnostic_only=True) if affinity: registered = client_affinity.registration() evidence.update(protocol=registered["protocol"], registration=registered, @@ -251,7 +264,7 @@ def execute(key, mode, baseline, experiment="paired"): coordinate = f'{coordinate["repo"]}@{coordinate["revision"]}' evidence["runs"].append({**design, "placements": placements, "quality": "passed", "arm_duration_s": time.monotonic() - started, - "samples": (read_json(directory / "client-noise.json") if streamed_noise or affinity else + "samples": (read_json(directory / "client-noise.json") if streamed_noise or affinity or timeline else client_final.verify(coordinate, directory) if final else client.verify(directory, coordinate) if sizing else read_json(directory / f"noise-{kind}.json") if diagnostic @@ -262,7 +275,7 @@ def execute(key, mode, baseline, experiment="paired"): "provenance.json", "split-admissions.json", "split-peer.json"): if (directory / name).is_file(): shutil.copyfile(directory / name, output / name) - if streamed_noise or affinity: + if streamed_noise or affinity or timeline: evidence["status"] = "diagnostic-complete" elif final: evidence["summary"] = client_final.summarize(evidence) @@ -274,7 +287,7 @@ def execute(key, mode, baseline, experiment="paired"): else: evidence["status"] = "diagnostic-complete" finally: - write_json(output / ("client-affinity.json" if affinity else "client-noise.json" if streamed_noise else + write_json(output / ("client-timeline.json" if timeline else "client-affinity.json" if affinity else "client-noise.json" if streamed_noise else "client-final.json" if final else "client-pilot.json" if sizing else f"noise-{kind}.json" if diagnostic else "paired-probe.json"), evidence) @@ -284,10 +297,10 @@ def execute(key, mode, baseline, experiment="paired"): parser.add_argument("model") parser.add_argument("mode", choices=("standalone", "split")) parser.add_argument("baseline") - parser.add_argument("experiment", nargs="?", choices=("paired", "noise-pilot", "noise-profile", "client-pilot", "client-final", "client-noise", "client-affinity"), default="paired") + parser.add_argument("experiment", nargs="?", choices=("paired", "noise-pilot", "noise-profile", "client-pilot", "client-final", "client-noise", "client-affinity", "client-timeline"), default="paired") args = parser.parse_args() try: - with cancel_on_signal(), time_budget(3600 if args.experiment in {"client-noise", "client-affinity"} else 14400): + with cancel_on_signal(), time_budget(3600 if args.experiment in {"client-noise", "client-affinity", "client-timeline"} else 14400): execute(args.model, args.mode, args.baseline, args.experiment) except (OSError, ValueError, KeyError, RuntimeError, subprocess.SubprocessError, KeyboardInterrupt) as error: sys.exit(str(error)) diff --git a/scripts/lib/inference_client_timeline.py b/scripts/lib/inference_client_timeline.py new file mode 100644 index 00000000..94ccc60c --- /dev/null +++ b/scripts/lib/inference_client_timeline.py @@ -0,0 +1,146 @@ +"""Bounded main-only graph timeline; raw profiler files never enter artifacts.""" + +import os +import platform +import shutil +import subprocess +import tempfile +import time +import uuid +from pathlib import Path + +from .ci_artifacts import digest, read_json, write_json +from .ci_process import command, stop, time_budget +from .inference_client import ROOT, expected_body, prompts +from .inference_client_noise import measure as noise_measure, parse +from .inference_stream_capture import capture_stream +from .inference_timeline_summary import summarize + +REGISTRATION = ROOT / 'ci/inference-client-timeline.json' + + +def registration(): + return read_json(REGISTRATION) + + +def schedule(baseline, configuration): + design = registration() + if baseline != design['baseline_sha'] or configuration != design['configuration']: + raise ValueError('timeline requires its registered main/configuration') + return [{'experiment': 'client-timeline', 'round': arm, 'arm': 'a', 'source_sha': baseline} + for arm in range(design['arms'])] + + +class Timeline: + def __init__(self, output): + self.output = output + self.session = 'skippy' + uuid.uuid4().hex + self.nsys = shutil.which('nsys') + if self.nsys is None: + raise ValueError('nsys unavailable; timeline NOT RUN') + self.env = {key: os.environ[key] for key in ('PATH', 'HOME', 'LD_LIBRARY_PATH', 'CUDA_VISIBLE_DEVICES') + if key in os.environ} + self.env.update(LANG='C.UTF-8', HF_HUB_OFFLINE='1') + self.launched = False + self.closed = False + self.proof = {'registration': registration(), 'status': 'incomplete', 'trace_mode': 'graph', + 'environment_names': sorted(self.env), 'raw_profiles_uploaded': False} + + def run(self, args, timeout=60): + return command([self.nsys, *args], timeout=timeout, overrides=self.env, + inherit_env=False, capture_stdout=True, stderr=subprocess.STDOUT) + + def __enter__(self): + if platform.node() != registration()['hostname']: + raise ValueError('timeline requires original pilot host') + self.temporary = tempfile.TemporaryDirectory(prefix='skippy-private-timeline-') + self.private = Path(self.temporary.name) + try: + self.proof['nsys_version'] = self.run(['--version']) + for verb, flags in {'launch': ('--session-new', '--wait', '--cuda-graph-trace', '--cpuctxsw'), + 'start': ('--session', '--output', '--duration'), + 'stop': ('--session',), 'shutdown': ('--session', '--kill')}.items(): + help_text = self.run([verb, '--help']) + (self.output / f'nsys-{verb}-help.txt').write_text(help_text) + if any(flag not in help_text for flag in flags): + raise ValueError(f'installed nsys {verb} lacks required documented flags') + except BaseException: + self.temporary.cleanup() + raise + return self + + def wrap(self, args): + self.launched = True + # env -i protects the raw report even if the job carries dispatch credentials. + return ['/usr/bin/env', '-i', *[f'{k}={v}' for k, v in sorted(self.env.items())], self.nsys, + 'launch', '--session-new=' + self.session, '--wait=primary', '--trace=cuda,osrt', + '--cuda-graph-trace=graph', '--sample=none', '--cpuctxsw=none', *args] + + def measure(self, model, output): + # Native startup, quality, streaming smoke and these two long warmups precede collection. + warmups = [] + for index in range(2): + warm = next(p for p in prompts(model) if p['bucket'] == 'warm-2') + request = expected_body(model, warm) + text = request['messages'][0]['content'].split('\n', 1)[1] + request['messages'][0]['content'] = f'T{900+index}\n{text}' + result = capture_stream(request) + warmups.append({'request': request, **result, 'parsed': parse(result['raw_sse'], request)}) + write_json(output / 'timeline-warmups.json', warmups) + self.proof['capture_start_before_ns'] = time.perf_counter_ns() + self.proof['start_log'] = self.run(['start', '--session=' + self.session, + '--duration=120', '--output=' + str(self.private / 'capture')]) + self.proof['capture_start_after_ns'] = time.perf_counter_ns() + try: + with time_budget(100): + noise_measure(model, output, registered=registration(), sender=capture_stream) + finally: + self.proof['capture_stop_before_ns'] = time.perf_counter_ns() + self.proof['stop_log'] = self.run(['stop', '--session=' + self.session], timeout=180) + self.proof['capture_stop_after_ns'] = time.perf_counter_ns() + reports = list(self.private.glob('*.nsys-rep')) + if len(reports) != 1: + raise ValueError('timeline requires exactly one completed private profiler report') + report = reports[0] + sqlite = self.private / 'capture.sqlite' + self.run(['export', '--type=sqlite', '--output=' + str(sqlite), str(report)], timeout=180) + self.proof['raw_report_sha256'] = digest(report) + self.proof['sqlite_sha256'] = digest(sqlite) + write_json(output / 'timeline-intervals.json', summarize(sqlite)) + # The pinned analyzer may lack graph-only activity support. Preserve that limitation. + try: + result = command([str(ROOT / 'scripts/inferencekit.sh'), 'nsys', 'analyze', str(sqlite), '--json'], + timeout=180, capture_stdout=True, + overrides={'INFERENCEKIT_RUNS_DIR': str(self.private / 'analysis')}) + (output / 'inferencekit-timeline.json').write_text(result) + except subprocess.CalledProcessError as error: + self.proof['pinned_analyzer_limitation'] = f'exit {error.returncode}; numeric graph intervals retained' + self.proof['status'] = 'diagnostic-complete' + + def shutdown(self): + if self.launched and not self.closed: + self.proof['shutdown_log'] = self.run(['shutdown', '--session=' + self.session, '--kill=sigterm']) + self.closed = True + + def close_server(self, server): + # Finish the named session before generic process-tree cleanup; the + # interactive profiler daemon can otherwise outlive its launch CLI. + try: + self.shutdown() + finally: + stop(server) + + def __exit__(self, kind, error, traceback): + try: + self.shutdown() + except BaseException as cleanup_error: + self.proof.update(status='failed', cleanup_error=str(cleanup_error)) + raise + finally: + if error is not None: + self.proof.update(status='failed', error=str(error)) + self.proof['raw_profile_policy'] = 'Analyzed locally then removed; never uploaded without user review' + try: + write_json(self.output / 'timeline-proof.json', self.proof) + finally: + self.temporary.cleanup() diff --git a/scripts/lib/inference_timeline_summary.py b/scripts/lib/inference_timeline_summary.py new file mode 100644 index 00000000..39e2272a --- /dev/null +++ b/scripts/lib/inference_timeline_summary.py @@ -0,0 +1,36 @@ +"""Export bounded numeric GPU/API intervals without profiler environment metadata.""" + +import re +import sqlite3 + + +def summarize(path): + with sqlite3.connect(f"file:{path}?mode=ro", uri=True) as db: + names = {r[0] for r in db.execute("SELECT name FROM sqlite_master WHERE type='table'")} + strings = dict(db.execute('SELECT id,value FROM StringIds')) if 'StringIds' in names else {} + tables = {} + for name in sorted(names): + if not re.fullmatch(r"CUPTI_ACTIVITY_KIND_[A-Z_]+", name): + continue + columns = [r[1] for r in db.execute(f'PRAGMA table_info("{name}")')] + if not {'start', 'end'} <= set(columns): + continue + selected = [c for c in ('start', 'end', 'globalTid', 'globalPid', 'correlationId', + 'streamId', 'deviceId', 'graphId', 'graphNodeId', 'nameId') if c in columns] + rows = db.execute(f'SELECT {",".join(selected)} FROM "{name}" ORDER BY start LIMIT 250001').fetchall() + if len(rows) > 250000: + raise ValueError("timeline numeric export exceeded bounded interval count") + records = [dict(zip(selected, r)) for r in rows] + # Only CUDA API names; never export arbitrary StringIds or target/environment tables. + for row in records: + if 'nameId' in row: + value = strings.get(row['nameId'], '') + row['api'] = value if re.fullmatch(r'cu[A-Za-z0-9_]+', value) else 'unresolved' + tables[name] = records + if not tables or not any('GRAPH' in n or 'KERNEL' in n for n in tables): + raise ValueError("timeline has no GPU execution intervals; attribution is NOT RUN") + return {'scope': 'Observed under graph tracing, not unprofiled performance', + 'tables': tables, 'raw_profiles_uploaded': False, + 'limitations': ['No kernel-family ranking from graph-only tracing', + 'Intervals may overlap; use interval unions, never summed durations', + 'Client requests are outside the profiled server process; correlate cautiously']} diff --git a/scripts/tests/inference_client_timeline.py b/scripts/tests/inference_client_timeline.py new file mode 100644 index 00000000..a71fd96f --- /dev/null +++ b/scripts/tests/inference_client_timeline.py @@ -0,0 +1,104 @@ +"""Offline timeline hygiene/failure checks; no GPU qualification.""" + +import os +import sqlite3 +import unittest +from pathlib import Path +from tempfile import TemporaryDirectory +from unittest.mock import Mock, patch + +from lib import inference_client_timeline as timeline +from lib.inference_timeline_summary import summarize + + +class TimelineTests(unittest.TestCase): + def test_profiler_launch_clears_credentials_and_selects_graph_mode(self): + with TemporaryDirectory() as temporary, patch.dict(os.environ, { + 'JIANYANG_API_KEY': 'offline-secret', 'HF_TOKEN': 'offline-secret', 'PATH': '/bin'}): + with patch.object(timeline.shutil, 'which', return_value='/bin/nsys'): + capture = timeline.Timeline(Path(temporary)) + args = capture.wrap(['/binary/skippy', 'serve']) + self.assertEqual(args[:2], ['/usr/bin/env', '-i']) + self.assertNotIn('offline-secret', '\n'.join(args)) + self.assertNotIn('JIANYANG_API_KEY', capture.env) + self.assertIn('--cuda-graph-trace=graph', args) + self.assertIn('--sample=none', args) + self.assertIn('--cpuctxsw=none', args) + + def test_preflight_checks_installed_help_and_raw_storage_is_outside_artifacts(self): + with TemporaryDirectory() as temporary: + output = Path(temporary) + with patch.object(timeline.shutil, 'which', return_value='/bin/nsys'): + capture = timeline.Timeline(output) + help_text = '--session-new --session --wait --cuda-graph-trace --cpuctxsw --output --duration --kill' + with patch.object(capture, 'run', return_value=help_text), \ + patch.object(timeline.platform, 'node', return_value=timeline.registration()['hostname']): + with capture: + private = capture.private + self.assertFalse(private.is_relative_to(output)) + (private / 'sensitive.nsys-rep').write_text('not uploaded') + self.assertFalse(private.exists()) + self.assertFalse(list(output.rglob('*.nsys-rep'))) + + def test_failure_shuts_down_exact_session_and_removes_private_reports(self): + with TemporaryDirectory() as temporary: + output = Path(temporary) + with patch.object(timeline.shutil, 'which', return_value='/bin/nsys'): + capture = timeline.Timeline(output) + capture.temporary = TemporaryDirectory() + capture.private = Path(capture.temporary.name) + (capture.private / 'private.sqlite').write_text('private') + capture.launched = True + with patch.object(capture, 'run', return_value='stopped') as run: + capture.__exit__(RuntimeError, RuntimeError('request failed'), None) + run.assert_called_once_with(['shutdown', '--session=' + capture.session, '--kill=sigterm']) + self.assertFalse(capture.private.exists()) + self.assertEqual(timeline.read_json(output / 'timeline-proof.json')['status'], 'failed') + + def test_named_session_shutdown_precedes_generic_process_cleanup(self): + with patch.object(timeline.shutil, 'which', return_value='/bin/nsys'): + capture = timeline.Timeline(Path('/unused')) + capture.launched = True + events = [] + with patch.object(capture, 'run', side_effect=lambda args: events.append('shutdown')), \ + patch.object(timeline, 'stop', side_effect=lambda child: events.append('process cleanup')): + capture.close_server(Mock()) + capture.shutdown() + self.assertEqual(events, ['shutdown', 'process cleanup']) + + def test_session_commands_also_use_clean_environment(self): + with patch.object(timeline.shutil, 'which', return_value='/bin/nsys'): + capture = timeline.Timeline(Path('/unused')) + with patch.object(timeline, 'command', return_value='ok') as run: + capture.run(['stop', '--session=fixture']) + self.assertFalse(run.call_args.kwargs['inherit_env']) + self.assertEqual(run.call_args.kwargs['overrides'], capture.env) + + def test_summary_exports_only_numeric_activity_and_cuda_api_names(self): + with TemporaryDirectory() as temporary: + path = Path(temporary) / 'trace.sqlite' + with sqlite3.connect(path) as db: + db.execute('CREATE TABLE StringIds(id,value)') + db.executemany('INSERT INTO StringIds VALUES (?,?)', [(1,'cudaGraphLaunch_v10000'), (2,'SECRET=offline')]) + db.execute('CREATE TABLE CUPTI_ACTIVITY_KIND_GRAPH_TRACE(start,end,correlationId)') + db.executemany('INSERT INTO CUPTI_ACTIVITY_KIND_GRAPH_TRACE VALUES (?,?,?)',[(1,10,1),(5,15,2)]) + db.execute('CREATE TABLE CUPTI_ACTIVITY_KIND_RUNTIME(start,end,nameId)') + db.executemany('INSERT INTO CUPTI_ACTIVITY_KIND_RUNTIME VALUES (?,?,?)', [(1,2,1),(3,4,2)]) + db.execute('CREATE TABLE TARGET_INFO_ENV_VAR(value)') + db.execute("INSERT INTO TARGET_INFO_ENV_VAR VALUES ('SECRET=offline')") + result = summarize(path) + self.assertNotIn('SECRET', str(result)) + self.assertNotIn('TARGET_INFO_ENV_VAR', result['tables']) + self.assertEqual(len(result['tables']['CUPTI_ACTIVITY_KIND_GRAPH_TRACE']),2) + self.assertEqual(result['tables']['CUPTI_ACTIVITY_KIND_RUNTIME'][1]['api'],'unresolved') + + def test_no_gpu_execution_cannot_be_reported_as_attribution(self): + with TemporaryDirectory() as temporary: + path = Path(temporary) / 'empty.sqlite' + sqlite3.connect(path).close() + with self.assertRaisesRegex(ValueError, 'no GPU execution'): + summarize(path) + + +if __name__ == '__main__': + unittest.main() From d9dc0a5aa0624d59db387139b7ef8462794012d2 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sun, 29 Nov 2026 04:00:27 +1100 Subject: [PATCH 16/22] Verify final client comparisons independently from every uploaded arm --- ci/README.md | 18 +++- ci/automation.just | 1 + scripts/inference-dispatch.py | 17 ++- scripts/inference-paired.py | 4 +- scripts/lib/inference_client_collect.py | 70 ++++++++++++ scripts/lib/inference_client_raw.py | 123 ++++++++++++++++++++++ scripts/tests/inference_client_collect.py | 103 ++++++++++++++++++ 7 files changed, 328 insertions(+), 8 deletions(-) create mode 100644 scripts/lib/inference_client_collect.py create mode 100644 scripts/lib/inference_client_raw.py create mode 100644 scripts/tests/inference_client_collect.py diff --git a/ci/README.md b/ci/README.md index b8ffe0eb..ed153858 100644 --- a/ci/README.md +++ b/ci/README.md @@ -356,9 +356,9 @@ procedure is implemented. Counts remain unset. Power evidence must bind the configuration, baseline, pilot source, exact pilot and independent-audit file digests, nine distinct endpoint cells, and the reserved placement. Registration rejects mismatches before server arms start. The actual -allocation must match that registered placement. The controller/collector wiring -for the new receipt also remains pending, so a directly launched native success -cannot close the acceptance criterion. +allocation must match that registered placement. The opt-in dispatcher/independent raw collector for the new receipt is implemented, +but protected/default activation and live final collection remain pending. A directly +launched native success cannot close the acceptance criterion. Final time blocks contain one A/A pair and one A/B pair. The count is a multiple of four, and A/A-first versus A/B-first positions are balanced separately within @@ -1217,3 +1217,15 @@ Raw `.nsys-rep` and SQLite files live outside the artifact directory, are analyz locally and removed before cleanup; they are never uploaded without user review. These traces can diagnose host launch gaps versus GPU graph spans, but cannot rank kernels inside graphs, establish an unprofiled speedup, or enter final pairs. + +The explicit `--experiment client-final` dispatch route requires a registered +count/power design before creating its ledger or reserving any hardware. The +independent collector downloads every uploaded arm on every reserved role, +checks archive hashes and safe member rosters, reconstructs the pinned client +measurements and server-phase diagnostics, verifies source/build/offload, +quality and complete streams, and checks mutual split attempts and matching +native admission digests. Missing raw evidence or any non-PASS final performance +verdict fails collection after retaining available receipt/report evidence. +The default remains the older `paired` route. The current unregistered design +and simulation fence prohibit real final admission on either route; synthetic +collector tests and ordinary legacy CI cannot establish final qualification. diff --git a/ci/automation.just b/ci/automation.just index c13c780a..7d88f0d4 100644 --- a/ci/automation.just +++ b/ci/automation.just @@ -26,6 +26,7 @@ inference-contracts: @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_stream_capture.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client_affinity.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client_timeline.py + @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client_collect.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_pairs.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_paired_execution.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/jy_read_recovery.py diff --git a/scripts/inference-dispatch.py b/scripts/inference-dispatch.py index 03a4780e..876e2932 100644 --- a/scripts/inference-dispatch.py +++ b/scripts/inference-dispatch.py @@ -19,6 +19,8 @@ from lib.inference_throughput import collect from lib.jy_qualification import Pilot, placement from lib.inference_paired_collect import collect_pairs +from lib.inference_client_collect import collect_final +from lib.inference_client_final import schedule as final_schedule TERMINAL = {"succeeded", "failed", "cancelled", "expired"} FAILURE = TERMINAL - {"succeeded"} @@ -138,7 +140,9 @@ def record(ledger, identifiers): temporary.unlink(missing_ok=True) -def dispatch(pilot, profile, sha, output, configuration, collect_public=False, baseline=None): +def dispatch(pilot, profile, sha, output, configuration, collect_public=False, baseline=None, experiment="paired"): + if experiment == "client-final" and profile != "pr": + raise ValueError("client-final requires the PR qualification profile") result = plan(profile, sha) if profile == "pr": if baseline is None or not re.fullmatch(r"[0-9a-f]{40}", baseline): @@ -148,6 +152,9 @@ def dispatch(pilot, profile, sha, output, configuration, collect_public=False, b result["rows"] = [row for row in result["rows"] if row["id"] == configuration] if len(result["rows"]) != 1: raise ValueError("configuration not in qualification plan") + if experiment == "client-final": + for row in result["rows"]: + final_schedule(baseline, sha, row["id"]) output.mkdir(parents=True, exist_ok=True) write_json(output / "plan.json", result) ledger = output / "jobs.json" @@ -173,6 +180,8 @@ def dispatch(pilot, profile, sha, output, configuration, collect_public=False, b } if profile == "pr": body["inputs"]["baseline_sha"] = baseline + if experiment == "client-final": + body["inputs"]["experiment"] = experiment launched = launch(pilot, f"/v1/repos/skippy/templates/{template}/launch", body, deadline, mode == "split") handle = resource_id(launched.get("job_id")) @@ -184,7 +193,8 @@ def dispatch(pilot, profile, sha, output, configuration, collect_public=False, b if mode == "split": verify_split_peer(pilot, job, row, sha, profile, output) if profile == "pr": - collect_pairs(pilot, job, row, sha, baseline, output) + collector = collect_final if experiment == "client-final" else collect_pairs + collector(pilot, job, row, sha, baseline, output) if collect_public: collect_nightly(pilot, job, row, sha, output, model_key, profile) elif profile == "pr": @@ -208,6 +218,7 @@ def main(): action.add_argument("sha") action.add_argument("output", type=Path) action.add_argument("configuration", nargs="?") + action.add_argument("--experiment", choices=("paired", "client-final"), default="paired") action.add_argument("--collect-public", action="store_true") action.add_argument("--baseline", help="Protected admission's immutable main SHA") actions.add_parser("cancel").add_argument("ledger", type=Path) @@ -215,7 +226,7 @@ def main(): args = parser.parse_args() pilot = Pilot() if args.action == "dispatch": - dispatch(pilot, args.profile, args.sha, args.output, args.configuration, args.collect_public, args.baseline) + dispatch(pilot, args.profile, args.sha, args.output, args.configuration, args.collect_public, args.baseline, args.experiment) elif args.action == "cancel": cancel(pilot, args.ledger) else: diff --git a/scripts/inference-paired.py b/scripts/inference-paired.py index 899573ee..74487dcc 100644 --- a/scripts/inference-paired.py +++ b/scripts/inference-paired.py @@ -153,7 +153,7 @@ def ready(): return state["index"] == index await_condition(ready) directory = run_arm(design, main, baseline, key, "split", output) - if design["experiment"] == "ab" and design["arm"] == "b": + if design["experiment"] in {"ab", "client-ab"} and design["arm"] == "b": shutil.copyfile(directory / "split-peer.json", output / "split-peer.json") exchange(origin, "/done", {"index": index}) except BaseException: @@ -270,7 +270,7 @@ def execute(key, mode, baseline, experiment="paired"): read_json(directory / f"noise-{kind}.json") if diagnostic else samples(directory, coordinate))}) # Preserve the existing standalone nightly smoke receipts too. - if design["experiment"] == "ab" and design["arm"] == "b": + if design["experiment"] in {"ab", "client-ab"} and design["arm"] == "b": for name in ("qualification.json", "quality.json", "throughput-probe.json", "provenance.json", "split-admissions.json", "split-peer.json"): if (directory / name).is_file(): diff --git a/scripts/lib/inference_client_collect.py b/scripts/lib/inference_client_collect.py new file mode 100644 index 00000000..c812b757 --- /dev/null +++ b/scripts/lib/inference_client_collect.py @@ -0,0 +1,70 @@ +"""Independently verify final client qualification, including raw evidence on both roles.""" + +import os +from pathlib import Path + +from .ci_artifacts import write_json +from .inference_client_final import summarize +from .inference_client_raw import audit_role +from .inference_client_report import render +from .inference_paired_collect import arm_archives +from .inference_peer_evidence import overlap +from .inference_throughput import fetch_artifact, successful_run + + +def collect_final(pilot, job, row, candidate, baseline, output): + leader_run = successful_run(job, candidate) + evidence = fetch_artifact(pilot, leader_run, 'client-final.json') + if (evidence['source_sha'] != candidate or evidence['baseline_sha'] != baseline + or evidence['configuration'] != row['id']): + raise ValueError('final client receipt source/configuration mismatch') + write_json(output / (row['id'] + '-client-unverified.json'), evidence) + # This also enforces the registered acquisition/power fence before accepting results. + summary = summarize(evidence) + if evidence.get('summary') != summary: + raise ValueError('final client verdict differs from independently reconstructed decision') + roles = {'leader': job} + if row['mode'] == 'split': + formation = pilot.api('GET', '/v1/formations/' + job['formation_id']) + members = formation['members'] + if (formation['id'] != job['formation_id'] or formation['status'] != 'succeeded' + or len(members) != 2 or {m['role'] for m in members} != {'leader', 'worker'} + or any(m['status'] != 'succeeded' for m in members)): + raise ValueError('final client requires its own successful atomic split formation') + roles = {m['role']: pilot.api('GET', '/v1/jobs/' + m['job_id']) for m in members} + if roles['leader']['id'] != job['id']: + raise ValueError('final client formation leader mismatch') + overlap(roles['leader'], roles['worker']) + for member in members: + native = roles[member['role']] + if (native['id'] != member['job_id'] or native['formation_id'] != formation['id'] + or successful_run(native, candidate) != member['run_id'] + or native['runs'][-1]['machine_node'] != member['node']): + raise ValueError('final client formation attempt/placement mismatch') + runs = {role: successful_run(native, candidate) for role, native in roles.items()} + placements = {p['role']: p for p in evidence['placements']} + reserved = evidence['registration']['configurations'][row['id']]['reserved_nodes'] + rosters, audited = {}, {} + for role, native in roles.items(): + place = placements[role] + if (native['machine']['node'] != reserved[role] + or native['machine']['host']['hostname'] != place['hostname'] + or place['node'] != (native['machine']['node'] if row['mode'] == 'split' else place['hostname'])): + raise ValueError('final client placement differs from its actual reserved machine') + rosters[role] = arm_archives(pilot, runs[role], evidence['runs']) + write_json(output / (row['id'] + '-archives-' + role + '.json'), rosters[role]) + audited[role] = audit_role(pilot, native, runs[role], evidence, role, rosters[role], output, runs) + if row['mode'] == 'split' and any(a['split_admissions_sha256'] != b['split_admissions_sha256'] + for a, b in zip(audited['leader'], audited['worker'])): + raise ValueError('final leader/worker native admission digests differ') + receipt = {**evidence, 'summary': summary, 'job_id': job['id'], 'run_ids': runs, + 'archives_by_role': rosters, 'independent_raw_audit': 'verified'} + write_json(output / (row['id'] + '-client-final.json'), receipt) + report = render(receipt) + (output / (row['id'] + '-comparison.md')).write_text(report) + if os.environ.get('GITHUB_STEP_SUMMARY'): + with Path(os.environ['GITHUB_STEP_SUMMARY']).open('a') as stream: + stream.write(report) + if summary['claim_verdict'] != 'PASS': + raise ValueError('final client performance ' + summary['claim_verdict'] + '; see retained comparison') + return receipt diff --git a/scripts/lib/inference_client_raw.py b/scripts/lib/inference_client_raw.py new file mode 100644 index 00000000..7ea7b8d4 --- /dev/null +++ b/scripts/lib/inference_client_raw.py @@ -0,0 +1,123 @@ +"""Reconstruct final client samples from hashed uploaded arm archives.""" + +import re +import tarfile +import tempfile +from pathlib import Path +from urllib.request import Request + +from .ci_artifacts import digest, read_json +from .inference_admission import split_admissions_digest +from .inference_client_final import verify +from .inference_inputs import fixture +from .jy_qualification import ORIGIN + +ROOT = Path(__file__).resolve().parents[2] +MAX_ARCHIVE = 128 * 1024 * 1024 +MAX_EXPANDED = 512 * 1024 * 1024 + + +def download(pilot, run_id, name, manifest, path): + if manifest['size_bytes'] > MAX_ARCHIVE: + raise ValueError('final arm archive exceeds download limit') + request = Request(f'{ORIGIN}/v1/artifacts/{run_id}/raw/{name}', headers={ + 'Authorization': 'Bearer ' + pilot.auth(), 'User-Agent': 'skippy-inference-ci/1.0'}) + with pilot.opener.open(request, timeout=60) as response, path.open('wb') as stream: + size = 0 + while block := response.read(65536): + size += len(block) + if size > MAX_ARCHIVE: + raise ValueError('final arm archive exceeds download limit') + stream.write(block) + if path.stat().st_size != manifest['size_bytes'] or digest(path) != manifest['sha256']: + raise ValueError('final arm archive hash/size mismatch') + + +def unpack(path, destination, arm): + with tarfile.open(path) as archive: + members = archive.getmembers() + if (not members or len(members) > 10000 or sum(m.size for m in members) > MAX_EXPANDED + or any(not (m.isfile() or m.isdir()) or not Path(m.name).parts or Path(m.name).parts[0] != arm + or Path(m.name).is_absolute() or '..' in Path(m.name).parts for m in members) + or len({m.name for m in members}) != len(members)): + raise ValueError('invalid final arm archive contents') + archive.extractall(destination, filter='data') + return destination / arm + + +def audit_arm(directory, design, build, key, mode, role, expected_peer=None): + provenance = read_json(directory / 'provenance.json') + if (provenance['stack_commit'] != design['source_sha'] + or provenance['cli_sha256'] != build['cli_sha256'] + or provenance['build_inputs'] != build['build_inputs']): + raise ValueError('final raw arm executable/build provenance mismatch') + log = (directory / 'server.log').read_text() + if not any(int(n) > 0 for n in re.findall(r'offloaded ([0-9]+)/[^\n]*GPU', log)): + raise ValueError('final raw arm lacks GPU offload proof') + model = fixture(key) + admission, peer = None, None + if mode == 'split': + admissions = read_json(directory / 'split-admissions.json') + if admissions['stages'][-1]['layer_end'] != model['layers']: + raise ValueError('final raw arm split layer closure mismatch') + admission = split_admissions_digest(admissions) + peer = read_json(directory / 'split-peer.json') + if peer != expected_peer: + raise ValueError('final raw arm mutual split attempt proof mismatch') + if role == 'worker': + return {'split_admissions_sha256': admission} + expected = {'source_sha': design['source_sha'], 'model': key, 'mode': mode, + 'profile': 'pr', 'status': 'passed', 'split_peer': peer, + 'split_admissions_sha256': admission} + qualification = read_json(directory / 'qualification.json') + if any(qualification.get(k) != v for k, v in expected.items()): + raise ValueError('final raw arm qualification identity mismatch') + quality = read_json(directory / 'quality.json') + cases = read_json(ROOT / 'ci/inference-quality.json') + if len(quality) != len(cases): + raise ValueError('final raw arm quality roster incomplete') + for sample, case in zip(quality, cases): + text = sample['response']['choices'][0]['message']['content'] + if (sample['case'] != case or sample['passed'] is not True + or text.strip() != case['expected'] + or text != sample['repeat']['choices'][0]['message']['content']): + raise ValueError('final raw arm deterministic quality mismatch') + if (read_json(directory / 'smoke.json')['status'] != 'passed' + or b'[DONE]' not in (directory / 'streaming.sse').read_bytes()): + raise ValueError('final raw arm streaming smoke incomplete') + coordinate = model['repo'] + '@' + model['revision'] + fresh = verify(coordinate, directory) + if fresh != design['samples']: + raise ValueError('final client samples differ from retained raw records') + return {'samples': fresh, 'split_admissions_sha256': admission} + + +def audit_role(pilot, job, run_id, evidence, role, roster, output, peers): + key, mode = evidence['configuration'].rsplit('-', 1) + builds = next(b for b in evidence['builds'] if b['role'] == role) + manifests = {row['key'].rsplit('/', 1)[-1]: row for row in roster} + results = [] + with tempfile.TemporaryDirectory(prefix='final-raw-', dir=output) as temporary: + temporary = Path(temporary) + for design in evidence['runs']: + arm = f'{design["experiment"]}-{design["round"]}-{design["arm"]}' + name = arm + '-evidence.tar.gz' + manifest = manifests[name] + if f'/{job["id"]}/{run_id}/raw/' not in manifest['key']: + raise ValueError('final archive manifest belongs to another attempt') + archive = temporary / name + download(pilot, run_id, name, manifest, archive) + with tempfile.TemporaryDirectory(dir=temporary) as extracted: + directory = unpack(archive, Path(extracted), arm) + side = 'main' if design['source_sha'] == evidence['baseline_sha'] else 'candidate' + proof = None + if mode == 'split': + common = {'formation_id': job['formation_id'], 'source_sha': design['source_sha'], + 'model': key, 'profile': 'pr'} + other = 'worker' if role == 'leader' else 'leader' + proof = {'local': dict(common, role=role, run_id=run_id), + 'peer': dict(common, role=other, run_id=peers[other]), + 'completion_acknowledged': True} + results.append(audit_arm(directory, design, builds[side], key, mode, role, proof)) + archive.unlink() + return results diff --git a/scripts/tests/inference_client_collect.py b/scripts/tests/inference_client_collect.py new file mode 100644 index 00000000..fff21ecd --- /dev/null +++ b/scripts/tests/inference_client_collect.py @@ -0,0 +1,103 @@ +"""Final collector failure guards; synthetic data never qualifies performance.""" + +import io +import tarfile +import unittest +from pathlib import Path +from runpy import run_path +from tempfile import TemporaryDirectory +from unittest.mock import Mock, patch + +from lib import inference_client_collect as collect +from lib import inference_client_raw as raw +from lib.ci_artifacts import write_json + + +class CollectorTests(unittest.TestCase): + def test_final_dispatch_refuses_unregistered_design_before_hardware_or_ledger(self): + module = run_path(str(Path(__file__).resolve().parents[1] / 'inference-dispatch.py')) + dispatch = module['dispatch'] + pilot = Mock() + with TemporaryDirectory() as temporary: + output = Path(temporary) / 'not-created' + with self.assertRaisesRegex(ValueError, 'registered before acquisition'): + dispatch(pilot, 'pr', 'b'*40, output, 'qwen35-4b-standalone', baseline='a'*40, + experiment='client-final') + pilot.api.assert_not_called() + self.assertFalse(output.exists()) + + def test_archive_rejects_links_escape_and_duplicate_members(self): + with TemporaryDirectory() as temporary: + root = Path(temporary) + for names in [('arm/file','arm/file'), ('../escape',), ('/arm/file',)]: + archive = root / 'bad.tar.gz' + with tarfile.open(archive,'w:gz') as stream: + for name in names: + member = tarfile.TarInfo(name);member.size=1 + stream.addfile(member,io.BytesIO(b'x')) + with self.assertRaisesRegex(ValueError,'archive contents'): + raw.unpack(archive,root,'arm') + with tarfile.open(archive,'w:gz') as stream: + member=tarfile.TarInfo('arm/link');member.type=tarfile.SYMTYPE;member.linkname='/etc/passwd' + stream.addfile(member) + with self.assertRaisesRegex(ValueError,'archive contents'): + raw.unpack(archive,root,'arm') + + def test_download_checks_content_hash_not_just_manifest_presence(self): + with TemporaryDirectory() as temporary: + pilot=Mock();pilot.auth.return_value='offline-fixture' + pilot.opener.open.return_value=io.BytesIO(b'tampered') + with self.assertRaisesRegex(ValueError,'hash/size'): + raw.download(pilot,'run_fixture','arm.tar.gz',{'size_bytes':8,'sha256':'a'*64}, + Path(temporary)/'arm.tar.gz') + + def test_worker_without_native_offload_or_matching_executable_cannot_pass(self): + with TemporaryDirectory() as temporary: + root=Path(temporary);design={'source_sha':'a'*40} + build={'cli_sha256':'b'*64,'build_inputs':{'policy':{'cargo_profile':'release'}}} + write_json(root/'provenance.json',{'stack_commit':'a'*40,**build}) + (root/'server.log').write_text('CPU only') + with self.assertRaisesRegex(ValueError,'GPU offload'): + raw.audit_arm(root,design,build,'qwen35-4b','standalone','worker') + (root/'server.log').write_text('offloaded 25/25 layers to GPU') + changed={**build,'cli_sha256':'c'*64} + with self.assertRaisesRegex(ValueError,'provenance'): + raw.audit_arm(root,design,changed,'qwen35-4b','standalone','worker') + + def test_nonpassing_performance_retains_report_after_verified_raw_audit(self): + candidate,baseline='b'*40,'a'*40 + job={'id':'job_fixture','repo_rev':candidate,'status':'succeeded', + 'machine':{'node':'reserved-fixture','host':{'hostname':'host-fixture'}}, + 'runs':[{'id':'run_fixture','status':'succeeded'}]} + row={'id':'fixture-standalone','mode':'standalone'} + summary={'claim_verdict':'UNPROVEN'} + evidence={'source_sha':candidate,'baseline_sha':baseline,'configuration':row['id'], + 'summary':summary,'runs':[], 'placements':[{'role':'leader','hostname':'host-fixture','node':'host-fixture'}], + 'registration':{'configurations':{row['id']:{'reserved_nodes':{'leader':'reserved-fixture'}}}}} + with TemporaryDirectory() as temporary, \ + patch.object(collect,'fetch_artifact',return_value=evidence), \ + patch.object(collect,'summarize',return_value=summary), \ + patch.object(collect,'arm_archives',return_value=[]), \ + patch.object(collect,'audit_role',return_value=[]) as audit, \ + patch.object(collect,'render',return_value='UNPROVEN fixture; not qualification'): + output=Path(temporary) + with self.assertRaisesRegex(ValueError,'performance UNPROVEN'): + collect.collect_final(Mock(),job,row,candidate,baseline,output) + audit.assert_called_once() + self.assertTrue((output/(row['id']+'-comparison.md')).exists()) + self.assertEqual(collect.summarize.call_count,1) + + def test_malformed_or_unregistered_top_receipt_never_reaches_raw_admission(self): + job={'id':'job_fixture','repo_rev':'b'*40,'status':'succeeded', + 'runs':[{'id':'run_fixture','status':'succeeded'}]} + evidence={'source_sha':'b'*40,'baseline_sha':'a'*40,'configuration':'fixture'} + with patch.object(collect,'write_json'), patch.object(collect,'fetch_artifact',return_value=evidence), \ + patch.object(collect,'summarize',side_effect=ValueError('unregistered')), \ + patch.object(collect,'audit_role') as audit: + with self.assertRaisesRegex(ValueError,'unregistered'): + collect.collect_final(Mock(),job,{'id':'fixture','mode':'standalone'},'b'*40,'a'*40,Path('/unused')) + audit.assert_not_called() + + +if __name__ == '__main__': + unittest.main() From 8bf1932fb8e985056a827e95a2d650918c27ddb7 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sun, 29 Nov 2026 04:03:26 +1100 Subject: [PATCH 17/22] Use installed Nsight session controls and bind raw input manifests --- scripts/lib/inference_client_raw.py | 7 ++- scripts/lib/inference_client_timeline.py | 51 ++++++++++++++++++---- scripts/tests/inference_client_collect.py | 2 +- scripts/tests/inference_client_timeline.py | 14 ++++-- 4 files changed, 59 insertions(+), 15 deletions(-) diff --git a/scripts/lib/inference_client_raw.py b/scripts/lib/inference_client_raw.py index 7ea7b8d4..74b971e3 100644 --- a/scripts/lib/inference_client_raw.py +++ b/scripts/lib/inference_client_raw.py @@ -9,7 +9,7 @@ from .ci_artifacts import digest, read_json from .inference_admission import split_admissions_digest from .inference_client_final import verify -from .inference_inputs import fixture +from .inference_inputs import fixture, input_hashes from .jy_qualification import ORIGIN ROOT = Path(__file__).resolve().parents[2] @@ -51,6 +51,8 @@ def audit_arm(directory, design, build, key, mode, role, expected_peer=None): or provenance['cli_sha256'] != build['cli_sha256'] or provenance['build_inputs'] != build['build_inputs']): raise ValueError('final raw arm executable/build provenance mismatch') + if any(provenance.get(k) != v for k, v in input_hashes().items()): + raise ValueError('final raw arm input-manifest identity mismatch') log = (directory / 'server.log').read_text() if not any(int(n) > 0 for n in re.findall(r'offloaded ([0-9]+)/[^\n]*GPU', log)): raise ValueError('final raw arm lacks GPU offload proof') @@ -68,7 +70,8 @@ def audit_arm(directory, design, build, key, mode, role, expected_peer=None): return {'split_admissions_sha256': admission} expected = {'source_sha': design['source_sha'], 'model': key, 'mode': mode, 'profile': 'pr', 'status': 'passed', 'split_peer': peer, - 'split_admissions_sha256': admission} + 'split_admissions_sha256': admission, + 'artifact_manifest_sha256': input_hashes()['model_manifest_sha256']} qualification = read_json(directory / 'qualification.json') if any(qualification.get(k) != v for k, v in expected.items()): raise ValueError('final raw arm qualification identity mismatch') diff --git a/scripts/lib/inference_client_timeline.py b/scripts/lib/inference_client_timeline.py index 94ccc60c..5073e429 100644 --- a/scripts/lib/inference_client_timeline.py +++ b/scripts/lib/inference_client_timeline.py @@ -5,9 +5,11 @@ import shutil import subprocess import tempfile +import threading import time import uuid from pathlib import Path +from contextlib import contextmanager from .ci_artifacts import digest, read_json, write_json from .ci_process import command, stop, time_budget @@ -57,8 +59,8 @@ def __enter__(self): self.private = Path(self.temporary.name) try: self.proof['nsys_version'] = self.run(['--version']) - for verb, flags in {'launch': ('--session-new', '--wait', '--cuda-graph-trace', '--cpuctxsw'), - 'start': ('--session', '--output', '--duration'), + for verb, flags in {'launch': ('--session-new', '--wait', '--cuda-graph-trace'), + 'start': ('--session', '--output', '--sample', '--cpuctxsw'), 'stop': ('--session',), 'shutdown': ('--session', '--kill')}.items(): help_text = self.run([verb, '--help']) (self.output / f'nsys-{verb}-help.txt').write_text(help_text) @@ -74,7 +76,7 @@ def wrap(self, args): # env -i protects the raw report even if the job carries dispatch credentials. return ['/usr/bin/env', '-i', *[f'{k}={v}' for k, v in sorted(self.env.items())], self.nsys, 'launch', '--session-new=' + self.session, '--wait=primary', '--trace=cuda,osrt', - '--cuda-graph-trace=graph', '--sample=none', '--cpuctxsw=none', *args] + '--cuda-graph-trace=graph', *args] def measure(self, model, output): # Native startup, quality, streaming smoke and these two long warmups precede collection. @@ -89,15 +91,12 @@ def measure(self, model, output): write_json(output / 'timeline-warmups.json', warmups) self.proof['capture_start_before_ns'] = time.perf_counter_ns() self.proof['start_log'] = self.run(['start', '--session=' + self.session, - '--duration=120', '--output=' + str(self.private / 'capture')]) + '--sample=none', '--cpuctxsw=none', + '--output=' + str(self.private / 'capture')]) self.proof['capture_start_after_ns'] = time.perf_counter_ns() - try: + with self.collection_window(): with time_budget(100): noise_measure(model, output, registered=registration(), sender=capture_stream) - finally: - self.proof['capture_stop_before_ns'] = time.perf_counter_ns() - self.proof['stop_log'] = self.run(['stop', '--session=' + self.session], timeout=180) - self.proof['capture_stop_after_ns'] = time.perf_counter_ns() reports = list(self.private.glob('*.nsys-rep')) if len(reports) != 1: raise ValueError('timeline requires exactly one completed private profiler report') @@ -117,6 +116,40 @@ def measure(self, model, output): self.proof['pinned_analyzer_limitation'] = f'exit {error.returncode}; numeric graph intervals retained' self.proof['status'] = 'diagnostic-complete' + @contextmanager + def collection_window(self): + # Nsight 2025.3 start has no --duration. An independent watchdog stops + # the named collection even while a request/cleanup blocks. + done, lock, errors = threading.Event(), threading.Lock(), [] + stopped = False + def finish(): + nonlocal stopped + with lock: + if not stopped: + self.proof['capture_stop_before_ns'] = time.perf_counter_ns() + self.proof['stop_log'] = self.run(['stop', '--session=' + self.session], timeout=180) + self.proof['capture_stop_after_ns'] = time.perf_counter_ns() + stopped = True + def watchdog(): + if not done.wait(110): + self.proof['watchdog_triggered'] = True + try: + finish() + except BaseException as error: + errors.append(error) + watcher = threading.Thread(target=watchdog, daemon=True) + watcher.start() + try: + yield + finally: + done.set() + try: + finish() + finally: + watcher.join(timeout=190) + if watcher.is_alive() or errors or self.proof.get('watchdog_triggered'): + raise RuntimeError('timeline capture exceeded watchdog or stop failed') + def shutdown(self): if self.launched and not self.closed: self.proof['shutdown_log'] = self.run(['shutdown', '--session=' + self.session, '--kill=sigterm']) diff --git a/scripts/tests/inference_client_collect.py b/scripts/tests/inference_client_collect.py index fff21ecd..a2dccecf 100644 --- a/scripts/tests/inference_client_collect.py +++ b/scripts/tests/inference_client_collect.py @@ -55,7 +55,7 @@ def test_worker_without_native_offload_or_matching_executable_cannot_pass(self): with TemporaryDirectory() as temporary: root=Path(temporary);design={'source_sha':'a'*40} build={'cli_sha256':'b'*64,'build_inputs':{'policy':{'cargo_profile':'release'}}} - write_json(root/'provenance.json',{'stack_commit':'a'*40,**build}) + write_json(root/'provenance.json',{'stack_commit':'a'*40,**build,**raw.input_hashes()}) (root/'server.log').write_text('CPU only') with self.assertRaisesRegex(ValueError,'GPU offload'): raw.audit_arm(root,design,build,'qwen35-4b','standalone','worker') diff --git a/scripts/tests/inference_client_timeline.py b/scripts/tests/inference_client_timeline.py index a71fd96f..9167c907 100644 --- a/scripts/tests/inference_client_timeline.py +++ b/scripts/tests/inference_client_timeline.py @@ -22,15 +22,13 @@ def test_profiler_launch_clears_credentials_and_selects_graph_mode(self): self.assertNotIn('offline-secret', '\n'.join(args)) self.assertNotIn('JIANYANG_API_KEY', capture.env) self.assertIn('--cuda-graph-trace=graph', args) - self.assertIn('--sample=none', args) - self.assertIn('--cpuctxsw=none', args) def test_preflight_checks_installed_help_and_raw_storage_is_outside_artifacts(self): with TemporaryDirectory() as temporary: output = Path(temporary) with patch.object(timeline.shutil, 'which', return_value='/bin/nsys'): capture = timeline.Timeline(output) - help_text = '--session-new --session --wait --cuda-graph-trace --cpuctxsw --output --duration --kill' + help_text = '--session-new --session --wait --cuda-graph-trace --cpuctxsw --output --sample --kill' with patch.object(capture, 'run', return_value=help_text), \ patch.object(timeline.platform, 'node', return_value=timeline.registration()['hostname']): with capture: @@ -66,6 +64,16 @@ def test_named_session_shutdown_precedes_generic_process_cleanup(self): capture.shutdown() self.assertEqual(events, ['shutdown', 'process cleanup']) + def test_collection_stops_named_session_even_when_request_fails(self): + with patch.object(timeline.shutil, 'which', return_value='/bin/nsys'): + capture = timeline.Timeline(Path('/unused')) + with patch.object(capture, 'run', return_value='stopped') as run: + with self.assertRaisesRegex(RuntimeError,'request failure'): + with capture.collection_window(): + raise RuntimeError('request failure') + run.assert_called_once_with(['stop','--session='+capture.session],timeout=180) + self.assertIn('capture_stop_after_ns',capture.proof) + def test_session_commands_also_use_clean_environment(self): with patch.object(timeline.shutil, 'which', return_value='/bin/nsys'): capture = timeline.Timeline(Path('/unused')) From a9dd16051ccbc80efcb04ce308dd87ebd3009e6f Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sun, 29 Nov 2026 04:14:14 +1100 Subject: [PATCH 18/22] Bound timeline exports by aggregating high-volume CUDA API calls --- scripts/lib/inference_client_timeline.py | 10 ++--- scripts/lib/inference_timeline_summary.py | 48 +++++++++++++++++----- scripts/tests/inference_client_timeline.py | 22 +++++++++- 3 files changed, 62 insertions(+), 18 deletions(-) diff --git a/scripts/lib/inference_client_timeline.py b/scripts/lib/inference_client_timeline.py index 5073e429..529b6340 100644 --- a/scripts/lib/inference_client_timeline.py +++ b/scripts/lib/inference_client_timeline.py @@ -89,12 +89,12 @@ def measure(self, model, output): result = capture_stream(request) warmups.append({'request': request, **result, 'parsed': parse(result['raw_sse'], request)}) write_json(output / 'timeline-warmups.json', warmups) - self.proof['capture_start_before_ns'] = time.perf_counter_ns() - self.proof['start_log'] = self.run(['start', '--session=' + self.session, - '--sample=none', '--cpuctxsw=none', - '--output=' + str(self.private / 'capture')]) - self.proof['capture_start_after_ns'] = time.perf_counter_ns() with self.collection_window(): + self.proof['capture_start_before_ns'] = time.perf_counter_ns() + self.proof['start_log'] = self.run(['start', '--session=' + self.session, + '--sample=none', '--cpuctxsw=none', + '--output=' + str(self.private / 'capture')]) + self.proof['capture_start_after_ns'] = time.perf_counter_ns() with time_budget(100): noise_measure(model, output, registered=registration(), sender=capture_stream) reports = list(self.private.glob('*.nsys-rep')) diff --git a/scripts/lib/inference_timeline_summary.py b/scripts/lib/inference_timeline_summary.py index 39e2272a..dea16f17 100644 --- a/scripts/lib/inference_timeline_summary.py +++ b/scripts/lib/inference_timeline_summary.py @@ -1,36 +1,62 @@ -"""Export bounded numeric GPU/API intervals without profiler environment metadata.""" +"""Export bounded GPU/graph-launch intervals without profiler environment metadata.""" import re import sqlite3 +MAX_ROWS = 250000 + def summarize(path): with sqlite3.connect(f"file:{path}?mode=ro", uri=True) as db: names = {r[0] for r in db.execute("SELECT name FROM sqlite_master WHERE type='table'")} strings = dict(db.execute('SELECT id,value FROM StringIds')) if 'StringIds' in names else {} - tables = {} + tables, inventory, api_counts, omitted = {}, {}, {}, [] for name in sorted(names): if not re.fullmatch(r"CUPTI_ACTIVITY_KIND_[A-Z_]+", name): continue columns = [r[1] for r in db.execute(f'PRAGMA table_info("{name}")')] if not {'start', 'end'} <= set(columns): continue + count = db.execute(f'SELECT count(*) FROM "{name}"').fetchone()[0] + inventory[name] = {'count': count, 'columns': columns} selected = [c for c in ('start', 'end', 'globalTid', 'globalPid', 'correlationId', 'streamId', 'deviceId', 'graphId', 'graphNodeId', 'nameId') if c in columns] - rows = db.execute(f'SELECT {",".join(selected)} FROM "{name}" ORDER BY start LIMIT 250001').fetchall() - if len(rows) > 250000: - raise ValueError("timeline numeric export exceeded bounded interval count") + where = '' + if name.endswith(('_RUNTIME', '_DRIVER')) and 'nameId' in columns: + # Millions of sync/query/copy API calls need not become per-row + # JSON. Preserve complete counts and duration ranges by API; + # retain individual graph-launch intervals for host/device joins. + groups = db.execute(f'SELECT nameId,count(*),min(end-start),max(end-start),avg(end-start) ' + f'FROM "{name}" GROUP BY nameId LIMIT 4097').fetchall() + if len(groups) > 4096: + raise ValueError(f'{name}: API-name inventory exceeds bound') + api_counts[name] = [{'api': api_name(strings.get(n, '')), 'count': c, + 'min_ns': lo, 'max_ns': hi, 'mean_ns': avg} for n, c, lo, hi, avg in groups] + ids = [int(n) for n, value in strings.items() if re.match(r'^cu(da)?GraphLaunch', value)] + where = ' WHERE nameId IN (' + ','.join(map(str, ids)) + ')' if ids else ' WHERE 0' + rows = db.execute(f'SELECT {",".join(selected)} FROM "{name}"{where} ' + f'ORDER BY start LIMIT {MAX_ROWS+1}').fetchall() + if len(rows) > MAX_ROWS: + omitted.append({'table': name, 'reason': 'interval roster exceeds bound', 'original_count': count}) + continue # Never present a biased prefix as complete coverage. records = [dict(zip(selected, r)) for r in rows] - # Only CUDA API names; never export arbitrary StringIds or target/environment tables. for row in records: if 'nameId' in row: - value = strings.get(row['nameId'], '') - row['api'] = value if re.fullmatch(r'cu[A-Za-z0-9_]+', value) else 'unresolved' + row['api'] = api_name(strings.get(row['nameId'], '')) tables[name] = records - if not tables or not any('GRAPH' in n or 'KERNEL' in n for n in tables): - raise ValueError("timeline has no GPU execution intervals; attribution is NOT RUN") + if not any(('GRAPH' in n or 'KERNEL' in n) and rows for n, rows in tables.items()): + counts = {n: row['count'] for n, row in inventory.items()} + raise ValueError(f'timeline has no complete bounded GPU execution intervals; attribution is NOT RUN: {counts}') return {'scope': 'Observed under graph tracing, not unprofiled performance', - 'tables': tables, 'raw_profiles_uploaded': False, + 'tables': tables, 'inventory': inventory, 'api_counts': api_counts, + 'omitted_interval_tables': omitted, 'raw_profiles_uploaded': False, 'limitations': ['No kernel-family ranking from graph-only tracing', 'Intervals may overlap; use interval unions, never summed durations', + 'API counts/ranges are complete, individual API rows cover graph launch only', + 'Any omitted GPU table prevents a complete device-busy attribution', 'Client requests are outside the profiled server process; correlate cautiously']} + + +def api_name(value): + # Never export arbitrary StringIds or target/environment metadata. + return value if re.fullmatch(r'cu[A-Za-z0-9_]+', value) else 'unresolved' diff --git a/scripts/tests/inference_client_timeline.py b/scripts/tests/inference_client_timeline.py index 9167c907..560ec3fe 100644 --- a/scripts/tests/inference_client_timeline.py +++ b/scripts/tests/inference_client_timeline.py @@ -98,13 +98,31 @@ def test_summary_exports_only_numeric_activity_and_cuda_api_names(self): self.assertNotIn('SECRET', str(result)) self.assertNotIn('TARGET_INFO_ENV_VAR', result['tables']) self.assertEqual(len(result['tables']['CUPTI_ACTIVITY_KIND_GRAPH_TRACE']),2) - self.assertEqual(result['tables']['CUPTI_ACTIVITY_KIND_RUNTIME'][1]['api'],'unresolved') + self.assertEqual(len(result['tables']['CUPTI_ACTIVITY_KIND_RUNTIME']),1) + self.assertEqual(result['api_counts']['CUPTI_ACTIVITY_KIND_RUNTIME'][1]['api'],'unresolved') + + def test_high_volume_api_calls_are_aggregated_while_graph_launches_are_retained(self): + with TemporaryDirectory() as temporary: + path=Path(temporary)/'trace.sqlite' + with sqlite3.connect(path) as db: + db.execute('CREATE TABLE StringIds(id,value)') + db.executemany('INSERT INTO StringIds VALUES (?,?)',[(1,'cudaGraphLaunch'),(2,'cudaEventQuery')]) + db.execute('CREATE TABLE CUPTI_ACTIVITY_KIND_GRAPH_TRACE(start,end)') + db.execute('INSERT INTO CUPTI_ACTIVITY_KIND_GRAPH_TRACE VALUES (1,10)') + db.execute('CREATE TABLE CUPTI_ACTIVITY_KIND_RUNTIME(start,end,nameId)') + db.executemany('INSERT INTO CUPTI_ACTIVITY_KIND_RUNTIME VALUES (?,?,2)',[(i,i+1) for i in range(100)]) + db.execute('INSERT INTO CUPTI_ACTIVITY_KIND_RUNTIME VALUES (1,2,1)') + with patch('lib.inference_timeline_summary.MAX_ROWS',4): + result=summarize(path) + self.assertEqual(len(result['tables']['CUPTI_ACTIVITY_KIND_RUNTIME']),1) + self.assertEqual(result['api_counts']['CUPTI_ACTIVITY_KIND_RUNTIME'][1]['count'],100) + self.assertFalse(result['omitted_interval_tables']) def test_no_gpu_execution_cannot_be_reported_as_attribution(self): with TemporaryDirectory() as temporary: path = Path(temporary) / 'empty.sqlite' sqlite3.connect(path).close() - with self.assertRaisesRegex(ValueError, 'no GPU execution'): + with self.assertRaisesRegex(ValueError, 'no complete bounded GPU execution'): summarize(path) From 104facd68ba9b5b434626ec57edb9a420906285f Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sun, 29 Nov 2026 04:34:45 +1100 Subject: [PATCH 19/22] Trace native ABI and scheduler costs behind pre-launch noise --- ci/README.md | 10 ++++ ci/automation.just | 1 + ci/inference-client-noise.json | 21 +++++-- scripts/inference-paired.py | 9 ++- scripts/lib/inference_client_phases.py | 74 ++++++++++++++++++++++++ scripts/tests/inference_client_phases.py | 45 ++++++++++++++ 6 files changed, 154 insertions(+), 6 deletions(-) create mode 100644 scripts/lib/inference_client_phases.py create mode 100644 scripts/tests/inference_client_phases.py diff --git a/ci/README.md b/ci/README.md index ed153858..ed7db329 100644 --- a/ci/README.md +++ b/ci/README.md @@ -1229,3 +1229,13 @@ verdict fails collection after retaining available receipt/report evidence. The default remains the older `paired` route. The current unregistered design and simulation fence prohibit real final admission on either route; synthetic collector tests and ordinary legacy CI cannot establish final qualification. + +The main-only `client-noise` diagnostic registration v2 enables debug native-ABI +and scheduler OTLP timings to locate the remaining pre-launch host gap. The +original request bodies/order, sampling flags and token counts are unchanged; +all streams and content-event timestamps remain raw evidence. Each request +must retain enough innermost native iteration-call spans; nested ABI wrappers +never become extra samples. Detailed native sampler spans may be unavailable +in a static executable and cannot be inferred from their absence. Debug trace +cost is part of this diagnostic, so none of these requests enters sizing or +final qualification. Earlier v1 evidence keeps its original scope and labels. diff --git a/ci/automation.just b/ci/automation.just index 7d88f0d4..573699c4 100644 --- a/ci/automation.just +++ b/ci/automation.just @@ -26,6 +26,7 @@ inference-contracts: @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_stream_capture.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client_affinity.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client_timeline.py + @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client_phases.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client_collect.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_pairs.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_paired_execution.py diff --git a/ci/inference-client-noise.json b/ci/inference-client-noise.json index ee16d45b..bab2e78d 100644 --- a/ci/inference-client-noise.json +++ b/ci/inference-client-noise.json @@ -1,13 +1,24 @@ { - "protocol": "DGX Spark standalone streaming noise diagnostic v1", - "purpose": "Distinguish native generation variability from client delivery variability and correlate it with clocks, scheduling and CPU quota; no candidate or power verdict", + "protocol": "DGX Spark standalone streaming host-phase diagnostic v2", + "purpose": "Localize observed pre-GPU-launch variation inside native ABI calls versus serving/scheduler gaps; no candidate or power verdict", "baseline_sha": "cc2a27435e798649a9cb938d600d39722e4a2263", "configuration": "qwen35-4b-standalone", "arms": 2, "workload": "Exact client-pilot request bodies and order: three cycled shapes, three repetitions, two64-token warmups before128-token measurement", "acquisition": "Diagnostic curl streaming capture retains complete SSE including native terminal timings; not the pinned client's final timing path", - "hypotheses": ["Native predicted_ms varies with client elapsed time: engine/host variability", "Native predicted_ms is stable while client elapsed varies: delivery/client path", "GPU clocks, CPU placement/frequency or cgroup throttling covary with slow requests"], - "telemetry": "One-second GPU/host samples; monotonic request boundaries, CPU thread placement/frequency and cgroup CPU counters; standard native logging, phase tracing off", + "hypotheses": [ + "Native call duration varies while between-call gap stays stable: native host work or device wait path", + "Between-call gap varies while native call duration stays stable: serving/scheduler handoff", + "Existing native source disables backend greedy sampling with ignore_eos=true; CPU sampling is a hypothesis, not a proven cause" + ], + "telemetry": "One-second GPU/host samples plus debug OTLP native ABI/scheduler spans; complete original curl streams and content-event timestamps. Detailed native sampler spans are optional and may be unavailable in static builds.", "analysis": "Retain every raw stream; identical request IDs/text/token counts and complete usage/length/DONE required. Correlation alone does not establish a causal fix; no historical verdict changes.", - "budget": {"approved": true, "max_usd": 0, "max_duration_s": 14400, "controller_duration_s": 3600, "no_preemption": true} + "budget": { + "approved": true, + "max_usd": 0, + "max_duration_s": 14400, + "controller_duration_s": 3600, + "no_preemption": true + }, + "native_phase_trace": true } diff --git a/scripts/inference-paired.py b/scripts/inference-paired.py index 74487dcc..93afa2d4 100644 --- a/scripts/inference-paired.py +++ b/scripts/inference-paired.py @@ -30,6 +30,8 @@ from lib import inference_client_noise as client_noise from lib import inference_client_affinity as client_affinity from lib import inference_client_timeline as client_timeline +from lib import inference_client_phases as client_phases +from lib.inference_stream_capture import capture_stream ROOT = Path(__file__).resolve().parents[1] EXECUTE = run_path(str(ROOT / "scripts/inference-execute.py"))["execute"] @@ -124,7 +126,12 @@ def run_arm(design, main, baseline, key, mode, output): elif design["experiment"] in {"client-aa", "client-ab"}: EXECUTE("pr", key, mode, probe=client_final.measure) elif design["experiment"] == "client-noise": - EXECUTE("pr", key, mode, probe=client_noise.measure) + phase = client_noise.registration().get("native_phase_trace", False) + with client_phases.trace_context(directory) if phase else nullcontext(): + probe = partial(client_noise.measure, sender=capture_stream) if phase else client_noise.measure + EXECUTE("pr", key, mode, probe=probe, phase_profile=phase) + if phase: + client_phases.verify_trace(directory) elif design["experiment"] == "client-timeline": with client_timeline.Timeline(directory) as timeline: EXECUTE("pr", key, mode, probe=timeline.measure, server_command_wrapper=timeline.wrap, diff --git a/scripts/lib/inference_client_phases.py b/scripts/lib/inference_client_phases.py new file mode 100644 index 00000000..cffcba86 --- /dev/null +++ b/scripts/lib/inference_client_phases.py @@ -0,0 +1,74 @@ +"""Require per-request native ABI timing coverage for the host-gap diagnostic.""" + +import json +import os +from collections import Counter +from contextlib import contextmanager +from statistics import mean, median + +from .ci_artifacts import digest, read_json, write_json + +TRACE_ENV = 'SKIPPY_TELEMETRY_OTLP_FILE' +CALL = 'native.skippy_iteration_batch_sampled' + + +@contextmanager +def trace_context(output): + previous = os.environ.get(TRACE_ENV) + os.environ[TRACE_ENV] = str(output / 'phases.jsonl') + try: + yield + finally: + if previous is None: + os.environ.pop(TRACE_ENV, None) + else: + os.environ[TRACE_ENV] = previous + + +def leaf_calls(spans): + # Some runtime layers nest wrappers around the same ABI call. Count the + # innermost interval, never multiply those wrappers into extra iterations. + pairs = sorted({(int(s['startTimeUnixNano']), int(s['endTimeUnixNano'])) for s in spans}, + key=lambda p: (p[0], -p[1])) + return [p for i, p in enumerate(pairs) if i+1 == len(pairs) + or not (p[0] <= pairs[i+1][0] and pairs[i+1][1] <= p[1])] + + +def verify_trace(output): + path = output / 'phases.jsonl' + spans = [] + with path.open() as stream: + for line in stream: + for resource in json.loads(line).get('resourceSpans', []): + for scope in resource.get('scopeSpans', []): + spans.extend(scope.get('spans', [])) + counts = Counter(s['name'] for s in spans) + if not counts[CALL] or not counts['stage.scheduler_feature_iteration']: + raise ValueError('host-gap diagnostic lacks native ABI and scheduler timing coverage') + requests = read_json(output / 'client-noise.json')['samples'] + calls = [s for s in spans if s['name'] == CALL] + rows = [] + for request in requests: + begin = request['started_wall_ns'] + end = begin + request['completed_ns'] - request['started_ns'] + selected = [s for s in calls if begin <= int(s['startTimeUnixNano']) + and int(s['endTimeUnixNano']) <= end] + leaves = leaf_calls(selected) + required = request['request']['max_tokens'] - 1 + if not required <= len(leaves) <= required + 9 or any(a >= b for a, b in leaves): + raise ValueError('host-gap diagnostic has incomplete or ambiguous per-request native calls') + durations = [(b-a)/1e6 for a, b in leaves] + gaps = [(b[0]-a[1])/1e6 for a, b in zip(leaves, leaves[1:])] + if any(v < 0 for v in gaps): + raise ValueError('host-gap native leaf calls overlap') + rows.append({'id': request['id'], 'bucket': request['bucket'], 'leaf_calls': len(leaves), + 'native_call_ms': {'mean': mean(durations), 'median': median(durations)}, + 'between_native_calls_ms': {'mean': mean(gaps), 'median': median(gaps)}}) + proof = {'status': 'diagnostic-complete', 'trace_sha256': digest(path), 'span_counts': dict(counts), + 'requests': rows, 'scope': 'Observed with debug telemetry; no performance qualification', + 'limitations': ['Wall-clock request joins assume no host clock step during a request', + 'Native ABI spans include all native work, not just GPU execution', + 'Inner sampler spans may be unavailable in a static executable; missing detail is NOT RUN', + 'Debug telemetry adds overhead; these requests never enter sizing or final acquisition']} + write_json(output / 'client-phase-proof.json', proof) + return proof diff --git a/scripts/tests/inference_client_phases.py b/scripts/tests/inference_client_phases.py new file mode 100644 index 00000000..2fa6111f --- /dev/null +++ b/scripts/tests/inference_client_phases.py @@ -0,0 +1,45 @@ +"""Offline host-phase capture guards; no native or hardware qualification.""" + +import json +import os +import unittest +from pathlib import Path +from tempfile import TemporaryDirectory + +from lib import inference_client_phases as phases +from lib.ci_artifacts import write_json + + +class PhaseTests(unittest.TestCase): + def test_trace_environment_is_restored_after_failure(self): + old = os.environ.get(phases.TRACE_ENV) + with TemporaryDirectory() as temporary: + with self.assertRaisesRegex(RuntimeError,'injected'): + with phases.trace_context(Path(temporary)): + self.assertEqual(os.environ[phases.TRACE_ENV],str(Path(temporary)/'phases.jsonl')) + raise RuntimeError('injected') + self.assertEqual(os.environ.get(phases.TRACE_ENV),old) + + def test_nested_wrappers_count_as_one_leaf_and_not_extra_samples(self): + rows=[{'startTimeUnixNano':str(a),'endTimeUnixNano':str(b)} for a,b in ((1,10),(2,9),(11,20),(11,20))] + self.assertEqual(phases.leaf_calls(rows),[(2,9),(11,20)]) + + def test_every_request_requires_sufficient_native_call_coverage(self): + with TemporaryDirectory() as temporary: + output=Path(temporary) + write_json(output/'client-noise.json',{'samples':[{'id':'fixture','bucket':'shape-0', + 'request':{'max_tokens':4},'started_wall_ns':100,'started_ns':0,'completed_ns':100}]}) + def trace(count): + spans=[{'name':phases.CALL,'startTimeUnixNano':str(110+i*10), + 'endTimeUnixNano':str(115+i*10)} for i in range(count)] + spans.append({'name':'stage.scheduler_feature_iteration','startTimeUnixNano':'100','endTimeUnixNano':'200'}) + (output/'phases.jsonl').write_text(json.dumps({'resourceSpans':[{'scopeSpans':[{'spans':spans}]}]})+'\n') + trace(3) + self.assertEqual(phases.verify_trace(output)['requests'][0]['leaf_calls'],3) + trace(2) + with self.assertRaisesRegex(ValueError,'incomplete or ambiguous'): + phases.verify_trace(output) + + +if __name__ == '__main__': + unittest.main() From e4b8c704002131d074580daa22283d1e8ebb4e87 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sun, 29 Nov 2026 04:55:31 +1100 Subject: [PATCH 20/22] Use conservative order-stratified client intervals --- ci/README.md | 37 ++++++--- ci/automation.just | 4 + ci/inference-client-final.json | 37 +++++++-- ci/inference-client-statistics.md | 79 ++++++++++++++++++++ scripts/inference-client-coverage.py | 77 +++++++++++++++++++ scripts/lib/inference_client_decision.py | 56 ++++++++++---- scripts/lib/inference_client_final.py | 10 +-- scripts/lib/inference_client_registration.py | 4 +- scripts/lib/inference_client_report.py | 4 +- scripts/tests/inference_client_decision.py | 50 +++++++++---- 10 files changed, 303 insertions(+), 55 deletions(-) create mode 100644 ci/inference-client-statistics.md create mode 100644 scripts/inference-client-coverage.py diff --git a/ci/README.md b/ci/README.md index ed7db329..0dfafc42 100644 --- a/ci/README.md +++ b/ci/README.md @@ -333,8 +333,8 @@ offload and mutual completion proofs. For an admitted allocation: just inference-paired qwen3-coder-30b-a3b split cc2a27435e798649a9cb938d600d39722e4a2263 client-pilot ``` -Final acquisition remains unregistered until pilot variance, covariance and arm -durations establish a feasible fixed count under the four-hour lease. The 2% +Final acquisition remains unregistered until order-specific pilot variance, +drift sensitivity and arm durations establish a feasible fixed count under the four-hour lease. The 2% material effect and 1% maximum pointwise interval half-width remain unchanged. The opt-in `client-final` implementation has its own registration in @@ -350,8 +350,14 @@ fixed-width heuristic only. Its `2.5*SD/sqrt(pairs)` width proxy does not simula the realized bootstrap interval and did not preserve the observed split arm-order effect. Its scores are **inadmissible** for final registration; historical estimates remain available without becoming power guarantees. Final acquisition -is hard-disabled until simulation validation of the actual registered interval -procedure is implemented. Counts remain unset. +is hard-disabled. A subsequent coverage audit of the actual fixed-seed procedure +at 16/20/24 pairs found only 91.11%/92.77%/92.26% coverage in 4,096 independent +Gaussian trials per count. Simultaneous 99% Monte Carlo upper bounds were +92.28%/93.83%/93.35%, below the nominal 95%. Thus reproducing this bootstrap +cannot certify positive qualification at those counts. The prospective v3 interval uses a conservative minimum-stratum-df t interval +with unpooled order variances. Its coverage argument, independent numerical checks +and assumptions are in [inference-client-statistics.md](inference-client-statistics.md). +Power validation and fresh cadence-matched evidence remain pending. Counts remain unset. Power evidence must bind the configuration, baseline, pilot source, exact pilot and independent-audit file digests, nine distinct endpoint cells, and the reserved @@ -362,12 +368,14 @@ launched native success cannot close the acceptance criterion. Final time blocks contain one A/A pair and one A/B pair. The count is a multiple of four, and A/A-first versus A/B-first positions are balanced separately within -each AB/BA arm-order stratum. Pointwise percentile intervals use 100,000 paired -resamples **within those fixed equal strata**; order counts cannot fluctuate and -nested requests never become independent units. The equally weighted order -means cancel a constant position effect in both the point estimate and every -resample. This prospective correction does not relabel historical results and -still requires fresh validation. +each AB/BA arm-order stratum. Pointwise v3 intervals use equally weighted order +means, unpooled within-order sample variances, and the conservative t critical +with degrees of freedom equal to the smaller stratum's sample size minus one. +A constant signed order effect cancels in the estimate; unequal order variances +are allowed under independent Gaussian pairs. Drift, changing position effects +and common A/A bias remain outside that coverage proof. Nested requests never +become independent units. This prospective correction does not relabel +historical results and still requires fresh validation. Each endpoint's complete A/A interval must lie inside `[0.99, 1.01]`. Its A/B ratio-scale half-width must be at most 1%. An A/B interval strictly inside @@ -1239,3 +1247,12 @@ never become extra samples. Detailed native sampler spans may be unavailable in a static executable and cannot be inferred from their absence. Debug trace cost is part of this diagnostic, so none of these requests enters sizing or final qualification. Earlier v1 evidence keeps its original scope and labels. + +The coverage audit separately screened every lease-feasible count, without +assuming power is monotone in count: standalone 16/20/24 and split16. The +necessary placebo gate had zero passes in4,096 trials at each count under the +pooled3x Gaussian sensitivity model; the simultaneous one-sided probability +upper bound was0.147%. This is conditional futility evidence, not heterogeneous +variance certification or permission to acquire a final comparison. A positive +power design must account for unequal order-stratum variances, pilot uncertainty, +Monte Carlo multiplicity, drift assumptions, and actual-interval coverage. diff --git a/ci/automation.just b/ci/automation.just index 573699c4..cc21dacd 100644 --- a/ci/automation.just +++ b/ci/automation.just @@ -38,6 +38,10 @@ inference-contracts: inference-client-plan pilot output: @"{{ automation_python }}" scripts/inference-client-plan.py "$@" +[positional-arguments] +inference-client-coverage output: + @"{{ automation_python }}" scripts/inference-client-coverage.py "$@" + inference-publication-test: @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_publication.py diff --git a/ci/inference-client-final.json b/ci/inference-client-final.json index b1676f2d..0c8405a9 100644 --- a/ci/inference-client-final.json +++ b/ci/inference-client-final.json @@ -1,6 +1,6 @@ { - "protocol": "DGX Spark release client paired qualification v2", - "status": "awaiting validated order-aware power and precision resolution; final acquisition prohibited", + "protocol": "DGX Spark release client paired qualification v3", + "status": "blocked: revised interval requires fresh cadence-matched pilot and validated power; acquisition prohibited", "baseline_sha": "cc2a27435e798649a9cb938d600d39722e4a2263", "configurations": { "qwen3-coder-30b-a3b-split": { @@ -31,8 +31,7 @@ 1.01 ], "estimator": "Geometric mean of within-pair candidate/main arm-summary ratios", - "interval": "Pointwise paired percentile bootstrap with fixed equal AB/BA strata; never vary order counts or resample nested requests", - "resamples": 100000, + "interval": "Pointwise conservative minimum-stratum-df t interval for equally weighted balanced AB/BA means with unpooled variances; independent Gaussian pairs required", "seed": 20261129, "schedule": "Alternate AB/BA pair order; randomize balanced A/A-first vs A/B-first positions separately within each order stratum; count must be a multiple of four", "framing_gate": "TPOT requires matching per-request content-event counts across each pair; both arms use terminal usage, no token IDs, and disclose one-token-first-content assumption", @@ -60,12 +59,34 @@ 0.005 ], "historical_inadmissible_ci_width_proxy_factor": 2.5, - "variance_assumption": "Independent Gaussian pilot log ratios; uncertainty union bound over nine endpoints", + "variance_assumption": "Independent Gaussian pairs within each order; separate pilot SD envelopes for 18 endpoint/order cells required before positive admission", "endpoint_dependence": "Arbitrary; marginal failure probabilities added by union bound", "joint_power_target": 0.9, "lease_seconds": 14400, "setup_build_upload_reserve_seconds": 4200, - "method": "order-stratified-bootstrap-simulation-v1", - "validation_status": "NOT IMPLEMENTED: fixed-width proxy scores are inadmissible; final acquisition hard-disabled" - } + "method": "balanced-order-minimum-df-t-simulation-v1", + "validation_status": "BLOCKED: conservative interval implemented; unequal-order variance envelopes, drift sensitivity, actual-procedure power and authenticated replay not validated" + }, + "coverage_audit": { + "procedure": "Superseded v2: 100000 fixed-seed stratified percentile resamples, production ranks2499/97500; integer-weight scalar crosschecks", + "outer_replicates_per_count": 4096, + "counts": [ + 16, + 20, + 24 + ], + "observed_coverage": [ + 0.9111328125, + 0.927734375, + 0.922607421875 + ], + "simultaneous_99pct_mc_upper": [ + 0.9227845074596258, + 0.9382793069824055, + 0.9335099295431615 + ], + "model": "Independent Gaussian pairs, equal variances within balanced AB/BA strata, true log effect0", + "finding": "Superseded nominal95% percentile interval inadmissible at these counts; v3 uses the documented conservative t interval. No final acquisition used v2. Historical measurements and labels unchanged." + }, + "interval_method": "balanced-order-minimum-df-t-v1" } diff --git a/ci/inference-client-statistics.md b/ci/inference-client-statistics.md new file mode 100644 index 00000000..9863ef20 --- /dev/null +++ b/ci/inference-client-statistics.md @@ -0,0 +1,79 @@ +# Prospective client interval, v3 + +Final acquisition is disabled. This method replaces the unactivated v2 +percentile interval prospectively. It does not change historical v1 results, +the 2% material margin, the 1% ratio half-width, or the A/A `[0.99, 1.01]` gate. +The v2 audit found undercoverage even for independent Gaussian pairs. Replaying +an interval exactly is insufficient if that interval has incorrect coverage. + +## Estimator and interval + +For each endpoint, retain independent candidate/main paired log ratios in the +two balanced arm-order strata AB and BA. Each stratum has `m` observations. +Nested requests contribute to one arm summary, never to the pair count. + +Let `xAB`, `xBA` be the sample means and `sAB²`, `sBA²` the unbiased sample +variances. Define + +``` +mu = (xAB + xBA) / 2 +SE = sqrt((sAB² + sBA²) / (4m)) +df = m - 1 +CI95 = exp(mu ± t(0.975, df) * SE) +``` + +This uses the minimum stratum degrees of freedom, not a pooled or approximate +Welch degrees of freedom. The t critical is deliberately conservative for +unequal unknown order variances. A constant signed order penalty cancels in +the equally weighted mean. Within-order sample variances exclude that constant. + +## Coverage argument and assumptions + +Assume mutually independent Gaussian paired log ratios with constant mean and +variance within each order. The two variances may differ arbitrarily. Gaussian +sample means are independent of sample variances. Write the standardized mean +error as `Z ~ Normal(0,1)`. For nonzero total variance, + +``` +estimated_SE² / true_SE² = w*V1 + (1-w)*V2 +V1, V2 ~ chi-square(df)/df +w = sigmaAB² / (sigmaAB² + sigmaBA²) +``` + +For critical `c > 0`, `f(v) = 2*Phi(-c*sqrt(v))` is convex on positive `v`: +`f''(v) = c*phi(c*sqrt(v))*(1+c²*v)/(2*v**1.5) > 0`. +Jensen's inequality gives, pointwise and then in expectation, + +``` +E[f(w*V1 + (1-w)*V2)] <= w*E[f(V1)] + (1-w)*E[f(V2)] = 0.05 +``` + +Thus two-sided coverage is at least 95% under those assumptions; each tail is +at most 2.5% by the same argument or symmetry. The zero-variance limit is exact. +Exponentiation preserves coverage. This is a pointwise endpoint interval; +the all-endpoint non-regression claim requires every endpoint to pass. + +This proof does **not** cover serial dependence, changing arm-position effects, +common A/A bias, heavy tails, or an incorrectly modeled final acquisition cadence. +Eight historical sizing pairs do not establish those assumptions. Before any +positive admission, require fresh cadence-matched evidence, separate per-order +pilot variance envelopes, prospective drift sensitivities, modeled joint power +for the actual gate, and independently authenticated controller replay. Counts +remain unset and the power validator rejects all final acquisitions. + +## Numerical verification + +`just inference-client-coverage OUTPUT` uses pinned NumPy 2.2.6, 200,000 fixed-seed +Gaussian trials at each of 16, 20 and 24 pairs, and seven variance ratios including +one zero variance and 100:1 SD imbalance. It records coverage and both adverse +tail rates, cross-checks vector results against the scalar production interval, +and checks critical values using independent Simpson integration of the t density. +Simulation is a numerical audit of the implementation, not a substitute for the +coverage argument or evidence about real runtime noise. It cannot admit hardware +work or establish performance. + +The [NIST t table](https://www.itl.nist.gov/div898/handbook/eda/section3/eda3672.htm) +provides an independent rounded check of the 0.975 critical values. The production +implementation uses a trigonometric integral recurrence and bisection, requiring +only the Python standard library. The workload schedule still has its own fixed +random seed; interval inference no longer uses bootstrap randomness. diff --git a/scripts/inference-client-coverage.py b/scripts/inference-client-coverage.py new file mode 100644 index 00000000..870c358a --- /dev/null +++ b/scripts/inference-client-coverage.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +"""Numerical audit of the prospective interval; never power/admission evidence.""" + +import argparse +import math +from pathlib import Path + +import numpy as np + +from lib.ci_artifacts import write_json +from lib.inference_client_decision import INTERVAL_METHOD, critical_value, paired_interval + + +def integrated_cdf(critical, df): + # Independent from the production trigonometric recurrence. + steps = 65_536 + dx = critical / steps + constant = math.exp(math.lgamma((df + 1) / 2) - math.lgamma(df / 2)) / math.sqrt(df * math.pi) + def density(x): + return constant * (1 + x * x / df) ** (-(df + 1) / 2) + integral = dx / 3 * (density(0) + density(critical) + + 4 * sum(density((2 * i + 1) * dx) for i in range(steps // 2)) + + 2 * sum(density(2 * i * dx) for i in range(1, steps // 2))) + return .5 + integral + + +def audit(): + if np.__version__ != "2.2.6": + raise ValueError("interval audit requires pinned NumPy 2.2.6") + trials = 200_000 + results = [] + for pairs in (16, 20, 24): + size, df = pairs // 2, pairs // 2 - 1 + critical = critical_value(df) + cdf = integrated_cdf(critical, df) + if abs(cdf - .975) > 1e-12: + raise ValueError("critical value disagrees with independent density integration") + rng = np.random.Generator(np.random.PCG64(20261130 + pairs)) + values = rng.standard_normal((2, size, trials)) + means, variances = values.mean(axis=1), values.var(axis=1, ddof=1) + scenarios = [] + max_error = 0 + for a, b in ((0, 1), (1, 0), (1, 1), (1, 2), (1, 4), (1, 10), (1, 100)): + center = (a * means[0] + b * means[1]) / 2 + half = critical * np.sqrt((a * a * variances[0] + b * b * variances[1]) / (4 * size)) + # Cross-check the simulated decision against the scalar production + # procedure, including the real AB/BA ordering and exponentiation. + for i in range(16): + logs = [float(value) for pair in zip(a * values[0, :, i], b * values[1, :, i]) for value in pair] + scalar = paired_interval(logs) + expected = [center[i] - half[i], center[i] + half[i]] + error = max(abs(math.log(v) - want) for v, want in zip(scalar["ci95"], expected)) + max_error = max(max_error, error) + if error > 1e-12: + raise ValueError("vector audit disagrees with scalar production interval") + scenarios.append({"stratum_sd": [a, b], "covered": int(np.count_nonzero(np.abs(center) <= half)), + "upper_below_truth": int(np.count_nonzero(center + half < 0)), + "lower_above_truth": int(np.count_nonzero(center - half > 0))}) + results.append({"pairs": pairs, "df": df, "critical": critical, "independent_cdf": cdf, + "trials": trials, "scalar_log_bound_max_error": float(max_error), "scenarios": scenarios}) + return {"scope": "Numerical interval audit only; no performance/power/admission claim", + "method": INTERVAL_METHOD, "numpy": np.__version__, "rng": "PCG64; seed=20261130+pairs", + "assumptions": "Independent Gaussian order strata; unequal variances; no drift/heavy-tail claim", + "results": results} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("output", type=Path) + args = parser.parse_args() + result = audit() + write_json(args.output, result) + print(f'{result["method"]}: independent numerical checks completed; not qualification or admission evidence') + + +if __name__ == "__main__": + main() diff --git a/scripts/lib/inference_client_decision.py b/scripts/lib/inference_client_decision.py index d72896e6..83b1d3a4 100644 --- a/scripts/lib/inference_client_decision.py +++ b/scripts/lib/inference_client_decision.py @@ -1,34 +1,60 @@ """Prospective client decisions; historical paired-probe v1 stays unchanged.""" import math -import random -from statistics import fmean +from functools import lru_cache +from statistics import fmean, variance EFFECT = 0.02 PRECISION = 0.01 PLACEBO = (0.99, 1.01) -RESAMPLES = 100_000 -SEED = 20261129 +INTERVAL_METHOD = "balanced-order-minimum-df-t-v1" -def paired_interval(log_ratios, resamples=RESAMPLES, seed=SEED, orders=None): - """Resample pairs within fixed AB/BA strata, preserving balanced arm order.""" - if (len(log_ratios) < 4 or len(log_ratios) % 2 or type(resamples) is not int or resamples < 1000 +@lru_cache(maxsize=128) +def critical_value(df): + """Two-sided 95% t critical, integrating cos**(df-1) after substitution.""" + if type(df) is not int or not 1 <= df <= 50_000: + raise ValueError("client t interval requires bounded positive integer degrees of freedom") + constant = math.exp(math.lgamma((df + 1) / 2) - math.lgamma(df / 2)) / math.sqrt(math.pi) + low, high = 0., 16. + for _ in range(64): + value = (low + high) / 2 + theta = math.atan(value / math.sqrt(df)) + sine, cosine = math.sin(theta), math.cos(theta) + integral = theta if df % 2 else sine + for power in range(2 if df % 2 else 3, df, 2): + integral = (sine * cosine ** (power - 1) + (power - 1) * integral) / power + if .5 + constant * integral < .975: + low = value + else: + high = value + return high + + +def paired_interval(log_ratios, orders=None): + """Equal order means; unpooled SE and conservative minimum-stratum df. + + Gaussian independent pairs are required; unequal order variances are allowed. + See ci/inference-client-statistics.md for the coverage proof and limitations. + """ + if (len(log_ratios) < 4 or len(log_ratios) % 2 or any(type(v) not in (int, float) or not math.isfinite(v) for v in log_ratios)): raise ValueError("client interval requires finite independent paired blocks") orders = orders if orders is not None else ["ab" if i % 2 == 0 else "ba" for i in range(len(log_ratios))] if len(orders) != len(log_ratios) or set(orders) != {"ab", "ba"} or orders.count("ab") != orders.count("ba"): raise ValueError("client interval requires equally represented AB and BA strata") groups = [[v for v, order in zip(log_ratios, orders) if order == name] for name in ("ab", "ba")] - rng = random.Random(seed) size = len(groups[0]) - draws = sorted(fmean(v[min(int(rng.random() * size), size - 1)] for v in groups for _ in range(size)) - for _ in range(resamples)) - low = draws[int(0.025 * (resamples - 1))] - high = draws[math.ceil(0.975 * (resamples - 1))] - return {"ratio": math.exp(fmean(log_ratios)), "ci95": [math.exp(low), math.exp(high)], - "independent_pairs": len(log_ratios), "resamples": resamples, "seed": seed, - "orders": orders, "resampling": "fixed balanced AB/BA strata", + center = fmean(fmean(group) for group in groups) + variances = [variance(group) for group in groups] + se = math.sqrt(sum(variances) / (4 * size)) + critical = critical_value(size - 1) + width = critical * se + return {"ratio": math.exp(center), "ci95": [math.exp(center - width), math.exp(center + width)], + "independent_pairs": len(log_ratios), "orders": orders, "method": INTERVAL_METHOD, + "degrees_of_freedom": size - 1, "critical_value": critical, + "log_standard_error": se, "within_order_log_variances": variances, + "assumptions": "independent Gaussian pairs within each order; arbitrary unequal order variances", "estimator": "equally weighted AB/BA means of within-pair log ratios"} diff --git a/scripts/lib/inference_client_final.py b/scripts/lib/inference_client_final.py index 7a057b14..b7658fcc 100644 --- a/scripts/lib/inference_client_final.py +++ b/scripts/lib/inference_client_final.py @@ -7,7 +7,7 @@ from .ci_artifacts import read_json, write_json from .inference_client import ROOT, measure as client_measure, verify as client_verify -from .inference_client_decision import EFFECT, PLACEBO, PRECISION, RESAMPLES, all_endpoints, decide, paired_interval +from .inference_client_decision import EFFECT, PLACEBO, PRECISION, INTERVAL_METHOD, all_endpoints, decide, paired_interval from .inference_probe import measure as phase_measure, validate_evidence from .inference_client_registration import validate_power_evidence, validate_placement @@ -23,7 +23,7 @@ def schedule(baseline, candidate, configuration, design=None): config = design["configurations"].get(configuration, {}) pairs = config.get("pairs_per_phase") fixed = {"material_effect": EFFECT, "maximum_pointwise_ci95_ratio_half_width": PRECISION, - "placebo_ci95_band": list(PLACEBO), "resamples": RESAMPLES, + "placebo_ci95_band": list(PLACEBO), "interval_method": INTERVAL_METHOD, "primary_metrics": {"ttft_ms": "lower", "tpot_ms": "lower", "request_tok_s": "higher"}, "shapes": [0, 1, 2]} if any(design.get(k) != v for k, v in fixed.items()): @@ -116,7 +116,7 @@ def validate_samples(samples, design): raise ValueError("final client summary metric must be positive and finite") -def summarize(evidence, design=None, resamples=None): +def summarize(evidence, design=None): design = registration() if design is None else design roles = {"leader", "worker"} if evidence["configuration"].endswith("-split") else {"leader"} placements, builds = evidence["placements"], evidence["builds"] @@ -163,7 +163,7 @@ def summarize(evidence, design=None, resamples=None): framing_ok &= relevant(a) == relevant(b) values = [v["client"]["summaries"][shape][metric] for v in (a, b)] logs.append(math.log(values[1] / values[0])) - intervals[phase] = paired_interval(logs, resamples or design["resamples"], design["seed"]) + intervals[phase] = paired_interval(logs) decision = decide(intervals["ab"], intervals["aa"], direction) if metric == "tpot_ms" and not framing_ok: decision.update(claim_verdict="UNPROVEN", comparison="incompatible_event_framing") @@ -179,7 +179,7 @@ def summarize(evidence, design=None, resamples=None): by_pair[f"client-{phase}", r, "a"]["phases"][shape][metric]) for r in range(count)] for phase in ("aa", "ab")} diagnostics.append({"shape": shape, "metric": metric, "scope": "server phase diagnostic", - **{phase: paired_interval(values, resamples or design["resamples"], design["seed"]) + **{phase: paired_interval(values) for phase, values in ratios.items()}}) return {"claim_verdict": all_endpoints(decisions), "client_endpoints": decisions, "server_phase_diagnostics": diagnostics, "scope": design["scope"]} diff --git a/scripts/lib/inference_client_registration.py b/scripts/lib/inference_client_registration.py index 5001755f..6f913e35 100644 --- a/scripts/lib/inference_client_registration.py +++ b/scripts/lib/inference_client_registration.py @@ -4,14 +4,14 @@ from .ci_artifacts import digest, read_json -POWER_METHOD = "order-stratified-bootstrap-simulation-v1" +POWER_METHOD = "balanced-order-minimum-df-t-simulation-v1" def validate_simulation(plan): # The former fixed-width score omitted random realized interval widths. # Keep acquisition disabled until the actual registered interval procedure # has an independently checked simulation validator. No config flag bypass. - raise ValueError("final bootstrap power simulation validation is not implemented; acquisition prohibited") + raise ValueError("final t-interval power simulation validation is not implemented; acquisition prohibited") def validate_power_evidence(root, configuration, baseline, config): diff --git a/scripts/lib/inference_client_report.py b/scripts/lib/inference_client_report.py index 4df5adbd..656231f1 100644 --- a/scripts/lib/inference_client_report.py +++ b/scripts/lib/inference_client_report.py @@ -14,7 +14,9 @@ def render(evidence): f'Main `{evidence["baseline_sha"]}` · candidate `{evidence["source_sha"]}`', "", f'Client non-regression claim: **{summary["claim_verdict"]}**. {summary["scope"]}.', "", "Ratios are candidate/main in each metric's native direction. Intervals are pointwise 95%,", - "bootstrapped over fresh paired server blocks. Nested requests are not independent pairs.", "", + "conservative t intervals over equally weighted AB/BA paired log means with unpooled variances.", + "They assume independent Gaussian pairs; drift and heavy tails are not covered.", + "Nested requests are not independent pairs.", "", "| Paragraphs | Client metric | Main | Candidate | A/B ratio [CI95] | A/A ratio [CI95] | Half-width | Registered decision |", "| ---: | --- | ---: | ---: | --- | --- | ---: | --- |"] names = {"ttft_ms": "TTFT ms (lower)", "tpot_ms": "TPOT ms (lower)", diff --git a/scripts/tests/inference_client_decision.py b/scripts/tests/inference_client_decision.py index 0da5f887..1a7b7663 100644 --- a/scripts/tests/inference_client_decision.py +++ b/scripts/tests/inference_client_decision.py @@ -7,7 +7,7 @@ from tempfile import TemporaryDirectory from unittest.mock import patch -from lib.inference_client_decision import all_endpoints, decide, paired_interval +from lib.inference_client_decision import all_endpoints, critical_value, decide, paired_interval from lib import inference_client_final as final from lib.inference_client_report import render from lib.ci_artifacts import digest, write_json @@ -35,7 +35,7 @@ def registered_design(): path = final.ROOT / (name + ".json") write_json(path, document) refs[name] = {"path": path.name, "sha256": digest(path)} - plan = {"status": "feasible", "method": "order-stratified-bootstrap-simulation-v1", + plan = {"status": "feasible", "method": "balanced-order-minimum-df-t-simulation-v1", "eligible_for_registration": True, "configuration": config, "baseline_sha": design["baseline_sha"], "pilot_source_sha": pilot["source_sha"], "placements": placements, "reserved_nodes": nodes, "pilot_receipt_sha256": refs["pilot"]["sha256"], "independent_audit_sha256": refs["audit"]["sha256"], @@ -55,7 +55,7 @@ def setUp(self): self.enterContext(patch.object(registration, "validate_simulation", return_value=None)) def test_exact_equality_is_a_precise_within_tolerance_result(self): - interval = paired_interval([0] * 8, resamples=1000) + interval = paired_interval([0] * 8) self.assertEqual(interval["ci95"], [1, 1]) for direction in ("higher", "lower"): result = decide(interval, interval, direction) @@ -90,23 +90,45 @@ def test_clear_regression_is_reported_even_when_interval_is_wide(self): self.assertEqual(result["claim_verdict"], "FAIL") self.assertFalse(result["precision_met"]) - def test_bootstrap_preserves_pairs_and_does_not_multiply_nested_requests(self): + def test_interval_preserves_pairs_and_does_not_multiply_nested_requests(self): values = [math.log(v) for v in (.99, 1, 1.01, 1.02, .98, 1.01, 1, .99)] - first = paired_interval(values, resamples=1000) - self.assertEqual(first, paired_interval(values, resamples=1000)) + first = paired_interval(values) + self.assertEqual(first, paired_interval(values)) self.assertEqual(first["independent_pairs"], 8) self.assertLess(first["ci95"][0], first["ratio"]) self.assertGreater(first["ci95"][1], first["ratio"]) with self.assertRaises(ValueError): - paired_interval([0, 0, 0], resamples=1000) + paired_interval([0, 0, 0]) - def test_constant_position_penalty_is_cancelled_in_every_balanced_resample(self): + def test_constant_position_penalty_is_cancelled_in_balanced_order_means(self): penalty = math.log(1.06) - result = paired_interval([penalty, -penalty] * 8, resamples=1000) + result = paired_interval([penalty, -penalty] * 8) self.assertEqual(result["ratio"], 1) self.assertEqual(result["ci95"], [1, 1]) with self.assertRaisesRegex(ValueError, "strata"): - paired_interval([0] * 8, resamples=1000, orders=["ab"] * 8) + paired_interval([0] * 8, orders=["ab"] * 8) + + def test_minimum_df_criticals_match_independent_student_tables(self): + # NIST's 0.975 column, rounded to three decimals; includes both parity + # branches of the production integral recurrence and its extreme df=1. + for df, expected in ((1, 12.706), (2, 4.303), (3, 3.182), (7, 2.365), + (9, 2.262), (11, 2.201), (30, 2.042)): + self.assertLess(abs(critical_value(df) - expected), .0005) + for df in (0, True, 1.5, 50_001): + with self.assertRaises(ValueError): + critical_value(df) + + def test_unequal_variances_use_unpooled_se_and_minimum_stratum_df(self): + logs = [value for pair in zip([0, .01, .02, .03], [0, -.02, -.04, -.06]) for value in pair] + result = paired_interval(logs) + # Independent hand calculation: df=3, mean=-.0075, SE=sqrt(1/19200). + half = 3.182446305284263 * math.sqrt(1 / 19200) + self.assertEqual(result["degrees_of_freedom"], 3) + self.assertAlmostEqual(math.log(result["ci95"][0]), -.0075 - half, places=12) + self.assertAlmostEqual(math.log(result["ci95"][1]), -.0075 + half, places=12) + shifted = paired_interval([v + (.1 if i % 2 == 0 else -.1) for i, v in enumerate(logs)]) + for before, after in zip(result["ci95"], shifted["ci95"]): + self.assertAlmostEqual(before, after, places=12) def test_touching_loss_margin_does_not_establish_strict_non_regression(self): self.assertEqual(decide(ci(.98, 1), ci(1, 1), "higher")["claim_verdict"], "UNPROVEN") @@ -164,7 +186,7 @@ def test_final_summary_reports_phase_losses_without_changing_client_scope(self): "input_tokens": {f"shape-{s}": 200 for s in range(3)}, "phases": [ {"shape": s, "prefill_ms": 100 * phase_slow, "decode_ms": 200, "prompt_tokens": 200} for s in range(3)]}}) - result = final.summarize(evidence, design, resamples=1000) + result = final.summarize(evidence, design) self.assertEqual(result["claim_verdict"], "PASS") self.assertEqual(len(result["client_endpoints"]), 9) self.assertAlmostEqual(result["server_phase_diagnostics"][0]["ab"]["ratio"], 1.1) @@ -175,7 +197,7 @@ def test_final_summary_reports_phase_losses_without_changing_client_scope(self): self.assertIn("client pass does not prove server-phase non-regression", report) changed = copy.deepcopy(evidence) changed["runs"][0]["samples"]["framing"]["r0-s0-measured"] = 64 - result = final.summarize(changed, design, resamples=1000) + result = final.summarize(changed, design) self.assertEqual(result["claim_verdict"], "UNPROVEN") self.assertTrue(any(r["comparison"] == "incompatible_event_framing" for r in result["client_endpoints"])) self.assertTrue(all(r["claim_verdict"] == "PASS" for r in result["client_endpoints"] @@ -183,7 +205,7 @@ def test_final_summary_reports_phase_losses_without_changing_client_scope(self): changed = copy.deepcopy(evidence) changed["builds"][0]["main"]["stack_commit"] = candidate with self.assertRaisesRegex(ValueError, "source identity"): - final.summarize(changed, design, resamples=1000) + final.summarize(changed, design) def test_power_receipts_reject_wrong_baseline_configuration_or_tampering(self): for field, value in (("configuration", "other"), ("baseline_sha", "d" * 40)): @@ -201,7 +223,7 @@ def test_power_receipts_reject_wrong_baseline_configuration_or_tampering(self): class ProductionFenceTests(unittest.TestCase): def test_actual_simulation_validation_is_required_before_any_real_final_admission(self): with self.assertRaisesRegex(ValueError, "not implemented; acquisition prohibited"): - registration.validate_simulation({"method": "order-stratified-bootstrap-simulation-v1"}) + registration.validate_simulation({"method": "balanced-order-minimum-df-t-simulation-v1"}) if __name__ == "__main__": From 249f33bc654d9e8e8c29022ee664265661f9ba86 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sun, 29 Nov 2026 05:04:38 +1100 Subject: [PATCH 21/22] Screen infeasible qualification counts analytically --- ci/README.md | 7 ++- ci/automation.just | 5 ++ ci/inference-client-final.json | 63 ++++++++++++++++++++-- ci/inference-client-statistics.md | 41 ++++++++++++-- scripts/inference-client-coverage.py | 2 +- scripts/inference-client-futility.py | 24 +++++++++ scripts/lib/inference_client_decision.py | 33 +++++------- scripts/lib/inference_client_final.py | 6 ++- scripts/lib/inference_client_futility.py | 60 +++++++++++++++++++++ scripts/tests/inference_client_decision.py | 23 ++++++-- scripts/tests/inference_client_futility.py | 36 +++++++++++++ 11 files changed, 267 insertions(+), 33 deletions(-) create mode 100644 scripts/inference-client-futility.py create mode 100644 scripts/lib/inference_client_futility.py create mode 100644 scripts/tests/inference_client_futility.py diff --git a/ci/README.md b/ci/README.md index 0dfafc42..c4849e9e 100644 --- a/ci/README.md +++ b/ci/README.md @@ -357,7 +357,12 @@ Gaussian trials per count. Simultaneous 99% Monte Carlo upper bounds were cannot certify positive qualification at those counts. The prospective v3 interval uses a conservative minimum-stratum-df t interval with unpooled order variances. Its coverage argument, independent numerical checks and assumptions are in [inference-client-statistics.md](inference-client-statistics.md). -Power validation and fresh cadence-matched evidence remain pending. Counts remain unset. +The analytic necessary-calibration screen (`just inference-client-futility PILOT OUTPUT`) +also excludes the present full lease grid under the declared historical 3x Gaussian +noise sensitivity. Even granting zero-width intervals, its maximum necessary A/A +probabilities are only 30.31% standalone and 17.93% split, below the 90% joint-power +target. This is conditional futility evidence, not a measured regression. Diagnosis, +fresh cadence-matched evidence and power validation remain pending. Counts remain unset. Power evidence must bind the configuration, baseline, pilot source, exact pilot and independent-audit file digests, nine distinct endpoint cells, and the reserved diff --git a/ci/automation.just b/ci/automation.just index cc21dacd..952e54d9 100644 --- a/ci/automation.just +++ b/ci/automation.just @@ -21,6 +21,7 @@ inference-contracts: @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client_decision.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client_power.py + @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client_futility.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client_noise.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_thread_affinity.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_stream_capture.py @@ -42,6 +43,10 @@ inference-client-plan pilot output: inference-client-coverage output: @"{{ automation_python }}" scripts/inference-client-coverage.py "$@" +[positional-arguments] +inference-client-futility pilot output: + @"{{ automation_python }}" scripts/inference-client-futility.py "$@" + inference-publication-test: @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_publication.py diff --git a/ci/inference-client-final.json b/ci/inference-client-final.json index 0c8405a9..ea796588 100644 --- a/ci/inference-client-final.json +++ b/ci/inference-client-final.json @@ -1,6 +1,6 @@ { "protocol": "DGX Spark release client paired qualification v3", - "status": "blocked: revised interval requires fresh cadence-matched pilot and validated power; acquisition prohibited", + "status": "blocked: historical noise sensitivity excludes current lease grid; fresh diagnosis/pilot and validated power required", "baseline_sha": "cc2a27435e798649a9cb938d600d39722e4a2263", "configurations": { "qwen3-coder-30b-a3b-split": { @@ -48,7 +48,6 @@ "power_planning": { "minimum_pairs": 16, "pilot_pairs": 8, - "sd_upper_factor": 3, "ab_sd_factors": [ 1, 1.5, @@ -65,7 +64,8 @@ "lease_seconds": 14400, "setup_build_upload_reserve_seconds": 4200, "method": "balanced-order-minimum-df-t-simulation-v1", - "validation_status": "BLOCKED: conservative interval implemented; unequal-order variance envelopes, drift sensitivity, actual-procedure power and authenticated replay not validated" + "validation_status": "BLOCKED: conservative interval implemented; unequal-order variance envelopes, drift sensitivity, actual-procedure power and authenticated replay not validated", + "historical_futility_pooled_sd_factor": 3 }, "coverage_audit": { "procedure": "Superseded v2: 100000 fixed-seed stratified percentile resamples, production ranks2499/97500; integer-weight scalar crosschecks", @@ -88,5 +88,60 @@ "model": "Independent Gaussian pairs, equal variances within balanced AB/BA strata, true log effect0", "finding": "Superseded nominal95% percentile interval inadmissible at these counts; v3 uses the documented conservative t interval. No final acquisition used v2. Historical measurements and labels unchanged." }, - "interval_method": "balanced-order-minimum-df-t-v1" + "interval_method": "balanced-order-minimum-df-t-v1", + "critical_values": { + "7": 2.364625, + "9": 2.262158, + "11": 2.200986 + }, + "analytic_futility_audit": { + "qwen35-4b-standalone": { + "method": "gaussian-aa-center-necessary-condition-v1", + "status": "conditional_futility", + "eligible_for_registration": false, + "source_sha": "7895aca17e09153a00debd4e5ae5672431254ad1", + "baseline_sha": "cc2a27435e798649a9cb938d600d39722e4a2263", + "pooled_sensitivity_sd": 0.12578296626721047, + "necessary_endpoint": { + "shape": 2, + "metric": "tpot_ms" + }, + "lease_grid": [ + { + "pairs": 16, + "necessary_aa_probability_upper": 0.24952893079783586 + }, + { + "pairs": 20, + "necessary_aa_probability_upper": 0.277826252966158 + }, + { + "pairs": 24, + "necessary_aa_probability_upper": 0.3030870431017274 + } + ], + "pilot_sha256": "80dd9a97a944ec61267378a4f0fc8ba4615fd11b861d4145cc838933a514eec3", + "audit_sha256": "4109bee1a235328bb24b7e55a42eacbb01e8ea88c153f1eba21d9da24a6e30ee" + }, + "qwen3-coder-30b-a3b-split": { + "method": "gaussian-aa-center-necessary-condition-v1", + "status": "conditional_futility", + "eligible_for_registration": false, + "source_sha": "7895aca17e09153a00debd4e5ae5672431254ad1", + "baseline_sha": "cc2a27435e798649a9cb938d600d39722e4a2263", + "pooled_sensitivity_sd": 0.17651447964577716, + "necessary_endpoint": { + "shape": 0, + "metric": "ttft_ms" + }, + "lease_grid": [ + { + "pairs": 16, + "necessary_aa_probability_upper": 0.17927898258170713 + } + ], + "pilot_sha256": "047c763e49003ff0c4833ce356a95ab37fc279203c0ab53a55247b22638da94b", + "audit_sha256": "040e8360313b5477c2b393b0b78d283b5d72aaebae74fb204edba5f6f84085d7" + } + } } diff --git a/ci/inference-client-statistics.md b/ci/inference-client-statistics.md index 9863ef20..e68b32fe 100644 --- a/ci/inference-client-statistics.md +++ b/ci/inference-client-statistics.md @@ -52,6 +52,11 @@ Thus two-sided coverage is at least 95% under those assumptions; each tail is at most 2.5% by the same argument or symmetry. The zero-variance limit is exact. Exponentiation preserves coverage. This is a pointwise endpoint interval; the all-endpoint non-regression claim requires every endpoint to pass. +At an adverse non-regression boundary, a false pass requires the corresponding +one-sided error; its probability is at most 2.5% under the model. If any of the +nine endpoints violates its margin, a false all-endpoint claim must pass that +endpoint, so the all-pass rule inherits this bound regardless of endpoint +dependence. This does not give simultaneous 95% coverage to the displayed CIs. This proof does **not** cover serial dependence, changing arm-position effects, common A/A bias, heavy tails, or an incorrectly modeled final acquisition cadence. @@ -74,6 +79,36 @@ work or establish performance. The [NIST t table](https://www.itl.nist.gov/div898/handbook/eda/section3/eda3672.htm) provides an independent rounded check of the 0.975 critical values. The production -implementation uses a trigonometric integral recurrence and bisection, requiring -only the Python standard library. The workload schedule still has its own fixed -random seed; interval inference no longer uses bootstrap randomness. +implementation uses upward-rounded six-decimal constants: `2.364625`, +`2.262158`, `2.200986` for df 7, 9 and 11 respectively. The independent density +audit checks that the exact critical lies between each stored value minus one +micro-unit and the stored value. Small offline fixtures also have verified +criticals for df 1, 2 and 3. Unsupported counts fail before acquisition; a new +count requires an explicitly verified critical. The workload schedule still has +its own fixed random seed; interval inference no longer uses bootstrap randomness. + +## Analytic futility screen + +`just inference-client-futility PILOT OUTPUT` reconstructs the historical pooled +within-order SD from all nine endpoints of the audited eight-pair sizing pilot, +then applies the declared 3x equal-variance Gaussian sensitivity. It reconstructs +the complete four-hour lease count grid from observed arm durations and the +historical diagnostic allowance. It cannot authorize acquisition. + +Because the v3 interval contains its estimate, A/A calibration necessarily +requires `log(.99) <= estimated_mu <= log(1.01)`, even granting a zero-width CI. +At common within-order model SD `sigma` and total count `n`, its probability is + +``` +Phi(log(1.01)*sqrt(n)/sigma) - Phi(log(.99)*sqrt(n)/sigma) +``` + +This is an upper bound on the complete A/A gate and hence on all-endpoint joint +power. The largest historical lease-feasible counts give bounds of about 30.31% +for standalone (24 pairs, model SD 0.125783) and 17.93% for split (16 pairs, model +SD 0.176514). Smaller counts give smaller necessary-event +probabilities, so none can meet 90% joint power under that sensitivity. These are +conditional analytic diagnostics, not a measured regression or a confidence +statement about the true runtime variance. A heterogeneous envelope containing +this parameter point cannot establish robust power. A count surviving this +screen would still need full joint-power validation and authenticated replay. diff --git a/scripts/inference-client-coverage.py b/scripts/inference-client-coverage.py index 870c358a..0a944ce7 100644 --- a/scripts/inference-client-coverage.py +++ b/scripts/inference-client-coverage.py @@ -33,7 +33,7 @@ def audit(): size, df = pairs // 2, pairs // 2 - 1 critical = critical_value(df) cdf = integrated_cdf(critical, df) - if abs(cdf - .975) > 1e-12: + if cdf < .975 - 1e-14 or integrated_cdf(critical - 1e-6, df) > .975 + 1e-14: raise ValueError("critical value disagrees with independent density integration") rng = np.random.Generator(np.random.PCG64(20261130 + pairs)) values = rng.standard_normal((2, size, trials)) diff --git a/scripts/inference-client-futility.py b/scripts/inference-client-futility.py new file mode 100644 index 00000000..3d1841f6 --- /dev/null +++ b/scripts/inference-client-futility.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python3 +"""Screen an audited sizing pilot analytically; cannot authorize final acquisition.""" + +import argparse +from pathlib import Path + +from lib.ci_artifacts import digest, read_json, write_json +from lib.inference_client_futility import screen + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("pilot", type=Path) + parser.add_argument("output", type=Path) + args = parser.parse_args() + pilot, audit = args.pilot / "client-pilot.json", args.pilot / "raw-evidence-verified.json" + result = screen(read_json(pilot), read_json(audit)) + result.update(pilot_sha256=digest(pilot), audit_sha256=digest(audit)) + write_json(args.output, result) + print(f'{result["configuration"]}: {result["status"]}; not positive power or admission evidence') + + +if __name__ == "__main__": + main() diff --git a/scripts/lib/inference_client_decision.py b/scripts/lib/inference_client_decision.py index 83b1d3a4..760543df 100644 --- a/scripts/lib/inference_client_decision.py +++ b/scripts/lib/inference_client_decision.py @@ -1,7 +1,6 @@ """Prospective client decisions; historical paired-probe v1 stays unchanged.""" import math -from functools import lru_cache from statistics import fmean, variance EFFECT = 0.02 @@ -10,25 +9,18 @@ INTERVAL_METHOD = "balanced-order-minimum-df-t-v1" -@lru_cache(maxsize=128) +# Upward-rounded 0.975 criticals. The first three support small offline fixtures; +# df7/9/11 cover the current full lease-feasible grid. A different count requires +# a prospectively verified critical, not an implicit numerical extrapolation. +CRITICAL_VALUES = {1: 12.706205, 2: 4.302653, 3: 3.182447, + 7: 2.364625, 9: 2.262158, 11: 2.200986} + + def critical_value(df): - """Two-sided 95% t critical, integrating cos**(df-1) after substitution.""" - if type(df) is not int or not 1 <= df <= 50_000: - raise ValueError("client t interval requires bounded positive integer degrees of freedom") - constant = math.exp(math.lgamma((df + 1) / 2) - math.lgamma(df / 2)) / math.sqrt(math.pi) - low, high = 0., 16. - for _ in range(64): - value = (low + high) / 2 - theta = math.atan(value / math.sqrt(df)) - sine, cosine = math.sin(theta), math.cos(theta) - integral = theta if df % 2 else sine - for power in range(2 if df % 2 else 3, df, 2): - integral = (sine * cosine ** (power - 1) + (power - 1) * integral) / power - if .5 + constant * integral < .975: - low = value - else: - high = value - return high + """Conservative fixed critical; independent density checks live in the audit.""" + if type(df) is not int or df not in CRITICAL_VALUES: + raise ValueError("client t interval requires prospectively verified degrees of freedom") + return CRITICAL_VALUES[df] def paired_interval(log_ratios, orders=None): @@ -53,7 +45,8 @@ def paired_interval(log_ratios, orders=None): return {"ratio": math.exp(center), "ci95": [math.exp(center - width), math.exp(center + width)], "independent_pairs": len(log_ratios), "orders": orders, "method": INTERVAL_METHOD, "degrees_of_freedom": size - 1, "critical_value": critical, - "log_standard_error": se, "within_order_log_variances": variances, + "log_standard_error": se, "degenerate_estimated_se": se == 0, + "critical_rounding": "upward to six decimals", "within_order_log_variances": variances, "assumptions": "independent Gaussian pairs within each order; arbitrary unequal order variances", "estimator": "equally weighted AB/BA means of within-pair log ratios"} diff --git a/scripts/lib/inference_client_final.py b/scripts/lib/inference_client_final.py index b7658fcc..90eea2c8 100644 --- a/scripts/lib/inference_client_final.py +++ b/scripts/lib/inference_client_final.py @@ -7,7 +7,7 @@ from .ci_artifacts import read_json, write_json from .inference_client import ROOT, measure as client_measure, verify as client_verify -from .inference_client_decision import EFFECT, PLACEBO, PRECISION, INTERVAL_METHOD, all_endpoints, decide, paired_interval +from .inference_client_decision import EFFECT, PLACEBO, PRECISION, INTERVAL_METHOD, all_endpoints, critical_value, decide, paired_interval from .inference_probe import measure as phase_measure, validate_evidence from .inference_client_registration import validate_power_evidence, validate_placement @@ -24,6 +24,7 @@ def schedule(baseline, candidate, configuration, design=None): pairs = config.get("pairs_per_phase") fixed = {"material_effect": EFFECT, "maximum_pointwise_ci95_ratio_half_width": PRECISION, "placebo_ci95_band": list(PLACEBO), "interval_method": INTERVAL_METHOD, + "critical_values": {str(df): critical_value(df) for df in (7, 9, 11)}, "primary_metrics": {"ttft_ms": "lower", "tpot_ms": "lower", "request_tok_s": "higher"}, "shapes": [0, 1, 2]} if any(design.get(k) != v for k, v in fixed.items()): @@ -31,6 +32,9 @@ def schedule(baseline, candidate, configuration, design=None): if (design["status"] != "registered" or baseline != design["baseline_sha"] or type(pairs) is not int or pairs < 16 or pairs % 4 or not config.get("planning_evidence")): raise ValueError("final client count and power plan must be registered before acquisition") + # Reject an unverified critical before reservation/server starts, rather + # than discovering an unsupported count during final summary collection. + critical_value(pairs // 2 - 1) plan = config["planning_evidence"] validate_power_evidence(ROOT, configuration, baseline, config) scenarios = {(s["candidate_loss"], s["ab_sd_factor"]): s["modeled_joint_power_lower_bound"] diff --git a/scripts/lib/inference_client_futility.py b/scripts/lib/inference_client_futility.py new file mode 100644 index 00000000..922d0069 --- /dev/null +++ b/scripts/lib/inference_client_futility.py @@ -0,0 +1,60 @@ +"""Analytic necessary-calibration screen; never positive power/admission evidence.""" + +import math +from statistics import NormalDist, variance + +from .inference_client_decision import PLACEBO + + +def mean_in_band_upper(sd, pairs): + """A/A passing requires its center in-band even with zero interval width.""" + if (type(sd) not in (int, float) or not math.isfinite(sd) or sd <= 0 + or type(pairs) is not int or pairs <= 0): + raise ValueError("futility requires positive Gaussian SD and pair count") + se = sd / math.sqrt(pairs) + normal = NormalDist() + probability = normal.cdf(math.log(PLACEBO[1]) / se) - normal.cdf(math.log(PLACEBO[0]) / se) + return min(1., probability + 1e-12) # outward floating-point reserve + + +def screen(evidence, proof): + if (proof.get("all_raw_quality_identity_gates") != "verified" or proof.get("independent_pairs") != 8 + or any(proof.get(k) != evidence.get(k) for k in ("configuration", "source_sha", "baseline_sha"))): + raise ValueError("futility requires an identity-matched independently audited eight-pair pilot") + endpoints = proof["summary"]["endpoints"] + expected = {(s, m) for s in range(3) for m in ("ttft_ms", "tpot_ms", "request_tok_s")} + if len(endpoints) != 9 or {(e["shape"], e["metric"]) for e in endpoints} != expected: + raise ValueError("futility requires all nine distinct pilot endpoints") + models = [] + for endpoint in endpoints: + logs = endpoint["paired_log_ratios"] + if len(logs) != 8 or any(type(v) not in (int, float) or not math.isfinite(v) for v in logs): + raise ValueError("futility requires eight finite independent log ratios per endpoint") + # Historical equal-variance sensitivity only: pooled within-order df=6. + # Constant signed order offsets are excluded from residual variability. + sd = 3 * math.sqrt((variance(logs[::2]) + variance(logs[1::2])) / 2) + models.append((sd, endpoint)) + sd, endpoint = max(models, key=lambda row: row[0]) + arm = max(r["arm_duration_s"] for r in evidence["runs"]) + phase = max(2 * sum(s["e2e_ms"] for s in r["samples"]["samples"]) / 1000 for r in evidence["runs"]) + if any(not math.isfinite(v) or v <= 0 for v in (arm, phase)): + raise ValueError("futility requires observed positive arm and diagnostic durations") + limit = int((14400 - 4200) / (4 * (arm + phase))) + counts = [{"pairs": n, "necessary_aa_probability_upper": mean_in_band_upper(sd, n)} + for n in range(16, limit + 1, 4)] + excluded = bool(counts) and all(c["necessary_aa_probability_upper"] < .9 for c in counts) + return {"method": "gaussian-aa-center-necessary-condition-v1", "eligible_for_registration": False, + "status": "conditional_futility" if excluded else "not_excluded_by_necessary_screen", + **{k: evidence[k] for k in ("source_sha", "baseline_sha", "configuration")}, + "necessary_endpoint": {k: endpoint[k] for k in ("shape", "metric")}, + "pooled_sensitivity_sd": sd, "pooled_residual_df": 6, "historical_sd_factor": 3, + "lease_grid": counts, "arm_duration_upper_s": arm, "phase_allowance_s": phase, + "lease_s": 14400, "setup_reserve_s": 4200, "joint_power_target": .9, + "numeric_probability_reserve": 1e-12, + "formula": "Phi(log(1.01)*sqrt(n)/sigma)-Phi(log(.99)*sqrt(n)/sigma)", + "limitations": ["Conditional on independent Gaussian pairs with equal order variances at the stated SD", + "Historical duration allowance may omit final-cadence effects; not positive feasibility proof", + "Pooled sensitivity is not a simultaneous heterogeneous pilot variance envelope", + "A surviving count is not certified; a zero pilot SD cannot establish zero true variability", + "No Monte Carlo approximation; floating-point reserve is not an interval-arithmetic proof", + "No measured regression, changed threshold, final-run data or acquisition permission"]} diff --git a/scripts/tests/inference_client_decision.py b/scripts/tests/inference_client_decision.py index 1a7b7663..cb616a40 100644 --- a/scripts/tests/inference_client_decision.py +++ b/scripts/tests/inference_client_decision.py @@ -112,9 +112,9 @@ def test_minimum_df_criticals_match_independent_student_tables(self): # NIST's 0.975 column, rounded to three decimals; includes both parity # branches of the production integral recurrence and its extreme df=1. for df, expected in ((1, 12.706), (2, 4.303), (3, 3.182), (7, 2.365), - (9, 2.262), (11, 2.201), (30, 2.042)): + (9, 2.262), (11, 2.201)): self.assertLess(abs(critical_value(df) - expected), .0005) - for df in (0, True, 1.5, 50_001): + for df in (0, True, 1.5, 4, 30, 50_001): with self.assertRaises(ValueError): critical_value(df) @@ -122,7 +122,7 @@ def test_unequal_variances_use_unpooled_se_and_minimum_stratum_df(self): logs = [value for pair in zip([0, .01, .02, .03], [0, -.02, -.04, -.06]) for value in pair] result = paired_interval(logs) # Independent hand calculation: df=3, mean=-.0075, SE=sqrt(1/19200). - half = 3.182446305284263 * math.sqrt(1 / 19200) + half = 3.182447 * math.sqrt(1 / 19200) self.assertEqual(result["degrees_of_freedom"], 3) self.assertAlmostEqual(math.log(result["ci95"][0]), -.0075 - half, places=12) self.assertAlmostEqual(math.log(result["ci95"][1]), -.0075 + half, places=12) @@ -130,6 +130,15 @@ def test_unequal_variances_use_unpooled_se_and_minimum_stratum_df(self): for before, after in zip(result["ci95"], shifted["ci95"]): self.assertAlmostEqual(before, after, places=12) + def test_one_zero_variance_order_retains_the_other_orders_uncertainty(self): + result = paired_interval([v for pair in zip([0] * 8, [0, .01] * 4) for v in pair]) + self.assertEqual(result["within_order_log_variances"][0], 0) + self.assertGreater(result["log_standard_error"], 0) + self.assertFalse(result["degenerate_estimated_se"]) + exact = paired_interval([0] * 16) + self.assertTrue(exact["degenerate_estimated_se"]) + self.assertEqual(exact["ci95"], [1, 1]) + def test_touching_loss_margin_does_not_establish_strict_non_regression(self): self.assertEqual(decide(ci(.98, 1), ci(1, 1), "higher")["claim_verdict"], "UNPROVEN") self.assertEqual(decide(ci(1, 1.02), ci(1, 1), "lower")["claim_verdict"], "UNPROVEN") @@ -158,10 +167,18 @@ def test_final_acquisition_refuses_unregistered_count_and_balances_every_pair(se self.assertEqual({a["experiment"] for a in selected}, {"client-aa", "client-ab"}) self.assertEqual([a["arm"] for a in selected], ["a", "b", "a", "b"] if block % 2 == 0 else ["b", "a", "b", "a"]) self.assertEqual(sum(a["source_sha"] == "b" * 40 for a in arms), 16) + tampered = copy.deepcopy(design) + tampered["critical_values"]["7"] = 1.96 + with self.assertRaisesRegex(ValueError, "differs from registration"): + final.schedule(design["baseline_sha"], "b" * 40, config, tampered) design["configurations"][config]["planning_evidence"]["status"] = "lease_shortfall" with self.assertRaisesRegex(ValueError, "exceeds the lease"): final.schedule(design["baseline_sha"], "b" * 40, config, design) design = registered_design() + design["configurations"][config]["pairs_per_phase"] = 28 + with self.assertRaisesRegex(ValueError, "prospectively verified"): + final.schedule(design["baseline_sha"], "b" * 40, config, design) + design = registered_design() design["configurations"][config]["planning_evidence"]["scenarios"][0]["modeled_joint_power_lower_bound"] = float("nan") with self.assertRaisesRegex(ValueError, "power plan"): final.schedule(design["baseline_sha"], "b" * 40, config, design) diff --git a/scripts/tests/inference_client_futility.py b/scripts/tests/inference_client_futility.py new file mode 100644 index 00000000..615bc281 --- /dev/null +++ b/scripts/tests/inference_client_futility.py @@ -0,0 +1,36 @@ +"""Necessary calibration bounds cannot turn an underpowered pilot into admission.""" + +import math +import unittest + +from lib.inference_client_futility import mean_in_band_upper, screen + + +class FutilityTests(unittest.TestCase): + def test_no_interval_can_exceed_the_center_in_band_probability(self): + # Independent Simpson quadrature, rather than another CDF subtraction. + for sd, n in ((.12578296626721047, 24), (.17651447964577716, 16)): + a, b = (math.log(bound) * math.sqrt(n) / sd for bound in (.99, 1.01)) + steps, total = 1000, 0 + for i in range(steps + 1): + x = a + (b - a) * i / steps + total += (1 if i in (0, steps) else 2 if i % 2 == 0 else 4) * math.exp(-x * x / 2) + expected = total * (b - a) / (3 * steps * math.sqrt(2 * math.pi)) + self.assertAlmostEqual(mean_in_band_upper(sd, n), expected + 1e-12, places=12) + for sd in (.12578296626721047, .17651447964577716): + bounds = [mean_in_band_upper(sd, n) for n in (16, 20, 24)] + self.assertEqual(bounds, sorted(bounds)) + self.assertLess(max(bounds), .9) + + def test_degenerate_noise_is_not_positive_sizing_evidence(self): + for sd in (0, -1, math.nan, math.inf): + with self.assertRaises(ValueError): + mean_in_band_upper(sd, 16) + with self.assertRaisesRegex(ValueError, "audited"): + screen({}, {"all_raw_quality_identity_gates": "missing"}) + # A necessary bound near one is not joint power or permission. + self.assertAlmostEqual(mean_in_band_upper(.00001, 16), 1) + + +if __name__ == "__main__": + unittest.main() From 701b56c4580895cd604e23ef4c5aea498bcd7762 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sun, 29 Nov 2026 06:01:15 +1100 Subject: [PATCH 22/22] Preflight unprivileged scheduler tracing before model capture --- ci/README.md | 12 ++ ci/automation.just | 5 + scripts/inference-scheduling-preflight.py | 128 ++++++++++++++++++++ scripts/lib/inference_scheduling_probe.py | 59 +++++++++ scripts/tests/inference_scheduling_probe.py | 123 +++++++++++++++++++ 5 files changed, 327 insertions(+) create mode 100644 scripts/inference-scheduling-preflight.py create mode 100644 scripts/lib/inference_scheduling_probe.py create mode 100644 scripts/tests/inference_scheduling_probe.py diff --git a/ci/README.md b/ci/README.md index c4849e9e..a231bfe6 100644 --- a/ci/README.md +++ b/ci/README.md @@ -364,6 +364,18 @@ probabilities are only 30.31% standalone and 17.93% split, below the 90% joint-p target. This is conditional futility evidence, not a measured regression. Diagnosis, fresh cadence-matched evidence and power validation remain pending. Counts remain unset. +`just inference-scheduling-preflight OUTPUT` is a separate explicit capability +probe on the original Spark host. It builds no model binary and cannot enable +qualification. Under the ordinary job account it captures two synthetic Python +threads with `--sample=none --cpuctxsw=process-tree --trace=osrt`, checks their +actual OS TIDs, 32 known sleep boundaries and a same-host monotonic clock join +no wider than 20 microseconds. The profiler receives a cleared allowlisted +environment. Reports and SQLite remain private and are removed; artifacts contain +only numeric transitions, clock bounds and capability diagnostics. Missing or +ambiguous records produce NOT RUN, never inferred scheduling attribution. A +successful synthetic probe still does not identify the serving receiver TIDs or +establish the runtime's delay mechanism. + Power evidence must bind the configuration, baseline, pilot source, exact pilot and independent-audit file digests, nine distinct endpoint cells, and the reserved placement. Registration rejects mismatches before server arms start. The actual diff --git a/ci/automation.just b/ci/automation.just index 952e54d9..c7243b74 100644 --- a/ci/automation.just +++ b/ci/automation.just @@ -27,6 +27,7 @@ inference-contracts: @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_stream_capture.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client_affinity.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client_timeline.py + @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_scheduling_probe.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client_phases.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_client_collect.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_pairs.py @@ -47,6 +48,10 @@ inference-client-coverage output: inference-client-futility pilot output: @"{{ automation_python }}" scripts/inference-client-futility.py "$@" +[positional-arguments] +inference-scheduling-preflight output: + @"{{ automation_python }}" scripts/inference-scheduling-preflight.py "$@" + inference-publication-test: @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_publication.py diff --git a/scripts/inference-scheduling-preflight.py b/scripts/inference-scheduling-preflight.py new file mode 100644 index 00000000..a09a7c01 --- /dev/null +++ b/scripts/inference-scheduling-preflight.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Unprivileged stock-affinity scheduling preflight; raw profiles stay private.""" + +import argparse +import ctypes +import json +import os +import platform +import shutil +import subprocess +import sys +import tempfile +import threading +import time +from pathlib import Path + +from lib.ci_artifacts import digest, source, write_json +from lib.ci_process import command +from lib.inference_scheduling_probe import summarize + + +def target(output): + ready, reply, finish = threading.Event(), threading.Event(), threading.Event() + worker_id = [] + def worker(): + worker_id.append(threading.get_native_id()) + for _ in range(32): + if not ready.wait(5): + raise RuntimeError("probe worker rendezvous timed out") + ready.clear() + end = time.thread_time_ns() + 200_000 + while time.thread_time_ns() < end: + pass + reply.set() + finish.set() + thread = threading.Thread(target=worker) + thread.start() + libc = ctypes.CDLL(None) + libc.usleep.argtypes, libc.usleep.restype = [ctypes.c_uint], ctypes.c_int + markers = [] + for i in range(32): + ready.set() + before = time.monotonic_ns() + result = libc.usleep((2000, 5000, 11000, 17000)[i % 4]) + after = time.monotonic_ns() + if result or not reply.wait(5): + raise RuntimeError("probe main rendezvous/sleep failed") + reply.clear() + markers.append({"before_ns": before, "after_ns": after}) + thread.join(timeout=5) + if thread.is_alive() or not finish.is_set(): + raise RuntimeError("probe worker did not finish") + write_json(output, {"pid": os.getpid(), "main_tid": threading.get_native_id(), + "worker_tid": worker_id[0], "markers": markers}) + + +def preflight(output): + output.mkdir(parents=True, exist_ok=True) + nsys = shutil.which("nsys") + env = {key: os.environ[key] for key in ("PATH", "HOME", "LD_LIBRARY_PATH") if key in os.environ} + env.update(LANG="C.UTF-8", HF_HUB_OFFLINE="1") + proof = {"status": "NOT RUN", "diagnostic_only": True, "source_sha": os.environ.get("JIANYANG_COMMIT"), + "environment_names": sorted(env), "raw_profiles_uploaded": False, + "budget": {"max_usd": 0, "max_duration_s": 600, "no_preemption": True}} + def run(args, timeout=45): + return command([nsys, *args], timeout=timeout, overrides=env, inherit_env=False, + capture_stdout=True, stderr=subprocess.STDOUT) + try: + if platform.system() != "Linux" or platform.node() != "spark-a29c": + raise ValueError("scheduling preflight requires the original spark-000586 host") + if not nsys: + raise ValueError("installed Nsight unavailable; scheduling NOT RUN") + if source() != proof["source_sha"]: + raise ValueError("scheduling preflight source differs from immutable job admission") + proof["script_sha256"] = digest(Path(__file__)) + proof["subject"] = "Synthetic Python threads only; no Skippy/model binary built or qualified" + proof["nsys_version"] = run(["--version"]) + help_text = run(["profile", "--help"]) + (output / "nsys-profile-help.txt").write_text(help_text) + if any(flag not in help_text for flag in ("--duration", "--cpuctxsw", "--sample", "--force-overwrite")): + raise ValueError("installed profile lacks documented required flags") + try: + proof["environment_status"] = run(["status", "--environment"]) + except subprocess.CalledProcessError as error: + # A status check may reject CPU sampling while process-tree + # context switches remain usable. The actual capture decides. + proof["environment_status_error"] = str(error) + proof["environment_status_log"] = str(error.output)[-4000:] + with tempfile.TemporaryDirectory(prefix="skippy-private-scheduling-") as temporary: + private = Path(temporary) + if private.resolve().is_relative_to(output.resolve()): + raise ValueError("private profiler directory must be outside uploaded artifacts") + proof["capture_log"] = run(["profile", "--trace=osrt", "--sample=none", "--cpuctxsw=process-tree", + "--duration=3", "--force-overwrite=true", "--output=" + str(private / "capture"), + sys.executable, str(Path(__file__).resolve()), "--target", str(private / "probe.json")]) + reports = list(private.glob("*.nsys-rep")) + if len(reports) != 1: + raise ValueError("preflight lacks exactly one completed private report") + database = private / "capture.sqlite" + proof["export_log"] = run(["export", "--type=sqlite", "--force-overwrite=true", + "--output=" + str(database), str(reports[0])]) + proof["raw_report_sha256"] = digest(reports[0]) + proof["sqlite_sha256"] = digest(database) + probe = json.loads((private / "probe.json").read_text()) + proof["result"] = summarize(database, probe) + proof["status"] = "preflight-capable" + except BaseException as error: + proof["error"] = str(error) + raise + finally: + write_json(output / "scheduling-preflight.json", proof) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("output", nargs="?", type=Path) + parser.add_argument("--target", type=Path) + args = parser.parse_args() + if args.target: + target(args.target) + elif args.output: + preflight(args.output) + else: + parser.error("output or --target required") + + +if __name__ == "__main__": + main() diff --git a/scripts/lib/inference_scheduling_probe.py b/scripts/lib/inference_scheduling_probe.py new file mode 100644 index 00000000..2f8940fe --- /dev/null +++ b/scripts/lib/inference_scheduling_probe.py @@ -0,0 +1,59 @@ +"""Numeric, bounded scheduling-probe export; never expose profiler metadata.""" + +import sqlite3 + + +def summarize(path, probe): + expected = {probe["main_tid"], probe["worker_tid"]} + pid = probe["pid"] + with sqlite3.connect(f"file:{path}?mode=ro", uri=True) as db: + names = {r[0] for r in db.execute("SELECT name FROM sqlite_master WHERE type='table'")} + if not {"SCHED_EVENTS", "OSRT_API", "StringIds"} <= names: + raise ValueError("usable per-TID scheduling/OS runtime data unavailable; scheduling NOT RUN") + columns = {r[1] for r in db.execute('PRAGMA table_info("SCHED_EVENTS")')} + if not {"start", "globalTid", "cpu", "isSchedIn"} <= columns: + raise ValueError("unsupported scheduling schema; scheduling NOT RUN") + count = db.execute("SELECT count(*) FROM SCHED_EVENTS").fetchone()[0] + if count > 100_000: + raise ValueError("scheduling preflight exceeds bounded complete export") + rows = [] + for start, global_tid, cpu, inside in db.execute( + "SELECT start,globalTid,cpu,isSchedIn FROM SCHED_EVENTS ORDER BY start"): + # Nsight serialized identifiers: PID bits24..47, TID bits0..23. + tid = global_tid % 0x1000000 + if global_tid // 0x1000000 % 0x1000000 == pid and tid in expected: + rows.append({"start": start, "tid": tid, "cpu": cpu, "isSchedIn": inside}) + for tid in expected: + events = [r for r in rows if r["tid"] == tid] + if (len(events) < 4 or {r["isSchedIn"] for r in events} != {0, 1} + or any(a["start"] >= b["start"] or a["isSchedIn"] == b["isSchedIn"] + for a, b in zip(events, events[1:]))): + raise ValueError("missing, lost or ambiguous scheduling transitions for known probe TID") + apis = db.execute("SELECT a.start,a.end,a.globalTid FROM OSRT_API a " + "JOIN StringIds s ON a.nameId=s.id WHERE s.value='usleep' ORDER BY a.start").fetchall() + apis = [(a, b) for a, b, tid in apis if tid // 0x1000000 % 0x1000000 == pid + and tid % 0x1000000 == probe["main_tid"]] + markers = probe["markers"] + if len(apis) != len(markers) or len(markers) != 32: + raise ValueError("probe clock markers missing/ambiguous; no application-clock join") + lower, upper = [], [] + for (start, end), marker in zip(apis, markers): + lower.append(marker["before_ns"] - start) + upper.append(marker["after_ns"] - end) + # Every known sleep must have a recorded switch-out and switch-in. + sleep_events = [r for r in rows if r["tid"] == probe["main_tid"] + and start <= r["start"] <= end] + if not {0, 1} <= {r["isSchedIn"] for r in sleep_events}: + raise ValueError("known sleep lacks scheduling boundaries; incomplete capture") + lo, hi = max(lower), min(upper) + if not 0 <= hi - lo <= 20_000: + raise ValueError("same-host clock alignment wider than20us or inconsistent") + return {"status": "preflight-capable", "scope": "Synthetic two-thread scheduling capability only", + "pid": pid, "main_tid": probe["main_tid"], "worker_tid": probe["worker_tid"], + "sched_events": rows, "clock_offset_ns": [lo, hi], "clock_uncertainty_ns": hi - lo, + "complete_sleep_markers": len(markers), "raw_profiles_uploaded": False, + "limitations": ["Synthetic TIDs are not the actual serving receiver identities", + "Context switches do not by themselves separate blocked from runnable delay", + "Known sleeps and alternating transitions audit probe coverage, not all possible event loss", + "Real workload still needs exact receiver identity and request-clock alignment", + "No GPU/model qualification or performance verdict"]} diff --git a/scripts/tests/inference_scheduling_probe.py b/scripts/tests/inference_scheduling_probe.py new file mode 100644 index 00000000..3e898d8d --- /dev/null +++ b/scripts/tests/inference_scheduling_probe.py @@ -0,0 +1,123 @@ +"""Offline scheduling-capability gates, not actual tracer qualification.""" + +import sqlite3 +import json +import os +import unittest +from pathlib import Path +from runpy import run_path +from tempfile import TemporaryDirectory +from unittest.mock import Mock, patch + +from lib.inference_scheduling_probe import summarize + + +class SchedulingProbeTests(unittest.TestCase): + def fixture(self, path): + pid, main, worker, offset = 123, 123, 124, 1_000_000_000 + with sqlite3.connect(path) as db: + db.execute('CREATE TABLE SCHED_EVENTS(start,globalTid,cpu,isSchedIn)') + db.execute('CREATE TABLE OSRT_API(start,end,globalTid,nameId)') + db.execute('CREATE TABLE StringIds(id,value)') + db.executemany('INSERT INTO StringIds VALUES (?,?)', [(1, 'usleep'), (2, 'SECRET=offline')]) + db.execute('CREATE TABLE TARGET_INFO_ENV_VAR(value)') + db.execute("INSERT INTO TARGET_INFO_ENV_VAR VALUES ('SECRET=offline')") + markers = [] + for i in range(32): + start, end = 100_000 * i + 10_000, 100_000 * i + 80_000 + db.execute('INSERT INTO OSRT_API VALUES (?,?,?,1)', (start, end, (pid << 24) + main)) + for tid in (main, worker): + db.executemany('INSERT INTO SCHED_EVENTS VALUES (?,?,3,?)', + [(start + 10_000, (pid << 24) + tid, 0), + (end - 10_000, (pid << 24) + tid, 1)]) + markers.append({'before_ns': offset + start - 1000, 'after_ns': offset + end + 1000}) + return {'pid': pid, 'main_tid': main, 'worker_tid': worker, 'markers': markers} + + def test_exact_known_tids_clock_bounds_and_numeric_only_export(self): + with TemporaryDirectory() as temporary: + path = Path(temporary) / 'trace.sqlite' + probe = self.fixture(path) + result = summarize(path, probe) + self.assertEqual(result['status'], 'preflight-capable') + self.assertEqual(result['clock_offset_ns'], [999_999_000, 1_000_001_000]) + self.assertEqual(result['complete_sleep_markers'], 32) + self.assertNotIn('SECRET', str(result)) + + def test_missing_context_switches_or_markers_cannot_pass(self): + for table in ('SCHED_EVENTS', 'OSRT_API'): + with self.subTest(table=table), TemporaryDirectory() as temporary: + path = Path(temporary) / 'trace.sqlite' + probe = self.fixture(path) + with sqlite3.connect(path) as db: + db.execute(f'DELETE FROM {table}') + with self.assertRaises(ValueError): + summarize(path, probe) + + def test_wrong_process_and_ambiguous_transition_are_rejected(self): + for mutation in ('UPDATE SCHED_EVENTS SET globalTid=globalTid+16777216', + 'UPDATE SCHED_EVENTS SET isSchedIn=1'): + with self.subTest(mutation=mutation), TemporaryDirectory() as temporary: + path = Path(temporary) / 'trace.sqlite' + probe = self.fixture(path) + with sqlite3.connect(path) as db: + db.execute(mutation) + with self.assertRaises(ValueError): + summarize(path, probe) + + def test_wide_application_clock_join_cannot_pass(self): + with TemporaryDirectory() as temporary: + path = Path(temporary) / 'trace.sqlite' + probe = self.fixture(path) + for marker in probe['markers']: + marker['before_ns'] -= 100_000 + marker['after_ns'] += 100_000 + with self.assertRaisesRegex(ValueError, 'clock alignment'): + summarize(path, probe) + + def test_preflight_clears_credentials_and_removes_raw_profiles(self): + preflight = run_path(str(Path(__file__).resolve().parents[1] / 'inference-scheduling-preflight.py'))['preflight'] + private_dirs = [] + def command(args, **kwargs): + self.assertFalse(kwargs['inherit_env']) + self.assertNotIn('HF_TOKEN', kwargs['overrides']) + self.assertNotIn('JIANYANG_API_KEY', kwargs['overrides']) + if args[1:3] == ['profile', '--help']: + return '--duration --cpuctxsw --sample --force-overwrite' + if args[1] == 'profile': + self.assertIn('--cpuctxsw=process-tree', args) + self.assertIn('--sample=none', args) + base = Path(next(a.split('=', 1)[1] for a in args if a.startswith('--output='))) + private_dirs.append(base.parent) + base.with_suffix('.nsys-rep').write_text('SECRET=private-profile') + probe = self.fixture(base.with_suffix('.sqlite')) + Path(args[args.index('--target') + 1]).write_text(json.dumps(probe)) + return 'ok' + with TemporaryDirectory() as temporary, patch.dict(os.environ, { + 'HF_TOKEN': 'secret', 'JIANYANG_API_KEY': 'secret', 'JIANYANG_COMMIT': 'a' * 40}): + output = Path(temporary) + with patch.dict(preflight.__globals__, { + 'platform': Mock(system=lambda: 'Linux', node=lambda: 'spark-a29c'), + 'shutil': Mock(which=lambda _: '/fake/nsys'), 'command': command, 'source': lambda: 'a' * 40}): + preflight(output) + result = json.loads((output / 'scheduling-preflight.json').read_text()) + self.assertEqual(result['status'], 'preflight-capable') + self.assertNotIn('SECRET', str(result)) + self.assertFalse(list(output.rglob('*.sqlite'))) + self.assertTrue(private_dirs) + self.assertTrue(all(not p.exists() for p in private_dirs)) + + def test_missing_tracer_retains_not_run_receipt(self): + preflight = run_path(str(Path(__file__).resolve().parents[1] / 'inference-scheduling-preflight.py'))['preflight'] + with TemporaryDirectory() as temporary: + output = Path(temporary) + with patch.dict(preflight.__globals__, { + 'platform': Mock(system=lambda: 'Linux', node=lambda: 'spark-a29c'), + 'shutil': Mock(which=lambda _: None)}): + with self.assertRaisesRegex(ValueError, 'Nsight unavailable'): + preflight(output) + result = json.loads((output / 'scheduling-preflight.json').read_text()) + self.assertEqual(result['status'], 'NOT RUN') + + +if __name__ == '__main__': + unittest.main()