Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(benchmarks): bound cross-encoder evidence size
svonava445c5b303a15
diff --git a/tools/benchmarks/cross_encoder_lora/README.md b/tools/benchmarks/cross_encoder_lora/README.mdindex 988ac98fe..12530dc1f 100644--- a/tools/benchmarks/cross_encoder_lora/README.md+++ b/tools/benchmarks/cross_encoder_lora/README.md@@ -106,7 +106,10 @@ list-append overhead; this is an SDK workload measurement.Actual timed C4/C16 batch shapes are **unknown**. Their raw four-score vectorsare compared diagnostically against complete preselection oracle vectors at-`1e-6`, with matching shapes and ambiguity recorded. A diagnostic cannot combine+`1e-6`. Each response records one deterministic matching oracle reference, or+null if none matches. This witness does not identify the actual shape or imply+a unique match: the retained raw vector and complete oracle corpus allow every+match and its ambiguity to be recomputed. A diagnostic cannot combinedifferent oracle shapes per element or substitute for the separately observedshape-qualified replays. Timed C1 has one outstanding four-document request andmust still match its preselection result at `1e-6`. This measurement is scoped to@@ -130,7 +133,11 @@ the observed untimed replays supply that evidence instead.## Evidence and CPU checks-`summary.json` retains trial outcomes, statistical gates and source hashes.+`summary.json` schema 2 retains trial outcomes, aggregate metrics, statistical+gates and source hashes. Each entry links its complete `trial.json` by relative+path and SHA-256; raw request arrays and oracle corpora stay in those per-trial+files instead of being copied into the growing summary. Final cross-process+checks reopen the complete records and verify their hashes and identities.The summary also hashes the complete benchmark file manifest. Each trialcaptures the full installed-distribution manifest; its digest must remainidentical across arms. An optional `--environment-receipt` attaches a separate@@ -142,6 +149,13 @@ hashes, library versions and shutdown status. Failure paths retain completedphases and partial request samples. Hash evidence files when archiving them;the runner records each terminal trial file hash.+The compact representation follows an incomplete run whose stdout archive was+truncated. Its old evidence stays separate and is not acceptance evidence. This+change affects only post-measurement diagnostics and storage, not the timed+path, workload, numerical tolerances, statistical gates, or raw observations.+Store the evidence directory on durable storage and verify the full archive+hash after retrieval; stdout is unsuitable for transferring large artifacts.+```consolemise run test -- tools/benchmarks/cross_encoder_lora/tests/test_probe.pymise run typecheck -- tools/benchmarks/cross_encoder_loradiff --git a/tools/benchmarks/cross_encoder_lora/runner.py b/tools/benchmarks/cross_encoder_lora/runner.pyindex 9195caf95..bc8c078bb 100644--- a/tools/benchmarks/cross_encoder_lora/runner.py+++ b/tools/benchmarks/cross_encoder_lora/runner.py@@ -132,11 +132,61 @@ def stop(process: subprocess.Popen) -> None:process.wait(timeout=KILL_GRACE_SECONDS)+def trial_summary(trial: dict[str, Any]) -> dict[str, Any]:+ """Keep the cumulative index independent of the number of raw requests."""+ fields = (+ "pair",+ "arm",+ "passed",+ "shutdown_complete",+ "smoke",+ "pid",+ "process_returncode",+ "source_commit",+ "terminal_record",+ "terminal_record_sha256",+ "error",+ "runner_error",+ )+ result = {field: trial[field] for field in fields if field in trial}+ if "performance" in trial:+ metrics = ("concurrency", "count", "elapsed_s", "mean_ms", "p95_ms", "rps", "actual_timed_batch_shape")+ result["performance"] = {+ concurrency: {field: phase[field] for field in metrics if field in phase}+ for concurrency, phase in trial["performance"].items()+ }+ return result+++def load_trial(output: Path, record: dict[str, Any]) -> dict[str, Any]:+ """Reopen the complete evidence only after checking its recorded identity."""+ relative = f"trial-{record['pair']}-{record['arm']}/trial.json"+ require(record["terminal_record"] == relative, "unexpected terminal record path")+ path = output / relative+ require(path.resolve().is_relative_to(output.resolve()), "terminal record path escapes output")+ require(digest(path) == record["terminal_record_sha256"], "terminal record hash differs")+ trial = json.loads(path.read_text())+ require((trial["pair"], trial["arm"]) == (record["pair"], record["arm"]), "terminal record identity differs")+ for field, value in trial_summary(trial).items():+ if field == "passed" and "runner_error" in record:+ # A process timeout can invalidate an otherwise successful worker+ # record. The runner's failed verdict must survive that override.+ require(record[field] is False, "runner error lost its failed verdict")+ else:+ require(record.get(field) == value, "terminal record summary differs")+ if "runner_error" in record:+ trial["passed"] = False+ trial["runner_error"] = record["runner_error"]+ if "process_returncode" in record:+ trial["process_returncode"] = record["process_returncode"]+ return trial++def run(args: argparse.Namespace) -> dict[str, Any]:args.output.mkdir(parents=True, exist_ok=False)manifest = extract(args.inputs.resolve(), args.output / "sources")summary: dict[str, Any] = {- "schema": 1,+ "schema": 2,"passed": False,"source_manifest": manifest,"harness_manifest": harness_manifest(),@@ -218,10 +268,15 @@ def run(args: argparse.Namespace) -> dict[str, Any]:trial["terminal_record_sha256"] = (digest(directory / "trial.json") if (directory / "trial.json").exists() else None)+ trial["terminal_record"] = (+ str((directory / "trial.json").relative_to(args.output))+ if trial["terminal_record_sha256"] is not None+ else None+ )if pending_error is not None:trial["passed"] = Falsetrial["runner_error"] = {"type": type(pending_error).__name__, "message": str(pending_error)}- summary["trials"].append(trial)+ summary["trials"].append(trial_summary(trial))atomic_json(summary_path, summary)if pending_error is not None:raise pending_error@@ -234,8 +289,9 @@ def run(args: argparse.Namespace) -> dict[str, Any]:summary["passed"] = Truesummary["qualification"] = Falseelse:- summary["correctness_memory"] = cross_checks(summary["trials"])- summary["statistics"] = compare(summary["trials"])+ complete_trials = [load_trial(args.output, row) for row in summary["trials"]]+ summary["correctness_memory"] = cross_checks(complete_trials)+ summary["statistics"] = compare(complete_trials)summary["passed"] = summary["statistics"]["passed"]require(summary["passed"], "fixed non-inferiority gates did not pass")except BaseException as error:diff --git a/tools/benchmarks/cross_encoder_lora/tests/test_evidence_size.py b/tools/benchmarks/cross_encoder_lora/tests/test_evidence_size.pynew file mode 100644index 000000000..0ea45f796--- /dev/null+++ b/tools/benchmarks/cross_encoder_lora/tests/test_evidence_size.py@@ -0,0 +1,223 @@+"""Raw observations remain revalidatable without multiplying diagnostic copies."""++from __future__ import annotations++import json+from pathlib import Path+from typing import Any++import pytest++from tools.benchmarks.cross_encoder_lora import runner+from tools.benchmarks.cross_encoder_lora.evidence import atomic_json, digest, vector_delta+from tools.benchmarks.cross_encoder_lora.protocol import ORDERS, RESTORE_ATOL+from tools.benchmarks.cross_encoder_lora.tests.test_runner_budget import arguments, setup_sources+from tools.benchmarks.cross_encoder_lora.worker import ORDER, matching_vector+++def corpus() -> tuple[list[float], dict[str, Any]]:+ scores = [1.0, 2.0, 3.0, 4.0]+ oracles = {+ f"workload-{copies:02d}": {+ "copies": copies,+ "scores": [scores[index] for index in ORDER for _ in range(copies)],+ }+ for copies in range(1, 17)+ }+ return scores, oracles+++def oracle_vector(oracles: dict[str, Any], reference: dict[str, Any]) -> list[float]:+ # Deliberately reconstruct independently of the matcher, in request order.+ oracle = oracles[reference["workload_sha256"]]+ assert reference["copies"] == oracle["copies"]+ offset = reference["request_position"]+ groups = {+ item: oracle["scores"][index * oracle["copies"] : (index + 1) * oracle["copies"]]+ for index, item in enumerate(ORDER)+ }+ return [groups[item][offset] for item in range(4)]+++def test_all_136_matches_have_bounded_reconstructible_witness() -> None:+ scores, oracles = corpus()+ reference = matching_vector(scores, oracles)+ assert reference == {"workload_sha256": "workload-01", "copies": 1, "request_position": 0}+ assert matching_vector(scores, dict(reversed(list(oracles.items())))) == reference+ raw = [+ {+ "label": str(index),+ "scores": scores,+ "latency_ms": 1.0 + index / 1000,+ "responses": [{"status": 200}],+ "diagnostic_matching_oracle": matching_vector(scores, oracles),+ }+ for index in range(1000)+ ]+ encoded = json.dumps({"shape_oracles": oracles, "samples": raw})+ assert len(encoded) < 260_000 # Independent of repeating all 136 witnesses per response.+ recovered = json.loads(encoded)+ for original, row in zip(raw, recovered["samples"], strict=True):+ assert row == original+ witness = oracle_vector(recovered["shape_oracles"], row["diagnostic_matching_oracle"])+ assert vector_delta(row["scores"], witness) <= RESTORE_ATOL+ all_matches = [+ {"workload_sha256": key, "copies": oracle["copies"], "request_position": position}+ for key, oracle in recovered["shape_oracles"].items()+ for position in range(oracle["copies"])+ if vector_delta(+ scores,+ oracle_vector(+ recovered["shape_oracles"],+ {"workload_sha256": key, "copies": oracle["copies"], "request_position": position},+ ),+ )+ <= RESTORE_ATOL+ ]+ assert len(all_matches) == 136 # Ambiguity is reconstructible, not asserted away.+ assert matching_vector([1.0, 2.0, 3.0, 4.0 + 2 * RESTORE_ATOL], oracles) is None+++def terminal(directory: Path, pair: int, arm: str, *, failed: bool = False) -> dict[str, Any]:+ scores, oracles = corpus()+ rows = [+ {+ "label": str(index),+ "scores": scores,+ "latency_ms": 10.0,+ "responses": [+ {"status": 503, "code": "TEST_FAILURE", "body": "retained error"} if failed else {"status": 200}+ ],+ }+ for index in range(500)+ ]+ trial = {+ "pair": pair,+ "arm": arm,+ "passed": not failed,+ "shutdown_complete": not failed,+ "shape_oracles": oracles,+ "performance": {+ str(concurrency): {+ "count": len(rows),+ "mean_ms": 10.0,+ "p95_ms": 10.0,+ "rps": 100.0,+ "samples": rows,+ "future_raw_field": rows,+ }+ for concurrency in (1, 4, 16)+ },+ }+ if failed:+ trial["error"] = {"type": "RuntimeError", "message": "retained failure"}+ directory.mkdir(parents=True)+ atomic_json(directory / "trial.json", trial)+ return trial+++def test_summary_size_is_bounded_and_final_checks_reopen_every_trial(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ setup_sources(monkeypatch)+ monkeypatch.setattr(runner, "extract", lambda *_: {"sources": {arm: {"commit": arm} for arm in ("B", "candidate")}})+ monkeypatch.setattr(runner.time, "monotonic", lambda: 100.0)++ class CompletedProcess:+ returncode = 0++ def wait(self, *, timeout: float) -> int:+ return self.returncode++ def poll(self) -> int:+ return self.returncode++ def start(command: list[str], **_kwargs: Any) -> CompletedProcess:+ def value(flag: str) -> str:+ return command[command.index(flag) + 1]++ terminal(Path(value("--output")), int(value("--pair")), value("--arm"))+ return CompletedProcess()++ full_records = []++ def inspect(trials: list[dict[str, Any]]) -> dict[str, Any]:+ full_records.extend(trials)+ assert len(trials) == 18+ for trial in trials:+ assert len(trial["shape_oracles"]) == 16+ for phase in trial["performance"].values():+ assert len(phase["samples"]) == 500+ assert phase["samples"][0]["scores"] == [1.0, 2.0, 3.0, 4.0]+ assert phase["samples"][0]["responses"] == [{"status": 200}]+ return {"passed": True}++ monkeypatch.setattr(runner.subprocess, "Popen", start)+ monkeypatch.setattr(runner, "cross_checks", inspect)+ args = arguments(tmp_path, 3000)+ args.smoke = False+ summary = runner.run(args)+ assert summary["schema"] == 2+ assert summary["passed"]+ assert len(full_records) == 18+ encoded = (args.output / "summary.json").read_bytes()+ assert len(encoded) < 30_000+ assert b'"samples"' not in encoded+ assert b'"shape_oracles"' not in encoded+ assert b'"future_raw_field"' not in encoded+ for record, (pair, arm) in zip(+ summary["trials"], ((i, arm) for i, order in enumerate(ORDERS) for arm in order), strict=True+ ):+ assert record["terminal_record"] == f"trial-{pair}-{arm}/trial.json"+ assert record["terminal_record_sha256"] == digest(args.output / record["terminal_record"])+++def test_failed_raw_record_survives_compaction_and_refs_reject_tampering(tmp_path: Path) -> None:+ path = tmp_path / "trial-0-R/trial.json"+ trial = terminal(path.parent, 0, "R", failed=True)+ trial.update(+ terminal_record="trial-0-R/trial.json",+ terminal_record_sha256=digest(path),+ process_returncode=-9,+ runner_error={"type": "TimeoutExpired", "message": "owned worker stopped"},+ )+ record = runner.trial_summary(trial)+ assert not record["passed"]+ assert not record["shutdown_complete"]+ assert record["error"] == trial["error"]+ assert record["runner_error"] == trial["runner_error"]+ assert record["process_returncode"] == -9+ raw = runner.load_trial(tmp_path, record)+ assert raw["performance"]["1"]["samples"] == trial["performance"]["1"]["samples"]+ changed = json.loads(json.dumps(record))+ changed["performance"]["1"]["mean_ms"] = 9.0+ with pytest.raises(AssertionError, match="summary differs"):+ runner.load_trial(tmp_path, changed)+ with pytest.raises(AssertionError, match="record path"):+ runner.load_trial(tmp_path, {**record, "terminal_record": "../trial.json"})+ path.write_text(path.read_text() + "\n")+ with pytest.raises(AssertionError, match="record hash"):+ runner.load_trial(tmp_path, record)+ raw["pair"] = 1+ atomic_json(path, raw)+ with pytest.raises(AssertionError, match="identity"):+ runner.load_trial(tmp_path, {**record, "terminal_record_sha256": digest(path)})+++def test_runner_failure_override_never_turns_into_success(tmp_path: Path) -> None:+ path = tmp_path / "trial-0-R/trial.json"+ trial = terminal(path.parent, 0, "R")+ trial.update(+ terminal_record="trial-0-R/trial.json",+ terminal_record_sha256=digest(path),+ passed=False,+ runner_error={"type": "TimeoutExpired", "message": "owned worker stopped"},+ )+ record = runner.trial_summary(trial)+ reopened = runner.load_trial(tmp_path, record)+ assert not reopened["passed"]+ assert reopened["runner_error"] == record["runner_error"]+ assert json.loads(path.read_text())["passed"] # The original raw file remains unchanged.+ assert not record["passed"]+ with pytest.raises(AssertionError, match="lost its failed verdict"):+ runner.load_trial(tmp_path, {**record, "passed": True})diff --git a/tools/benchmarks/cross_encoder_lora/tests/test_probe.py b/tools/benchmarks/cross_encoder_lora/tests/test_probe.pyindex eb820a77a..5fed4ea86 100644--- a/tools/benchmarks/cross_encoder_lora/tests/test_probe.py+++ b/tools/benchmarks/cross_encoder_lora/tests/test_probe.py@@ -21,7 +21,7 @@ from tools.benchmarks.cross_encoder_lora.evidence import Evidence, atomic_json,from tools.benchmarks.cross_encoder_lora.fixtures import preparefrom tools.benchmarks.cross_encoder_lora.protocol import BASE_REVISION, ORDERS, compare, paired_gate, percentilefrom tools.benchmarks.cross_encoder_lora.runner import ROOT, extract, source_environment-from tools.benchmarks.cross_encoder_lora.worker import ORDER, describe_response, matching_vectors, validate_response+from tools.benchmarks.cross_encoder_lora.worker import ORDER, describe_response, matching_vector, validate_responsedef tiny_snapshot(directory: Path) -> Path:@@ -280,8 +280,8 @@ def test_timed_diagnostics_require_one_complete_oracle_vector() -> None:"first": {"copies": 1, "scores": [first[index] for index in ORDER]},"second": {"copies": 2, "scores": [second[index] for index in ORDER for _ in range(2)]},}- assert matching_vectors(first, oracles) == [{"workload_sha256": "first", "copies": 1, "request_position": 0}]- assert matching_vectors([0.0, 11.0, 2.0, 13.0], oracles) == []+ assert matching_vector(first, oracles) == {"workload_sha256": "first", "copies": 1, "request_position": 0}+ assert matching_vector([0.0, 11.0, 2.0, 13.0], oracles) is Nonedef test_hidden_retry_rejected_and_malformed_error_retained() -> None:diff --git a/tools/benchmarks/cross_encoder_lora/tests/test_runner_budget.py b/tools/benchmarks/cross_encoder_lora/tests/test_runner_budget.pyindex 7f9810410..f755de8e1 100644--- a/tools/benchmarks/cross_encoder_lora/tests/test_runner_budget.py+++ b/tools/benchmarks/cross_encoder_lora/tests/test_runner_budget.py@@ -116,7 +116,7 @@ def test_full_timeout_cleanup_finishes_before_budget_and_retains_partial_trial("arm": "R","passed": False,"shutdown_complete": False,- "performance": {"1": {"completed_samples": 7}},+ "performance": {"1": {"count": 7}},}))@@ -132,6 +132,6 @@ def test_full_timeout_cleanup_finishes_before_budget_and_retains_partial_trial(terminal = json.loads((args.output / "summary.json").read_text())assert not terminal["passed"]trial = terminal["trials"][0]- assert trial["performance"]["1"]["completed_samples"] == 7+ assert trial["performance"]["1"]["count"] == 7assert trial["process_returncode"] == -9assert trial["runner_error"]["type"] == "TimeoutExpired"diff --git a/tools/benchmarks/cross_encoder_lora/worker.py b/tools/benchmarks/cross_encoder_lora/worker.pyindex b8dcd9c8a..33269264a 100644--- a/tools/benchmarks/cross_encoder_lora/worker.py+++ b/tools/benchmarks/cross_encoder_lora/worker.py@@ -328,15 +328,21 @@ def unobserved(adapter: Any) -> Iterator[None]:)-def matching_vectors(scores: list[float], oracles: dict[str, Any]) -> list[dict[str, Any]]:- matches = []- for key, oracle_row in oracles.items():+def matching_vector(scores: list[float], oracles: dict[str, Any]) -> dict[str, Any] | None:+ """Return one deterministic diagnostic witness, never actual batch attribution.++ The full oracle corpus and raw score vector are retained separately, so all+ matches (including ambiguity) can be recomputed without repeating up to 136+ equivalent descriptions on every response.+ """+ for key in sorted(oracles):+ oracle_row = oracles[key]copies = oracle_row["copies"]for position in range(copies):vector = [oracle_row["scores"][ORDER.index(index) * copies + position] for index in range(REQUEST_ITEMS)]if vector_delta(scores, vector) <= RESTORE_ATOL:- matches.append({"workload_sha256": key, "copies": copies, "request_position": position})- return matches+ return {"workload_sha256": key, "copies": copies, "request_position": position}+ return Nonedef performance(url: str, concurrency: int, evidence: Evidence, *, smoke: bool) -> dict[str, Any]:@@ -727,13 +733,13 @@ async def experiment(args: argparse.Namespace, evidence: Evidence, summary: dictrequire(row["result"]["usage"] == bases[0]["result"]["usage"], "timed SDK usage differs")if concurrency == 1:require(vector_delta(row["scores"], baseline) <= RESTORE_ATOL, "timed C1 base output differs")- row["diagnostic_matching_oracles"] = matching_vectors(row["scores"], summary["shape_oracles"])+ row["diagnostic_matching_oracle"] = matching_vector(row["scores"], summary["shape_oracles"])measured["actual_timed_batch_shape"] = "unobserved"evidence.emit("timed_output_diagnostics",concurrency=concurrency,- matches=[- {"label": row["label"], "matches": row["diagnostic_matching_oracles"]}+ witnesses=[+ {"label": row["label"], "match": row["diagnostic_matching_oracle"]}for row in measured["samples"]],)