From 4736b193dab4008ecbd782eac360efb9d4a4fddc Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 19:38:00 +0200 Subject: [PATCH] feat(bench): validate paired comparisons and report uncertainty privately --- benchmarks/README.md | 66 ++++ scripts/check-local.sh | 2 + scripts/compare-chat-reports.py | 592 +++++++++++++++++++++++------- scripts/render-paired-report.py | 181 +++++++++ scripts/test-benchmark-harness.py | 12 +- scripts/test-paired-markdown.py | 104 ++++++ scripts/test-paired-report.py | 301 +++++++++++++++ 7 files changed, 1118 insertions(+), 140 deletions(-) create mode 100644 scripts/render-paired-report.py create mode 100644 scripts/test-paired-markdown.py create mode 100644 scripts/test-paired-report.py diff --git a/benchmarks/README.md b/benchmarks/README.md index 2e991ab3..9a1b8295 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -9,6 +9,72 @@ Store future benchmark definitions and sanitized fixtures in Git; place generate `fixtures/chat/paired-smoke.json` contains public synthetic arithmetic, retrieval, and function-call prompts. Run `scripts/bench-chat-paired.py` from the repository root. It sends one untimed warmup per case and endpoint, then alternates baseline/candidate order over repeated, sequential requests with the same model, prompt, greedy sampling settings, and token cap. It checks each response's terminal `finish_reason` and case-specific text or tool arguments. The report includes per-case pass counts, raw response timings, and paired wall-time ratios. The full response report is written only to a new private path outside Git with mode 0600; API keys are read from private server config files and omitted from the report. For the current upstream server, pass its full bound URL as `--baseline-url`, its `/health` URL as `--baseline-ready-url`, the configured model name as `--model`, and its private JSON config as `--baseline-auth-config`. The readiness poll waits for a nonzero `max_context` because upstream can report `loaded: true` during loading. Once a compressed inference endpoint exists, pass its URL as `--candidate-url` and optionally `--candidate-ready-url`. A baseline-only run is a functional check and cannot establish a speedup. Even a paired run of this small synthetic suite is only a smoke test: the charter's long-context, real-agent, cache-state, and model-quality gates still require separate runs. Record engine/config digests, GPU, driver, CUDA, power settings, and artifact digests in a private `--metadata` JSON for any reported performance result. Never commit the report or private config. + +## Offline comparison of sequential Chat reports + +When two model arms cannot fit together, compare two **single-arm** schema-1 +reports from the same suite/model/configuration. A standalone harness run may +label its rows `baseline` in both files; the filenames select the comparison +arms. Each file must contain one arm, exactly one warmup per case and the full +declared repeat range. Missing or duplicate pairs, category drift, malformed +rows, nonfinite numbers and inconsistent successful HTTP/terminal/quality +claims fail before any comparison is published. Genuine observed quality or +HTTP failures remain explicit data, with failed categories reported separately. + +```sh +python3 -B scripts/compare-chat-reports.py \ + /private/evaluation/baseline.json /private/evaluation/candidate.json \ + --output /private/evaluation/comparison.json +python3 -B scripts/render-paired-report.py /private/evaluation/comparison.json \ + --output /private/evaluation/comparison.md +``` + +JSON and Markdown outputs must be new files outside Git and use mode 0600; +neither overwrites an existing file. The comparator prints fixed aggregate +counts only, without case labels, response text, tool arguments or metadata. +Markdown omits raw responses, tool arguments and metadata values. Private +metadata remains in the private JSON for reproducibility. + +Existing schema-1 median fields remain available. Overall, category and case +groups additionally contain mean, median, linearly interpolated p10/p90 and +sample counts for both arms' wall times and positive paired prefill/decode +rates. Ratios are calculated **within each pair**, then summarized; they are +not ratios of arm medians. Zero token rates (for example fully cached prefill) +and missing timings never become divisions by zero: `timing_coverage` and +`unavailable_pairs` disclose their exclusion, while a wholly unavailable +throughput summary stays `null`. Counts must be nonnegative integers; timing +values must be finite/nonnegative and measured wall times strictly positive. + +Ratio uncertainty uses a deterministic distribution-free, two-sided 95% +confidence interval for the population **median paired ratio**, selected from +order statistics with exact binomial coverage. This bounds work without a +bootstrap dependency or random seed. Fewer than six pairs cannot yield a finite +95% interval and receive `null` bounds; fewer than 30 pairs receive an explicit +small-sample flag. The interval assumes independent pairs sharing a population +median; sequential cache/load drift and correlated repeats can invalidate that +assumption. Category/overall mixtures also depend on case composition. The +interval does not measure those systematic errors or uncertainty in the mean. + +The report names missing charter provenance fields without echoing their +values: `engine_commit`, `control_plane_commit`, `model_sha256`, `quantization`, +`gpu`, `driver`, `cuda_toolkit`, `power_limit_watts`, `context_tokens`, +`kv_configuration`, `slots`, `batch_size`, `speculation`, `cache_state`, +`workload_sha256`, `quality_gate_result`, `draft_acceptance_rate`, +`expert_cache_hit_rate`, `kv_streaming_hit_rate`; measured TTFT and prompt/output +token-count coverage are checked separately. Unavailable/not-applicable metrics +should be explained in private provenance; a declaration is not a measurement. +Conflicting declared hardware, model source, context/KV/slot/batch/speculation, +cache or workload identity refuses pairing. Engine/control-plane/codec version +changes can be the intended comparison, but must be recorded for each arm. + +Inputs are bounded to 32 MiB each, 64 cases, 4,096 measured pairs, 100 repeats +per case, JSON depth 32 and one million JSON nodes. Timing/count magnitudes are +bounded to 10^12. Split larger suites deliberately instead of silently dropping +rows. JSON statistics and the Markdown rendering remain **descriptive**: +sequential runs, synthetic CPU fixtures, complete metadata or passing smoke +checks never automatically qualify GPU inference, model quality or an +end-to-end agent performance improvement. Those charter gates remain separate. + # Live Responses episode replay `scripts/replay-live-responses.py` is an offline evaluator for an **explicitly diff --git a/scripts/check-local.sh b/scripts/check-local.sh index f14cb531..23b8ba33 100755 --- a/scripts/check-local.sh +++ b/scripts/check-local.sh @@ -5,6 +5,8 @@ repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" python3 -m py_compile "${repo_root}/scripts/prepare-keyless-routing.py" "${repo_root}/scripts/calibrate-keyless-routing.py" "${repo_root}/scripts/test-keyless-routing.py" "${repo_root}/scripts/bench-chat-paired.py" "${repo_root}/scripts/compare-chat-reports.py" "${repo_root}/scripts/bench-chat-sequential-server.py" "${repo_root}/scripts/check-kar-cuda-records.py" "${repo_root}/scripts/strata-agent-profile.py" "${repo_root}/scripts/strata-dual-256-experiment.py" "${repo_root}/scripts/strata-dual-request-proxy.py" "${repo_root}/scripts/kv-keyless-feasibility.py" "${repo_root}/scripts/kv-keyless-attention.py" "${repo_root}/scripts/bench-expert-reserve.py" "${repo_root}/scripts/ple-cache-reuse.py" "${repo_root}/scripts/split-ple-row-trace.py" "${repo_root}/scripts/bench-kar-ple-device.py" "${repo_root}/scripts/bench-kar-ple-serve.py" python3 "${repo_root}/scripts/test-benchmark-harness.py" +python3 "${repo_root}/scripts/test-paired-report.py" +python3 "${repo_root}/scripts/test-paired-markdown.py" python3 "${repo_root}/scripts/test-native-service.py" python3 "${repo_root}/scripts/test-native-api.py" python3 "${repo_root}/scripts/test-native-menu.py" diff --git a/scripts/compare-chat-reports.py b/scripts/compare-chat-reports.py index e730225f..081a42b8 100644 --- a/scripts/compare-chat-reports.py +++ b/scripts/compare-chat-reports.py @@ -1,69 +1,379 @@ #!/usr/bin/env python3 -"""Compare two private, sequential runs of bench-chat-paired.py. +"""Descriptively compare two private, sequential bench-chat-paired.py runs. -Useful on one GPU when both model arms cannot fit in VRAM together. The output -is a descriptive paired report; load order and disk/cache drift still matter. +No performance/model-quality qualification follows from this offline report. """ import argparse import datetime as dt import json +import math import os from pathlib import Path import statistics +import sys + +MAX_INPUT_BYTES = 32 * 1024 * 1024 +MAX_CASES = 64 +MAX_PAIRS = 4096 +MAX_REPEATS = 100 +MAX_NUMBER = 1e12 +COUNT_FIELDS = {"prompt_n", "predicted_n", "cache_n", "draft_n", "draft_accepted_n"} +USAGE_COUNTS = {"prompt_tokens", "completion_tokens", "total_tokens", "input_tokens", + "output_tokens", "cached_tokens", "reasoning_tokens", + "accepted_prediction_tokens", "rejected_prediction_tokens"} +# Canonical private metadata keys. Presence is an operator assertion, not proof. +PROVENANCE_FIELDS = ( + "engine_commit", "control_plane_commit", "model_sha256", "quantization", + "gpu", "driver", "cuda_toolkit", "power_limit_watts", "context_tokens", + "kv_configuration", "slots", "batch_size", "speculation", "cache_state", + "workload_sha256", "quality_gate_result", "draft_acceptance_rate", + "expert_cache_hit_rate", "kv_streaming_hit_rate", +) +LIMITATION = ( + "Descriptive only: sequential model loads and requests may drift with I/O, " + "cache state and load order; repeats may be correlated. Synthetic/CPU " + "results and supplied metadata do not qualify GPU inference, end-to-end " + "agent performance or model quality. Pooled cases/categories depend on " + "their case composition; uncertainty assumes independent pairs sharing " + "a common population median." +) + + +def reject(message): + # Fixed field names only; never include values from a private report. + raise ValueError(message) + + +def integer(value, minimum=0, maximum=int(MAX_NUMBER)): + return type(value) is int and minimum <= value <= maximum + + +def number(value, positive=False): + return (type(value) in (int, float) and math.isfinite(value) + and (value > 0 if positive else value >= 0) and value <= MAX_NUMBER) + + +def label(value): + return isinstance(value, str) and bool(value.strip()) and len(value) <= 128 + + +def unique_object(items): + result = {} + for key, value in items: + if key in result: + reject("duplicate JSON field") + result[key] = value + return result + + +def finite_float(text): + value = float(text) + if not math.isfinite(value): + reject("nonfinite JSON number") + return value + + +def bounded_tree(report): + # Keep only one iterator per depth, not a second copy of a wide JSON array. + stack = [(iter((report,)), 0)] + nodes = 0 + while stack: + iterator, depth = stack[-1] + try: + value = next(iterator) + except StopIteration: + stack.pop() + continue + nodes += 1 + if depth > 32 or nodes > 1_000_000: + reject("report exceeds structure limit") + if isinstance(value, dict): + stack.append((iter(value.values()), depth + 1)) + elif isinstance(value, list): + stack.append((iter(value), depth + 1)) + elif type(value) is float and not math.isfinite(value): + reject("nonfinite JSON number") + + +def load_report(path): + with path.open("rb") as source: + raw = source.read(MAX_INPUT_BYTES + 1) + if len(raw) > MAX_INPUT_BYTES: + reject("report exceeds input byte limit") + try: + report = json.loads(raw, object_pairs_hook=unique_object, parse_float=finite_float, + parse_constant=lambda _: reject("nonfinite JSON number")) + except (UnicodeError, json.JSONDecodeError, RecursionError): + reject("invalid report JSON") + bounded_tree(report) + validate_report(report) + return report def normalized(row): try: - message = row["response"]["choices"][0]["message"] - return { - "content": message.get("content"), - "tool_calls": [ - {"name": call["function"]["name"], - "arguments": json.loads(call["function"]["arguments"])} - for call in message.get("tool_calls") or [] - ], - } - except (KeyError, IndexError, TypeError, ValueError): + choices = row["response"]["choices"] + if not isinstance(choices, list) or len(choices) != 1: + return None + choice = choices[0] + message = choice["message"] + if message.get("role") != "assistant" or choice.get("finish_reason") not in ("stop", "tool_calls"): + return None + content = message.get("content") + if content is not None and not isinstance(content, str): + return None + calls = message.get("tool_calls") + if calls is None: + calls = [] + if not isinstance(calls, list) or len(calls) > 128: + return None + if bool(calls) != (choice["finish_reason"] == "tool_calls"): + return None + tools, call_ids = [], set() + for call in calls: + call_id = call.get("id") + if not label(call_id) or call_id in call_ids: + return None + call_ids.add(call_id) + function = call["function"] + if call.get("type") != "function" or not label(function["name"]): + return None + if not isinstance(function["arguments"], str): + return None + arguments = json.loads(function["arguments"], object_pairs_hook=unique_object, parse_float=finite_float, + parse_constant=lambda _: reject("nonfinite tool JSON")) + if not isinstance(arguments, dict): + return None + bounded_tree(arguments) + tools.append({"name": function["name"], "arguments": arguments}) + if content is None and not tools: + return None + return {"content": content, "tool_calls": tools} + except (KeyError, IndexError, TypeError, ValueError, AttributeError, RecursionError): return None -def selected(report): - rows = {} - for row in report["rows"]: +def validate_usage(usage): + if usage is None: + return + if not isinstance(usage, dict): + reject("usage must be an object") + for key, value in usage.items(): + if key in USAGE_COUNTS and not integer(value): + reject("usage token count must be a bounded nonnegative integer") + if key in ("prompt_tokens_details", "completion_tokens_details", + "input_tokens_details", "output_tokens_details"): + if not isinstance(value, dict): + reject("usage token details must be an object") + validate_usage(value) + if all(key in usage for key in ("prompt_tokens", "completion_tokens", "total_tokens")): + if usage["prompt_tokens"] + usage["completion_tokens"] != usage["total_tokens"]: + reject("usage total_tokens is inconsistent") + for prefix in ("prompt", "input"): + total = usage.get(prefix + "_tokens") + cached = usage.get(prefix + "_tokens_details", {}).get("cached_tokens") + if total is not None and cached is not None and cached > total: + reject("usage cached_tokens exceeds input tokens") + + +def validate_report(report): + if not isinstance(report, dict) or type(report.get("schema")) is not int or report["schema"] != 1: + reject("unsupported report schema") + digest = report.get("suite_sha256") + if (not isinstance(digest, str) or len(digest) != 64 + or any(char not in "0123456789abcdefABCDEF" for char in digest)): + reject("suite_sha256 must be a SHA-256 digest") + if not label(report.get("model")): + reject("model must be a bounded nonempty string") + config = report.get("configuration") + if not isinstance(config, dict) or not integer(config.get("repeats"), 1, MAX_REPEATS): + reject("configuration.repeats is invalid") + for field in ("max_tokens", "seed"): + if field in config and not integer(config[field], 1 if field == "max_tokens" else 0): + reject("configuration integer is invalid") + if "temperature" in config and not number(config["temperature"]): + reject("configuration.temperature is invalid") + if "stream" in config and config["stream"] is not False: + reject("configuration.stream must be false") + for field in ("reasoning_effort", "cache_state"): + if field in config and (not isinstance(config[field], str) or not config[field].strip() or len(config[field]) > 1024): + reject("configuration text field is invalid") + if not isinstance(report.get("metadata", {}), dict): + reject("metadata must be an object") + rows = report.get("rows") + if not isinstance(rows, list) or not rows or len(rows) > MAX_PAIRS + MAX_CASES: + reject("rows exceed report limits or are empty") + cases, measured, warmups, arms = {}, set(), set(), set() + for row in rows: + if not isinstance(row, dict) or not label(row.get("case_id")) or not label(row.get("category")): + reject("row case_id/category is invalid") + if row.get("arm") not in ("baseline", "candidate"): + reject("row arm is invalid") + arms.add(row["arm"]) + case = row["case_id"] + if case in cases and cases[case] != row["category"]: + reject("case category changes between rows") + cases[case] = row["category"] + if type(row.get("warmup")) is not bool: + reject("row warmup must be boolean") if row["warmup"]: - continue - key = (row["case_id"], row["repeat"]) - if key in rows: - raise ValueError(f"duplicate run {key}") - rows[key] = row - return rows + if row.get("repeat") is not None or case in warmups: + reject("invalid or duplicate warmup") + warmups.add(case) + else: + repeat = row.get("repeat") + if not integer(repeat, 0, config["repeats"] - 1) or (case, repeat) in measured: + reject("invalid or duplicate measured repeat") + measured.add((case, repeat)) + if not number(row.get("wall_seconds"), positive=True): + reject("wall_seconds must be finite and positive") + if not integer(row.get("http_status"), 100, 599): + reject("http_status is invalid") + quality = row.get("quality") + if not isinstance(quality, dict) or type(quality.get("passed")) is not bool: + reject("quality.passed must be boolean") + response = row.get("response") + if not isinstance(response, dict): + reject("response must be an object") + if quality["passed"] and (row["http_status"] != 200 or normalized(row) is None): + reject("quality.passed contradicts HTTP/terminal response") + validate_usage(response.get("usage")) + timing = response.get("timings") + if timing is not None: + if not isinstance(timing, dict): + reject("timings must be an object") + for key, value in timing.items(): + if key in COUNT_FIELDS or key.endswith("_n"): + if not integer(value): + reject("timing token count must be a bounded nonnegative integer") + elif not number(value): + reject("optional timing must be finite and nonnegative") + if (len(arms) != 1 or len(cases) > MAX_CASES or len(measured) > MAX_PAIRS + or warmups != cases.keys() + or len(measured) != len(cases) * config["repeats"]): + reject("report must contain one arm and complete warmup/repeat coverage") + + +def selected(report): + return {(row["case_id"], row["repeat"]): row for row in report["rows"] if not row["warmup"]} + + +def percentile(values, fraction): + position = (len(values) - 1) * fraction + lower = int(position) + remainder = position - lower + return values[lower] * (1 - remainder) + values[min(lower + 1, len(values) - 1)] * remainder + + +def median_interval(values): + """Exact distribution-free paired median order-statistic interval. + + Pick the narrowest symmetric interval with >=95% binomial coverage. + Below six pairs no finite two-sided 95% interval exists; disclose null bounds. + """ + n = len(values) + total = 1 << n + weight, tail, chosen, chosen_tail = 1, 0, 0, 0 + for k in range(1, n // 2 + 1): + tail += weight + if 40 * tail > total: + break + chosen, chosen_tail = k, tail + weight = weight * (n - k + 1) // k + return { + "method": "exact paired median order-statistic interval", + "confidence_level": 0.95, + "coverage_lower_bound": 1 - 2 * chosen_tail / total if chosen else None, + "lower": values[chosen - 1] if chosen else None, + "upper": values[n - chosen] if chosen else None, + "finite_interval_available": bool(chosen), + "assumption": "independent pairs with a common population median; ties are conservative", + } + + +def distribution(values, uncertainty=False): + values = sorted(values) + result = {"sample_count": len(values), "mean": statistics.fmean(values), + "median": statistics.median(values), "p10": percentile(values, 0.1), + "p90": percentile(values, 0.9), "small_sample": len(values) < 30} + if uncertainty: + result["median_confidence_interval"] = median_interval(values) + return result + + +def ratio(candidate, baseline): + result = candidate / baseline + if not math.isfinite(result) or result <= 0: + reject("paired ratio is not finite and positive") + return result + + +def throughput(pairs, field): + measured = [(pair["baseline_timings"].get(field), pair["candidate_timings"].get(field)) + for pair in pairs] + valid = [(a, b) for a, b in measured if a is not None and b is not None and a > 0 and b > 0] + if not valid: + return None + ratios = [ratio(b, a) for a, b in valid] + return { + "pairs": len(valid), "unavailable_pairs": len(pairs) - len(valid), + "baseline_median_tokens_per_second": statistics.median(a for a, _ in valid), + "candidate_median_tokens_per_second": statistics.median(b for _, b in valid), + "candidate_over_baseline_median_ratio": statistics.median(ratios), + "baseline_distribution": distribution([a for a, _ in valid]), + "candidate_distribution": distribution([b for _, b in valid]), + "candidate_over_baseline_ratio_distribution": distribution(ratios, uncertainty=True), + } + + +def group_summary(pairs): + baseline_failed = sum(not pair["baseline_quality_passed"] for pair in pairs) + candidate_failed = sum(not pair["candidate_quality_passed"] for pair in pairs) + mismatched = sum(not pair["same_normalized_output"] for pair in pairs) + return { + "pairs": len(pairs), + "same_normalized_output": len(pairs) - mismatched, + "both_quality_passed": sum(pair["baseline_quality_passed"] and + pair["candidate_quality_passed"] for pair in pairs), + "candidate_over_baseline_wall_median_ratio": statistics.median( + pair["candidate_over_baseline_wall_ratio"] for pair in pairs), + "wall_seconds": { + "baseline": distribution([pair["baseline_wall_seconds"] for pair in pairs]), + "candidate": distribution([pair["candidate_wall_seconds"] for pair in pairs]), + }, + "candidate_over_baseline_wall_ratio_distribution": distribution( + [pair["candidate_over_baseline_wall_ratio"] for pair in pairs], uncertainty=True), + "quality": {"baseline_failed": baseline_failed, "candidate_failed": candidate_failed, + "normalized_output_mismatches": mismatched, + "baseline_http_or_protocol_failed": sum(pair["baseline_protocol_failed"] for pair in pairs), + "candidate_http_or_protocol_failed": sum(pair["candidate_protocol_failed"] for pair in pairs), + "observed_checks_passed": not (baseline_failed or candidate_failed or mismatched)}, + "timing_coverage": { + field: {"available_pairs": sum(pair["baseline_timings"].get(field, 0) > 0 and + pair["candidate_timings"].get(field, 0) > 0 for pair in pairs), + "total_pairs": len(pairs)} + for field in ("prompt_per_second", "predicted_per_second") + }, + "prefill": throughput(pairs, "prompt_per_second"), + "decode": throughput(pairs, "predicted_per_second"), + } def initial_requests(base, candidate): - def rows(report): - selected_rows = {} - for row in report["rows"]: - if row["warmup"]: - case = row["case_id"] - if case in selected_rows: - raise ValueError(f"duplicate initial request for {case}") - selected_rows[case] = row - return selected_rows - - b_rows, c_rows = rows(base), rows(candidate) + b_rows = {row["case_id"]: row for row in base["rows"] if row["warmup"]} + c_rows = {row["case_id"]: row for row in candidate["rows"] if row["warmup"]} if b_rows.keys() != c_rows.keys(): - raise ValueError("initial requests differ between arms") + reject("initial requests differ between arms") result = {} for case in sorted(b_rows): b, c = b_rows[case], c_rows[case] - b_timing = b["response"].get("timings") or {} - c_timing = c["response"].get("timings") or {} + if b["category"] != c["category"]: + reject("initial case category differs") + b_timing, c_timing = b["response"].get("timings") or {}, c["response"].get("timings") or {} result[case] = { - "baseline_wall_seconds": b["wall_seconds"], - "candidate_wall_seconds": c["wall_seconds"], - "baseline_quality_passed": b["quality"]["passed"], - "candidate_quality_passed": c["quality"]["passed"], + "baseline_wall_seconds": b["wall_seconds"], "candidate_wall_seconds": c["wall_seconds"], + "baseline_quality_passed": b["quality"]["passed"], "candidate_quality_passed": c["quality"]["passed"], "baseline_prompt_tokens_processed": b_timing.get("prompt_n"), "candidate_prompt_tokens_processed": c_timing.get("prompt_n"), "baseline_cached_prompt_tokens": b_timing.get("cache_n"), @@ -74,35 +384,71 @@ def initial_requests(base, candidate): return result -def throughput(pairs, field): - measured = [] +def provenance(report): + metadata = report.get("metadata", {}) + missing = [field for field in PROVENANCE_FIELDS if metadata.get(field) in (None, "", [], {})] + measured = [row for row in report["rows"] if not row["warmup"]] + if not all(any((row["response"].get("timings") or {}).get(key, 0) > 0 + for key in ("ttft_ms", "ttft_seconds")) for row in measured): + missing.append("ttft") + if not all(all(key in (row["response"].get("usage") or {}) + for key in ("prompt_tokens", "completion_tokens")) for row in measured): + missing.append("prompt_output_token_counts") + return {"missing_fields": missing, "metadata_presence_is_not_verified_evidence": True} + + +def compare(base, candidate): + for field in ("schema", "suite_sha256", "model", "configuration"): + if base[field] != candidate[field]: + reject("reports differ in " + field) + # An intended code/codec change may differ between arms, but a declared + # different workload/hardware/cache setup cannot be pooled as matched pairs. + for field in ("gpu", "driver", "power_limit_watts", "model_sha256", "context_tokens", + "kv_configuration", "slots", "batch_size", "speculation", "cache_state", "workload_sha256"): + b_value, c_value = base.get("metadata", {}).get(field), candidate.get("metadata", {}).get(field) + if b_value not in (None, "", [], {}) and c_value not in (None, "", [], {}) and b_value != c_value: + reject("incompatible paired provenance field") + b_rows, c_rows = selected(base), selected(candidate) + if not b_rows or b_rows.keys() != c_rows.keys(): + reject("reports do not contain the same measured cases") + pairs = [] + for key in sorted(b_rows): + b, c = b_rows[key], c_rows[key] + if b["category"] != c["category"]: + reject("case category differs") + b_normal, c_normal = normalized(b), normalized(c) + pairs.append({ + "case_id": key[0], "repeat": key[1], "category": b["category"], + "baseline_wall_seconds": b["wall_seconds"], "candidate_wall_seconds": c["wall_seconds"], + "candidate_over_baseline_wall_ratio": ratio(c["wall_seconds"], b["wall_seconds"]), + "baseline_quality_passed": b["quality"]["passed"], "candidate_quality_passed": c["quality"]["passed"], + "baseline_protocol_failed": b["http_status"] != 200 or b_normal is None, + "candidate_protocol_failed": c["http_status"] != 200 or c_normal is None, + "same_normalized_output": b["http_status"] == c["http_status"] == 200 and b_normal is not None and b_normal == c_normal, + "baseline_usage": b["response"].get("usage"), "candidate_usage": c["response"].get("usage"), + "baseline_timings": b["response"].get("timings") or {}, "candidate_timings": c["response"].get("timings") or {}, + }) + grouped_cases, grouped_categories = {}, {} for pair in pairs: - baseline = pair["baseline_timings"].get(field) - candidate = pair["candidate_timings"].get(field) - if (isinstance(baseline, (int, float)) and isinstance(candidate, (int, float)) - and baseline > 0 and candidate > 0): - measured.append((baseline, candidate)) - if not measured: - return None - return { - "pairs": len(measured), - "baseline_median_tokens_per_second": statistics.median(a for a, _ in measured), - "candidate_median_tokens_per_second": statistics.median(b for _, b in measured), - "candidate_over_baseline_median_ratio": statistics.median(b / a for a, b in measured), - } - - -def group_summary(pairs): - return { - "pairs": len(pairs), - "same_normalized_output": sum(pair["same_normalized_output"] for pair in pairs), - "both_quality_passed": sum(pair["baseline_quality_passed"] and - pair["candidate_quality_passed"] for pair in pairs), - "candidate_over_baseline_wall_median_ratio": statistics.median( - pair["candidate_over_baseline_wall_ratio"] for pair in pairs), - "prefill": throughput(pairs, "prompt_per_second"), - "decode": throughput(pairs, "predicted_per_second"), - } + grouped_cases.setdefault(pair["case_id"], []).append(pair) + grouped_categories.setdefault(pair["category"], []).append(pair) + categories = {category: group_summary(members) for category, members in sorted(grouped_categories.items())} + summary = group_summary(pairs) + summary.update({ + "baseline_quality_passed": sum(p["baseline_quality_passed"] for p in pairs), + "candidate_quality_passed": sum(p["candidate_quality_passed"] for p in pairs), + "categories": categories, + "cases": {case: group_summary(members) for case, members in sorted(grouped_cases.items())}, + "failed_quality_categories": [name for name, result in categories.items() + if not result["quality"]["observed_checks_passed"]], + }) + warmups = initial_requests(base, candidate) + summary["initial_request_quality_failed"] = sum( + not (row["baseline_quality_passed"] and row["candidate_quality_passed"]) for row in warmups.values()) + return {"summary": summary, "pairs": pairs, "initial_requests": warmups, + "provenance": {"baseline": provenance(base), "candidate": provenance(candidate)}, + "qualification": {"performance_qualified": False, "model_quality_qualified": False, + "reason": "descriptive offline comparison; separate charter gates required"}} def main(): @@ -111,78 +457,46 @@ def main(): parser.add_argument("candidate", type=Path) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() - repository = Path(__file__).resolve().parent.parent - output = args.output.resolve() - if output == repository or repository in output.parents: - parser.error("output must be outside the repository") - base, candidate = (json.loads(path.read_text()) for path in - (args.baseline, args.candidate)) - for field in ("schema", "suite_sha256", "model", "configuration"): - if base[field] != candidate[field]: - raise ValueError(f"reports differ in {field}") - b_rows, c_rows = selected(base), selected(candidate) - if not b_rows or b_rows.keys() != c_rows.keys(): - raise ValueError("reports do not contain the same measured cases") - pairs = [] - for key in sorted(b_rows): - b, c = b_rows[key], c_rows[key] - if b["category"] != c["category"]: - raise ValueError("case category differs") - pairs.append({ - "case_id": key[0], "repeat": key[1], "category": b["category"], - "baseline_wall_seconds": b["wall_seconds"], - "candidate_wall_seconds": c["wall_seconds"], - "candidate_over_baseline_wall_ratio": c["wall_seconds"] / b["wall_seconds"], - "baseline_quality_passed": b["quality"]["passed"], - "candidate_quality_passed": c["quality"]["passed"], - "same_normalized_output": (b["http_status"] == c["http_status"] == 200 - and normalized(b) is not None - and normalized(b) == normalized(c)), - "baseline_usage": b["response"].get("usage") if isinstance(b["response"], dict) else None, - "candidate_usage": c["response"].get("usage") if isinstance(c["response"], dict) else None, - "baseline_timings": (b["response"].get("timings") or {}) - if isinstance(b["response"], dict) else {}, - "candidate_timings": (c["response"].get("timings") or {}) - if isinstance(c["response"], dict) else {}, - }) - categories = {} - for category in sorted({pair["category"] for pair in pairs}): - members = [pair for pair in pairs if pair["category"] == category] - categories[category] = group_summary(members) - cases = {case: group_summary([pair for pair in pairs if pair["case_id"] == case]) - for case in sorted({pair["case_id"] for pair in pairs})} - report = { - "schema": 1, "created_utc": dt.datetime.now(dt.timezone.utc).isoformat(), - "baseline_report": str(args.baseline.resolve()), - "candidate_report": str(args.candidate.resolve()), - "baseline_metadata": base.get("metadata", {}), - "candidate_metadata": candidate.get("metadata", {}), - "comparison_limit": "Sequential model loads on one GPU; wall times include API and may drift with I/O and cache state.", - "summary": { - "pairs": len(pairs), - "baseline_quality_passed": sum(p["baseline_quality_passed"] for p in pairs), - "candidate_quality_passed": sum(p["candidate_quality_passed"] for p in pairs), - "same_normalized_output": sum(p["same_normalized_output"] for p in pairs), - "candidate_over_baseline_wall_median_ratio": statistics.median( - p["candidate_over_baseline_wall_ratio"] for p in pairs), - "prefill": throughput(pairs, "prompt_per_second"), - "decode": throughput(pairs, "predicted_per_second"), - "categories": categories, - "cases": cases, - }, - "initial_requests": initial_requests(base, candidate), - "pairs": pairs, - } - output.parent.mkdir(parents=True, exist_ok=True) - old_mask = os.umask(0o077) try: - with output.open("x", encoding="utf-8") as file: - json.dump(report, file, indent=2, ensure_ascii=False) - file.write("\n") - finally: - os.umask(old_mask) - print(json.dumps(report["summary"], indent=2)) + repository = Path(__file__).resolve().parent.parent + if args.output.is_symlink(): + reject("output must not be a symbolic link") + output = args.output.resolve() + if output == repository or repository in output.parents or any((parent / ".git").exists() for parent in output.parents): + reject("output must be outside Git repositories") + base, candidate = load_report(args.baseline), load_report(args.candidate) + report = {"schema": 1, "created_utc": dt.datetime.now(dt.timezone.utc).isoformat(), + "baseline_report": str(args.baseline.resolve()), "candidate_report": str(args.candidate.resolve()), + "baseline_metadata": base.get("metadata", {}), "candidate_metadata": candidate.get("metadata", {}), + "comparison_limit": LIMITATION, **compare(base, candidate)} + payload = (json.dumps(report, indent=2, ensure_ascii=False, allow_nan=False) + "\n").encode("utf-8") + old_mask = os.umask(0o077) + try: + output.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + fd = os.open(output, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + finally: + os.umask(old_mask) + try: + with os.fdopen(fd, "wb") as destination: + destination.write(payload) + except BaseException: + output.unlink(missing_ok=True) + raise + summary = report["summary"] + print(json.dumps({"pairs": summary["pairs"], + "baseline_quality_passed": summary["baseline_quality_passed"], + "candidate_quality_passed": summary["candidate_quality_passed"], + "same_normalized_output": summary["same_normalized_output"], + "failed_quality_category_count": len(summary["failed_quality_categories"]), + "performance_qualified": False, "model_quality_qualified": False})) + except (ValueError, TypeError, OverflowError, RecursionError): + print("paired report rejected: invalid or incompatible report data", file=sys.stderr) + return 1 + except OSError: + print("paired report rejected: private input/output unavailable or output already exists", file=sys.stderr) + return 1 + return 0 if __name__ == "__main__": - main() + raise SystemExit(main()) diff --git a/scripts/render-paired-report.py b/scripts/render-paired-report.py new file mode 100644 index 00000000..00bf0c87 --- /dev/null +++ b/scripts/render-paired-report.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +"""Render a private descriptive paired JSON report as private Markdown.""" + +import argparse +import html +import json +import math +import os +from pathlib import Path + +MAX_BYTES = 16 * 1024 * 1024 +MAX_GROUPS = 1000 + + +def count(value, ceiling=None): + if type(value) is not int or value < 0 or (ceiling is not None and value > ceiling): + raise ValueError("invalid count") + return value + + +def number(value): + if type(value) not in (int, float) or not math.isfinite(value) or value <= 0: + raise ValueError("invalid measurement") + return f"{value:.6g}" + + +def label(value): + if not isinstance(value, str) or not value or len(value) > 256: + raise ValueError("invalid group label") + return html.escape(value).replace("|", "|").replace("`", "`").replace("\n", " ").replace("\r", " ").replace("[", "[").replace("]", "]") + + +def distribution_row(name, distribution, expected): + n = count(distribution["sample_count"], expected) + if n != expected or not n: + raise ValueError("distribution count does not match") + values = [number(distribution[key]) for key in ("mean", "median", "p10", "p90")] + if not distribution["p10"] <= distribution["median"] <= distribution["p90"]: + raise ValueError("invalid percentiles") + small = distribution["small_sample"] + if type(small) is not bool or small != (n < 30): + raise ValueError("invalid sample warning") + interval = distribution.get("median_confidence_interval") + bounds = "not reported" + if interval is not None: + available = interval["finite_interval_available"] + if type(available) is not bool: + raise ValueError("invalid interval availability") + level = interval["confidence_level"] + number(level) + if level > 1: + raise ValueError("invalid confidence level") + if available: + lower, upper = interval["lower"], interval["upper"] + low_text, high_text = number(lower), number(upper) + if not lower <= distribution["median"] <= upper: + raise ValueError("invalid confidence interval") + bounds = f"{level * 100:.6g}%: [{low_text}, {high_text}]" + else: + if interval["lower"] is not None or interval["upper"] is not None: + raise ValueError("unavailable interval has bounds") + bounds = "insufficient pairs for finite interval" + warning = "small sample (<30 pairs)" if small else "30+ pairs; still descriptive" + return f"| {name} | {n} | {' | '.join(values)} | {bounds} | {warning} |" + + +def render(report): + if not isinstance(report, dict) or type(report.get("schema")) is not int or report["schema"] != 1: + raise ValueError("unsupported report") + summary = report["summary"] + pairs = count(summary["pairs"]) + if not pairs: + raise ValueError("empty report") + baseline = count(summary["baseline_quality_passed"], pairs) + candidate = count(summary["candidate_quality_passed"], pairs) + same = count(summary["same_normalized_output"], pairs) + ratio = number(summary["candidate_over_baseline_wall_median_ratio"]) + lines = ["# Descriptive paired comparison", "", + "Sequential loads and synthetic fixtures may confound this comparison. " + "These numbers do not qualify GPU inference, model quality, or a performance improvement.", "", + "## Aggregate", "", "| Metric | Value |", "| --- | ---: |", + f"| Measured pairs | {pairs} |", + f"| Baseline quality checks passed | {baseline}/{pairs} |", + f"| Candidate quality checks passed | {candidate}/{pairs} |", + f"| Same normalized output | {same}/{pairs} |", + f"| Candidate/baseline median wall ratio (lower is faster) | {ratio} |"] + if "initial_request_quality_failed" in summary: + initial_failed = count(summary["initial_request_quality_failed"], pairs) + lines.append(f"| Initial requests failing quality checks | {initial_failed} |") + lines += ["", + "## Categories", "", "Any failing category remains a failed gate; aggregate results cannot hide it.", "", + "| Category | Pairs | Both quality checks passed | Same output | Wall ratio | Observed checks |", + "| --- | ---: | ---: | ---: | ---: | --- |"] + groups = summary["categories"] + if not isinstance(groups, dict) or not groups or len(groups) > MAX_GROUPS: + raise ValueError("invalid categories") + total = total_same = total_both_quality = 0 + for name, group in sorted(groups.items()): + n = count(group["pairs"], pairs) + if not n: + raise ValueError("empty category") + total += n + quality = count(group["both_quality_passed"], n) + same_group = count(group["same_normalized_output"], n) + total_same += same_group + total_both_quality += quality + wall = number(group["candidate_over_baseline_wall_median_ratio"]) + verdict = "PASS (observed only)" if quality == same_group == n else "FAIL" + lines.append(f"| {label(name)} | {n} | {quality}/{n} | {same_group}/{n} | {wall} | {verdict} |") + if total != pairs or total_same != same or total_both_quality > min(baseline, candidate): + raise ValueError("category counts do not match") + lines += ["", "## Throughput", "", + "Optional timings cover only pairs with measurements in both arms.", "", + "| Timing | Pairs | Baseline median tok/s | Candidate median tok/s | Candidate/baseline ratio |", + "| --- | ---: | ---: | ---: | ---: |"] + for name in ("prefill", "decode"): + timing = summary.get(name) + if timing is None: + lines.append(f"| {name} | 0 | unavailable | unavailable | unavailable |") + continue + n = count(timing["pairs"], pairs) + if not n: + raise ValueError("empty timing") + b = number(timing["baseline_median_tokens_per_second"]) + c = number(timing["candidate_median_tokens_per_second"]) + r = number(timing["candidate_over_baseline_median_ratio"]) + lines.append(f"| {name} | {n} | {b} | {c} | {r} |") + distributions = [] + for name, group in [("Aggregate", summary), *[(label(k), v) for k, v in sorted(groups.items())]]: + for arm in ("baseline", "candidate"): + value = group.get("wall_seconds", {}).get(arm) + if value is not None: + distributions.append(distribution_row(f"{name}: {arm} wall seconds", value, group["pairs"])) + value = group.get("candidate_over_baseline_wall_ratio_distribution") + if value is not None: + distributions.append(distribution_row(f"{name}: wall ratio", value, group["pairs"])) + for name in ("prefill", "decode"): + timing = summary.get(name) + if timing is not None: + for key in ("baseline_distribution", "candidate_distribution", "candidate_over_baseline_ratio_distribution"): + if key in timing: + distributions.append(distribution_row(f"{name}: {key.replace('_', ' ')}", timing[key], timing["pairs"])) + if distributions: + lines += ["", "## Distributions and uncertainty", "", + "Intervals describe paired medians under independent-pair assumptions. " + "Repeated cases, sequential loads and cache drift limit their interpretation.", "", + "| Measurement | Pairs | Mean | Median | P10 | P90 | Median interval | Sample limit |", + "| --- | ---: | ---: | ---: | ---: | ---: | --- | --- |", *distributions] + lines += ["", "Raw responses, tool arguments, and private metadata values are omitted.", ""] + return "\n".join(lines) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("report", type=Path) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + try: + output = args.output.resolve() + if any((parent / ".git").exists() for parent in (output, *output.parents)): + raise ValueError("output must be outside Git") + with args.report.open("rb") as source: + data = source.read(MAX_BYTES + 1) + if len(data) > MAX_BYTES: + raise ValueError("report too large") + document = render(json.loads(data)) + output.parent.mkdir(parents=True, exist_ok=True) + fd = os.open(output, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + try: + with os.fdopen(fd, "w", encoding="utf-8") as target: + target.write(document) + except BaseException: + output.unlink() + raise + except (ValueError, KeyError, TypeError, OSError, RecursionError): + parser.exit(1, "paired Markdown report refused: invalid input or unavailable private output\n") + print("Private descriptive Markdown report written.") + + +if __name__ == "__main__": + main() diff --git a/scripts/test-benchmark-harness.py b/scripts/test-benchmark-harness.py index 3fa7c285..2e8de478 100644 --- a/scripts/test-benchmark-harness.py +++ b/scripts/test-benchmark-harness.py @@ -28,7 +28,8 @@ class Handler(http.server.BaseHTTPRequestHandler): body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) if "tools" in body: message = {"role": "assistant", "content": None, - "tool_calls": [{"function": {"name": "get_weather", + "tool_calls": [{"id": "call_fixture_weather", "type": "function", + "function": {"name": "get_weather", "arguments": '{"city":"Paris"}'}}]} finish = "tool_calls" else: @@ -117,6 +118,15 @@ def main(): assert sequential["candidate_quality_passed"] == 3 assert sequential["decode"]["pairs"] == 3 assert sequential["prefill"]["candidate_over_baseline_median_ratio"] == 1.0 + markdown = private / "sequential-comparison.md" + rendered = subprocess.run([ + "python3", str(root / "scripts/render-paired-report.py"), + str(compared), "--output", str(markdown), + ], check=True, capture_output=True, text=True) + assert stat.S_IMODE(markdown.stat().st_mode) == 0o600 + assert TOKEN not in markdown.read_text() + rendered.stdout + rendered.stderr + assert "Distributions and uncertainty" in markdown.read_text() + assert "insufficient pairs for finite interval" in markdown.read_text() finally: server.shutdown() server.server_close() diff --git a/scripts/test-paired-markdown.py b/scripts/test-paired-markdown.py new file mode 100644 index 00000000..23eeb78e --- /dev/null +++ b/scripts/test-paired-markdown.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +"""Owned synthetic CLI tests for private paired Markdown publication.""" + +import copy +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +SCRIPT = Path(__file__).with_name("render-paired-report.py") + + +class MarkdownTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory(prefix="leleka-paired-md-") + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.source = self.root / "input.json" + self.output = self.root / "report.md" + self.report = {"schema": 1, "metadata": {"private": "PRIVATE_VALUE"}, + "pairs": [{"response": "PRIVATE_RESPONSE"}], "summary": { + "pairs": 2, "baseline_quality_passed": 2, "candidate_quality_passed": 1, + "same_normalized_output": 1, "candidate_over_baseline_wall_median_ratio": 0.8, + "categories": {"tool|