Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

test(cross-encoder): add paired runtime LoRA qualification

svonava3d9993c35e8e
diff --git a/tools/benchmarks/cross_encoder_lora/.gitignore b/tools/benchmarks/cross_encoder_lora/.gitignore
new file mode 100644
index 000000000..5b3c90724
--- /dev/null
+++ b/tools/benchmarks/cross_encoder_lora/.gitignore
@@ -0,0 +1,2 @@
+_inputs/
+_evidence/
diff --git a/tools/benchmarks/cross_encoder_lora/README.md b/tools/benchmarks/cross_encoder_lora/README.md
new file mode 100644
index 000000000..988ac98fe
--- /dev/null
+++ b/tools/benchmarks/cross_encoder_lora/README.md
@@ -0,0 +1,154 @@
+# CrossEncoder runtime LoRA qualification
+
+This probe measures the ordinary `CrossEncoderAdapter` using the real SIE loader,
+worker, loopback HTTP API and `sie_sdk.SIEClient`. It does not provision compute,
+install dependencies, change precision, or change the production catalog. The
+catalog model is overridden locally to use the ordinary adapter rather than the
+catalog's BertFlash implementation.
+
+The fixed checkpoint is `cross-encoder/ms-marco-MiniLM-L-6-v2` at
+`c5ee24cb16019beea0893ab7796b1df96625c6b8`; `model.safetensors` must hash to
+`821d1aa69520101d6e0737f78a042ae25b19e5cb9160701909d10434f4aeb0ae`.
+Fixtures A/B/C are deterministic, untrained rank-4, alpha-8, bias-free LoRAs on
+every BERT encoder query/value projection. They establish reversible numerical
+effects and lifecycle behavior, **not retrieval quality**. Source seeds, model
+files and adapter files are hashed in the fixture manifest.
+
+## Prepare immutable sources and fixtures
+
+From a clean public checkout with the candidate committed:
+
+```console
+mise tasks
+mise exec -- uv run --no-sync python -m tools.benchmarks.cross_encoder_lora.prepare --candidate HEAD --output /tmp/ce-sources
+mise exec -- uv run --no-sync python -m tools.benchmarks.cross_encoder_lora.fixtures --output /tmp/ce-fixtures
+```
+
+The preparer resolves refs once, archives baseline
+`d5e024ad3ba6127b1ee176e2c85c794b76077888` and the candidate by full commit ID,
+and refuses differing dependency locks. Keep the archives with their manifest.
+The same benchmark code observes every arm; `PYTHONPATH` selects the archived
+server and SDK. No arm runs a dependency sync. Pass `--snapshot` to both fixture
+preparation and the runner when using a retained public checkpoint directory;
+the worker checks its full recorded file manifest before loading it.
+
+Prepare one Linux L4 environment using the public lock. The qualification
+preflight requires Torch `2.9.1+cu129`, Transformers `4.57.6`,
+SentenceTransformers `5.4.1`, PEFT `0.19.1`, and **no installed `torchao`**.
+Four Torch intra-op threads and one inter-op thread are fixed. Default CUDA
+precision remains unchanged (fp16 for this adapter). Record any environment
+preparation separately, including installed versions before and after; the
+benchmark only inspects them and fails on a mismatch.
+
+```console
+mise exec -- uv run --no-sync python -m tools.benchmarks.cross_encoder_lora.runner \
+ --inputs /tmp/ce-sources --fixtures /tmp/ce-fixtures \
+ --output /tmp/ce-evidence --deadline-s 1740 --trial-deadline-s 120
+```
+
+Use a fresh output directory. Set the outer compute-session deadline before
+launching, allowing bounded startup and cleanup. The runner owns and joins only
+its subprocesses; it cannot terminate an external GPU session. The operator
+must stop that exact session and record cleanup. A failed or incomplete trial
+stops the experiment and retains its evidence. Never change thresholds or drop
+failed trials to obtain a pass.
+
+## Frozen comparison
+
+There are six fresh-process blocks, in order `BNR`, `NRB`, `RBN`, `BRN`, `RNB`,
+`NBR` (18 fresh servers). B uses the pinned baseline with no declared LoRA.
+N uses the candidate with no declared LoRA. R uses the candidate after A/B
+activity, with base selected and two adapters resident but disabled.
+
+Every arm uses the same password-reset query and four documents in `protocol.py`.
+Each phase starts with 30 sequential warmup requests. C1 measures 200 sequential
+requests; C4 and C16 each run a 12-second closed loop with one SDK client per
+lane. Throughput includes draining requests admitted before the deadline.
+Latencies use the nearest-rank p95. Neither warmup nor correctness calls enter
+the primary statistics.
+
+All six metrics are required for **both** N/B and R/B: C1 mean and p95 latency,
+C4/C16 requests per second and p95 latency. The statistical unit is the six
+paired blocks. Latency ratios are candidate/B; throughput ratios are B/candidate.
+For log ratios, the one-sided 95% t upper bound (df=5, critical
+`2.0150483733330233`) must be at most 1.03, the geometric point ratio at most
+1.01, and every paired ratio at most 1.10. A wide interval is inconclusive.
+
+Before selection, three SDK base results must be finite and stable at absolute
+tolerance `1e-6`. The public fp32 checkpoint oracle has a separately fixed `0.1`
+CUDA-fp16 compatibility bound. Every ordered batch shape of 4, 8, …, 64 pairs
+has two preselection oracle runs, stable at `1e-6`. Actual batches must match
+the corresponding ordered-workload fingerprint and shape; unexpected partial
+requests or ordering fail qualification. All candidate base oracles and observed
+untimed SDK replay outputs must match the corresponding B-block oracle at `1e-6`. This is
+deliberately strict and is never relaxed after measurement.
+
+R also checks cold `503 LORA_LOADING`, bounded fresh SDK retries, duplicate-load
+single-flight, undeclared-source rejection before fetch, distinct A/base/B
+effects, base restoration, real concurrent base/A/B isolation and same-selection
+cross-request batching. It records actual PEFT selection at model forward
+boundaries. Mutation cannot overlap a score forward. Base tensors and classifier,
+tokenizer and outer-wrapper identities remain unchanged. Churn exceeds the
+two-adapter capacity; final removal restores the original Linear objects,
+module tree and PEFT flags; same-instance reload and full model unload follow.
+Production fault-injection tests separately cover malformed artifacts and
+partial-attachment rollback; this probe does not pretend to reproduce them on
+every GPU trial.
+
+The hook records deep selection/logit details during correctness checks and
+two observed SDK replay rounds at C1/C4/C16. During timed phases the forward
+hook is removed and production `score_pairs` and `set_active_lora` are bound
+directly. The harness asserts that no observer activity occurred. Response
+validation and header decoding happen after the phase clock stops; exactly one
+successful HTTP response is required per warmup/measured SDK call, excluding
+hidden retries. The timed client retains timer, result-list and raw-response
+list-append overhead; this is an SDK workload measurement.
+
+Actual timed C4/C16 batch shapes are **unknown**. Their raw four-score vectors
+are compared diagnostically against complete preselection oracle vectors at
+`1e-6`, with matching shapes and ambiguity recorded. A diagnostic cannot combine
+different oracle shapes per element or substitute for the separately observed
+shape-qualified replays. Timed C1 has one outstanding four-document request and
+must still match its preselection result at `1e-6`. This measurement is scoped to
+the observed workload and environment; it does not establish zero overhead or
+support for other CrossEncoder architectures.
+
+After synchronization and GC, unadapted allocated GPU bytes must match B.
+R's additional allocation is bounded by measured unique adapter storage bytes
+rounded up to 512 bytes per storage. Final adapter removal must restore the
+initial allocated bytes. Reserved allocator memory, RSS, load duration and
+GPU clock/temperature/utilization are recorded separately, not conflated with
+live parameter allocation. The memory reference is captured after finite
+preselection base and shape-oracle warmup, before any LoRA attachment, to keep
+one-time CUDA library initialization separate from adapter storage.
+
+These observation changes are an explicit **preallocation protocol amendment**
+to the original plan of observing every timed forward. All trial orders,
+warmup/request counts, phase durations, numerical tolerances and statistical
+gates remain unchanged. The original timed batch-attribution claim is withdrawn;
+the observed untimed replays supply that evidence instead.
+
+## Evidence and CPU checks
+
+`summary.json` retains trial outcomes, statistical gates and source hashes.
+The summary also hashes the complete benchmark file manifest. Each trial
+captures the full installed-distribution manifest; its digest must remain
+identical across arms. An optional `--environment-receipt` attaches a separate
+operator preparation receipt and its SHA-256 (never include credentials).
+Each trial contains incremental `events.jsonl`, atomic `trial.json`, generated
+model configuration and a separate process log. It preserves raw request
+scores, ranks, IDs, usage, latencies, errors, batch membership, logits, tensor
+hashes, library versions and shutdown status. Failure paths retain completed
+phases and partial request samples. Hash evidence files when archiving them;
+the runner records each terminal trial file hash.
+
+```console
+mise run test -- tools/benchmarks/cross_encoder_lora/tests/test_probe.py
+mise run typecheck -- tools/benchmarks/cross_encoder_lora
+```
+
+The CPU suite serves a tiny real BERT model through the actual loader and SDK,
+uses real PEFT tensors, and checks correctness plus positive and negative
+statistical/provenance controls. Its deliberately shorter phases and CPU
+precision are labeled `qualification: false`; it is a harness smoke test,
+not acceptance evidence for the pinned MiniLM checkpoint or L4 performance.
diff --git a/tools/benchmarks/cross_encoder_lora/__init__.py b/tools/benchmarks/cross_encoder_lora/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tools/benchmarks/cross_encoder_lora/adapter.py b/tools/benchmarks/cross_encoder_lora/adapter.py
new file mode 100644
index 000000000..c1f41ac84
--- /dev/null
+++ b/tools/benchmarks/cross_encoder_lora/adapter.py
@@ -0,0 +1,94 @@
+"""Identical benchmark observation on both main and candidate adapters."""
+
+from __future__ import annotations
+
+import time
+from typing import Any
+
+from sie_server.adapters.cross_encoder import CrossEncoderAdapter
+
+
+class ObservedCrossEncoder(CrossEncoderAdapter):
+ def load(self, device: str) -> None:
+ self.batch_observations = []
+ self.selection_observations = []
+ self.observed_selection = None
+ self.observation_phase = "load"
+ self.capture_logits = True
+ self.active_forward = False
+ self.mutation_overlap = False
+ self.forward_observations = []
+ self.fetch_observations = []
+ super().load(device)
+ assert self._model is not None
+ self._observer_handle = self._model.model.register_forward_hook(self._observe_forward, with_kwargs=True)
+
+ def _observe_forward(self, model: Any, _args: Any, kwargs: Any, result: Any) -> None:
+ enabled = []
+ if self.capture_logits:
+ for name, module in model.named_modules():
+ if hasattr(module, "lora_A") and not getattr(module, "disable_adapters", False):
+ enabled.append({"module": name, "adapters": list(module.active_adapters)})
+ inputs = kwargs.get("input_ids")
+ row = {
+ "selection": self.observed_selection,
+ "enabled_adapters": enabled,
+ "input_shape": list(inputs.shape) if inputs is not None else None,
+ }
+ if self.capture_logits:
+ row["logits"] = result.logits.detach().float().cpu().tolist()
+ self.forward_observations.append(row)
+
+ def set_active_lora(self, lora_name: str | None) -> None:
+ if self.active_forward:
+ self.mutation_overlap = True
+ super().set_active_lora(lora_name)
+ self.observed_selection = lora_name
+ self.selection_observations.append({"time_ns": time.time_ns(), "selection": lora_name})
+
+ def score_pairs(self, queries: list, docs: list, **kwargs: Any) -> Any:
+ started = time.time_ns()
+ first_forward = len(self.forward_observations)
+ self.active_forward = True
+ try:
+ result = super().score_pairs(queries, docs, **kwargs)
+ self.batch_observations.append(
+ {
+ "start_ns": started,
+ "end_ns": time.time_ns(),
+ "selection": self.observed_selection,
+ "phase": self.observation_phase,
+ "queries": [item.text for item in queries],
+ "documents": [item.text for item in docs],
+ "item_ids": [item.id for item in docs],
+ "scores": result.scores.tolist(),
+ "input_token_counts": result.input_token_counts,
+ "forwards": self.forward_observations[first_forward:],
+ }
+ )
+ return result
+ finally:
+ self.active_forward = False
+
+ def load_lora(self, *args: Any, **kwargs: Any) -> int:
+ if self.active_forward:
+ self.mutation_overlap = True
+ return super().load_lora(*args, **kwargs)
+
+ def fetch_lora(self, *args: Any, **kwargs: Any) -> str:
+ self.fetch_observations.append(
+ {"time_ns": time.time_ns(), "name": args[0] if args else kwargs.get("lora_name")}
+ )
+ return super().fetch_lora(*args, **kwargs)
+
+ def unload_lora(self, *args: Any, **kwargs: Any) -> None:
+ if self.active_forward:
+ self.mutation_overlap = True
+ super().unload_lora(*args, **kwargs)
+
+ def unload(self) -> None:
+ handle = getattr(self, "_observer_handle", None)
+ if handle is not None:
+ handle.remove()
+ self._observer_handle = None
+ super().unload()
diff --git a/tools/benchmarks/cross_encoder_lora/evidence.py b/tools/benchmarks/cross_encoder_lora/evidence.py
new file mode 100644
index 000000000..cc9e0e080
--- /dev/null
+++ b/tools/benchmarks/cross_encoder_lora/evidence.py
@@ -0,0 +1,63 @@
+"""Incremental observations and atomic terminal records for the bounded probe."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import math
+import os
+import threading
+import time
+from pathlib import Path
+from typing import Any
+
+from tools.benchmarks.cross_encoder_lora.protocol import require
+
+
+def digest(path: Path) -> str:
+ return hashlib.sha256(path.read_bytes()).hexdigest()
+
+
+def fingerprint(value: Any) -> str:
+ return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()
+
+
+def atomic_json(path: Path, value: Any) -> None:
+ temporary = path.with_suffix(path.suffix + ".pending")
+ with temporary.open("w") as stream:
+ stream.write(json.dumps(value, indent=2, allow_nan=False) + "\n")
+ stream.flush()
+ os.fsync(stream.fileno())
+ temporary.replace(path)
+
+
+def vector_delta(left: list[float], right: list[float]) -> float:
+ require(len(left) == len(right) and bool(left), "score vector shape changed")
+ require(all(math.isfinite(value) for value in left + right), "nonfinite score")
+ return max(abs(x - y) for x, y in zip(left, right, strict=True))
+
+
+class Evidence:
+ def __init__(self, directory: Path) -> None:
+ self.directory = directory
+ directory.mkdir(parents=True, exist_ok=False)
+ self.lock = threading.Lock()
+
+ def emit(self, event: str, **fields: Any) -> dict[str, Any]:
+ row = {"event": event, "time_ns": time.time_ns(), **fields}
+
+ # Preserve nonfinite observations as explicit strings in failed evidence.
+ def finite(value: Any) -> Any:
+ if isinstance(value, float) and not math.isfinite(value):
+ return str(value)
+ if isinstance(value, dict):
+ return {key: finite(item) for key, item in value.items()}
+ if isinstance(value, (list, tuple)):
+ return [finite(item) for item in value]
+ return value
+
+ row = finite(row)
+ with self.lock, (self.directory / "events.jsonl").open("a") as stream:
+ stream.write(json.dumps(row, sort_keys=True, allow_nan=False) + "\n")
+ stream.flush()
+ return row
diff --git a/tools/benchmarks/cross_encoder_lora/fixtures.py b/tools/benchmarks/cross_encoder_lora/fixtures.py
new file mode 100644
index 000000000..3e6e15dba
--- /dev/null
+++ b/tools/benchmarks/cross_encoder_lora/fixtures.py
@@ -0,0 +1,72 @@
+"""Pinned public model and deterministic, deliberately untrained LoRA fixtures."""
+
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+
+import torch
+from huggingface_hub import snapshot_download
+from peft import LoraConfig
+from safetensors.torch import save_file
+
+from tools.benchmarks.cross_encoder_lora.evidence import digest
+from tools.benchmarks.cross_encoder_lora.protocol import MODEL, REVISION, WEIGHTS_SHA256, require
+
+
+def prepare(output: Path, snapshot: Path | None = None, *, smoke: bool = False) -> dict:
+ if snapshot is None:
+ snapshot = Path(
+ snapshot_download(
+ MODEL,
+ revision=REVISION,
+ token=False,
+ allow_patterns=["*.json", "vocab.txt", "model.safetensors"],
+ )
+ )
+ if not smoke:
+ require(digest(snapshot / "model.safetensors") == WEIGHTS_SHA256, "pinned model weight hash differs")
+ config = json.loads((snapshot / "config.json").read_text())
+ require(config["model_type"] == "bert", "the fixture protocol requires BERT")
+ output.mkdir(parents=True, exist_ok=False)
+ manifest = {
+ "model": MODEL,
+ "revision": REVISION,
+ "snapshot": str(snapshot.resolve()),
+ "smoke": smoke,
+ "model_files": {p.name: digest(p) for p in sorted(snapshot.iterdir()) if p.is_file()},
+ "adapters": {},
+ }
+ for index, alias in enumerate(("a", "b", "c")):
+ seed = 20261016 + index
+ directory = output / alias
+ directory.mkdir()
+ LoraConfig(
+ r=4, lora_alpha=8, target_modules=["query", "value"], lora_dropout=0, bias="none", inference_mode=True
+ ).save_pretrained(str(directory))
+ generator = torch.Generator().manual_seed(seed)
+ weights = {}
+ width = config["hidden_size"]
+ for layer in range(config["num_hidden_layers"]):
+ for target in ("query", "value"):
+ prefix = f"base_model.model.bert.encoder.layer.{layer}.attention.self.{target}"
+ scale = 0.4 if smoke else 0.04
+ weights[f"{prefix}.lora_A.weight"] = torch.randn(4, width, generator=generator) * scale
+ weights[f"{prefix}.lora_B.weight"] = torch.randn(width, 4, generator=generator) * scale
+ save_file(weights, directory / "adapter_model.safetensors")
+ manifest["adapters"][alias] = {"seed": seed, "files": {p.name: digest(p) for p in directory.iterdir()}}
+ (output / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
+ return manifest
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--output", type=Path, required=True)
+ parser.add_argument("--snapshot", type=Path)
+ args = parser.parse_args()
+ prepare(args.output, args.snapshot)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/benchmarks/cross_encoder_lora/prepare.py b/tools/benchmarks/cross_encoder_lora/prepare.py
new file mode 100644
index 000000000..f38c4e143
--- /dev/null
+++ b/tools/benchmarks/cross_encoder_lora/prepare.py
@@ -0,0 +1,69 @@
+"""Archive immutable B/N/R sources without installing or changing dependencies."""
+
+# Fixed git subcommands, argv-only execution; refs resolve before archive reads.
+# ruff: noqa: S603, S607
+
+from __future__ import annotations
+
+import argparse
+import json
+import subprocess
+from pathlib import Path
+
+from tools.benchmarks.cross_encoder_lora.evidence import atomic_json, digest
+from tools.benchmarks.cross_encoder_lora.protocol import BASE_REVISION, require
+
+SOURCE_PATHS = (
+ "packages/sie_server/src",
+ "packages/sie_server/models",
+ "packages/sie_sdk/src",
+ "packages/sie_config/src",
+ "packages/sie_bundles",
+ "bundles",
+ "uv.lock",
+ "pyproject.toml",
+)
+
+
+def git(root: Path, *arguments: str) -> bytes:
+ return subprocess.check_output(["git", "-C", str(root), *arguments])
+
+
+def prepare(root: Path, output: Path, candidate: str, baseline: str = BASE_REVISION) -> dict:
+ # Resolve before collecting any bytes: moving symbolic refs are never
+ # reused when archiving, hashing the lock, or writing the manifest.
+ commits = {
+ "B": git(root, "rev-parse", "--verify", "--end-of-options", f"{baseline}^{{commit}}").decode().strip(),
+ "candidate": git(root, "rev-parse", "--verify", "--end-of-options", f"{candidate}^{{commit}}").decode().strip(),
+ }
+ require(commits["B"] == BASE_REVISION, "baseline differs from the frozen protocol")
+ output.mkdir(parents=True, exist_ok=False)
+ records = {}
+ locks = []
+ for name, commit in commits.items():
+ existing = [path for path in SOURCE_PATHS if git(root, "ls-tree", "--name-only", commit, path).strip()]
+ archive = output / f"{name}.tar"
+ with archive.open("wb") as stream:
+ subprocess.run(
+ ["git", "-C", str(root), "archive", "--format=tar", commit, *existing], stdout=stream, check=True
+ )
+ lock = git(root, "show", f"{commit}:uv.lock")
+ locks.append(lock)
+ records[name] = {"commit": commit, "archive": archive.name, "sha256": digest(archive), "paths": existing}
+ require(locks[0] == locks[1], "baseline and candidate dependency locks differ")
+ manifest = {"schema": 1, "sources": records, "dependency_lock_identical": True}
+ atomic_json(output / "manifest.json", manifest)
+ return manifest
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--repo", type=Path, default=Path.cwd())
+ parser.add_argument("--output", type=Path, required=True)
+ parser.add_argument("--candidate", required=True)
+ args = parser.parse_args()
+ print(json.dumps(prepare(args.repo, args.output, args.candidate), indent=2))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/benchmarks/cross_encoder_lora/protocol.py b/tools/benchmarks/cross_encoder_lora/protocol.py
new file mode 100644
index 000000000..6a40f19bc
--- /dev/null
+++ b/tools/benchmarks/cross_encoder_lora/protocol.py
@@ -0,0 +1,102 @@
+"""Preregistered workload and paired non-inferiority gates (2026-10-16)."""
+
+from __future__ import annotations
+
+import math
+import statistics
+from typing import Any
+
+MODEL = "cross-encoder/ms-marco-MiniLM-L-6-v2"
+REVISION = "c5ee24cb16019beea0893ab7796b1df96625c6b8"
+WEIGHTS_SHA256 = "821d1aa69520101d6e0737f78a042ae25b19e5cb9160701909d10434f4aeb0ae"
+BASE_REVISION = "d5e024ad3ba6127b1ee176e2c85c794b76077888"
+QUERY = {"text": "How do I reset my password?"}
+DOCUMENTS = [
+ "Use the password reset link on the sign-in page to receive a recovery email.",
+ "The capital of France is Paris.",
+ "Contact account support if you cannot access your recovery email.",
+ "To change a billing address, open the payment settings page.",
+]
+ITEMS = [{"id": str(i), "text": text} for i, text in enumerate(DOCUMENTS)]
+CPU_ORACLE = [3.89416241645813, -11.230953216552734, -10.699657440185547, -9.410902976989746]
+ORACLE_ATOL = 0.1 # Existing finite fp32 checkpoint oracle versus the default fp16 CUDA path.
+RESTORE_ATOL = 1e-6
+EFFECT_FLOOR = 1e-5
+EFFECT_DRIFT_MULTIPLIER = 5
+ORDERS = ("BNR", "NRB", "RBN", "BRN", "RNB", "NBR")
+WARMUP = 30
+SEQUENTIAL = 200
+STEADY_SECONDS = 12
+CONCURRENCIES = (4, 16)
+THREADS = 4
+MAX_BATCH_ITEMS = 64
+MAX_TRIAL_SECONDS = 300
+MAX_EXPERIMENT_SECONDS = 3600
+EXPECTED_VERSIONS = {
+ "torch": "2.9.1+cu129",
+ "transformers": "4.57.6",
+ "sentence-transformers": "5.4.1",
+ "peft": "0.19.1",
+ "safetensors": "0.7.0",
+ "huggingface-hub": "0.36.2",
+}
+T95_DF5 = 2.0150483733330233
+MAX_POINT_RATIO = 1.01
+MAX_UPPER_RATIO = 1.03
+MAX_PAIR_RATIO = 1.10
+
+
+def require(condition: Any, message: str) -> None:
+ if not condition:
+ raise AssertionError(message)
+
+
+def percentile(values: list[float], fraction: float) -> float:
+ require(bool(values) and all(math.isfinite(x) and x > 0 for x in values), "invalid latency samples")
+ return sorted(values)[math.ceil(len(values) * fraction) - 1]
+
+
+def paired_gate(ratios: list[float]) -> dict[str, Any]:
+ require(len(ratios) == len(ORDERS), "six fresh-process pairs are required")
+ require(all(math.isfinite(x) and x > 0 for x in ratios), "invalid paired ratios")
+ logs = [math.log(value) for value in ratios]
+ mean = statistics.mean(logs)
+ point = math.exp(mean)
+ upper = math.exp(mean + T95_DF5 * statistics.stdev(logs) / math.sqrt(len(logs)))
+ return {
+ "paired_ratios": ratios,
+ "geometric_ratio": point,
+ "one_sided_95_upper": upper,
+ "passed": point <= MAX_POINT_RATIO and upper <= MAX_UPPER_RATIO and max(ratios) <= MAX_PAIR_RATIO,
+ }
+
+
+def compare(trials: list[dict[str, Any]]) -> dict[str, Any]:
+ require(len(trials) == len(ORDERS) * 3, "all eighteen fresh-process trials are required")
+ require(
+ [(t["pair"], t["arm"]) for t in trials] == [(i, arm) for i, order in enumerate(ORDERS) for arm in order],
+ "trial identities/order differ from the six preregistered triplets",
+ )
+ require(all(trial["passed"] and trial["shutdown_complete"] for trial in trials), "a trial failed")
+ result = {}
+ for arm in ("N", "R"):
+ metrics = {}
+ for concurrency, field in (
+ (1, "mean_ms"),
+ (1, "p95_ms"),
+ (4, "rps"),
+ (4, "p95_ms"),
+ (16, "rps"),
+ (16, "p95_ms"),
+ ):
+ ratios = []
+ for pair in range(len(ORDERS)):
+ baseline = next(t for t in trials if t["pair"] == pair and t["arm"] == "B")
+ candidate = next(t for t in trials if t["pair"] == pair and t["arm"] == arm)
+ b = baseline["performance"][str(concurrency)][field]
+ c = candidate["performance"][str(concurrency)][field]
+ require(all(math.isfinite(value) and value > 0 for value in (b, c)), "invalid raw performance metric")
+ ratios.append(b / c if field == "rps" else c / b)
+ metrics[f"C{concurrency}_{field}"] = paired_gate(ratios)
+ result[arm] = {"metrics": metrics, "passed": all(value["passed"] for value in metrics.values())}
+ return {"arms": result, "passed": all(value["passed"] for value in result.values())}
diff --git a/tools/benchmarks/cross_encoder_lora/runner.py b/tools/benchmarks/cross_encoder_lora/runner.py
new file mode 100644
index 000000000..c381f71ee
--- /dev/null
+++ b/tools/benchmarks/cross_encoder_lora/runner.py
@@ -0,0 +1,270 @@
+"""Run the frozen six-block experiment in eighteen owned fresh processes."""
+
+# Only the current Python executable and this checkout's benchmark module run.
+# ruff: noqa: S603
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import signal
+import subprocess
+import sys
+import tarfile
+import time
+from pathlib import Path
+from typing import Any
+
+from tools.benchmarks.cross_encoder_lora.evidence import atomic_json, digest, fingerprint, vector_delta
+from tools.benchmarks.cross_encoder_lora.protocol import (
+ BASE_REVISION,
+ MAX_EXPERIMENT_SECONDS,
+ MAX_TRIAL_SECONDS,
+ ORDERS,
+ RESTORE_ATOL,
+ compare,
+ require,
+)
+
+ROOT = Path(__file__).resolve().parents[3]
+
+
+def harness_manifest() -> dict[str, Any]:
+ directory = Path(__file__).resolve().parent
+ files = {
+ str(path.relative_to(directory)): digest(path)
+ for path in sorted(directory.rglob("*"))
+ if path.is_file()
+ and path.suffix in {".py", ".md"}
+ and not any(part in {"_inputs", "_evidence", "__pycache__"} for part in path.relative_to(directory).parts)
+ }
+ return {"files": files, "file_manifest_sha256": fingerprint(files)}
+
+
+def source_environment(source: Path) -> dict[str, str]:
+ # The harness stays fixed; both server and SDK imports come from the
+ # selected immutable archive. Do not run uv sync per arm.
+ paths = [source / f"packages/{package}/src" for package in ("sie_server", "sie_sdk", "sie_config", "sie_bundles")]
+ return {
+ **os.environ,
+ "PYTHONPATH": os.pathsep.join(str(path) for path in [*paths, ROOT]),
+ "TOKENIZERS_PARALLELISM": "false",
+ "SIE_BUNDLE": "default",
+ }
+
+
+def extract(inputs: Path, output: Path) -> dict[str, Any]:
+ manifest = json.loads((inputs / "manifest.json").read_text())
+ require(manifest["schema"] == 1 and manifest["dependency_lock_identical"], "unexpected source manifest")
+ require(manifest["sources"]["B"]["commit"] == BASE_REVISION, "baseline differs from protocol")
+ for name, record in manifest["sources"].items():
+ require(name in {"B", "candidate"}, "unknown source arm")
+ path = inputs / record["archive"]
+ require(path.resolve().is_relative_to(inputs.resolve()), "archive path escapes inputs")
+ require(digest(path) == record["sha256"], "source archive hash differs")
+ target = output / name
+ target.mkdir(parents=True)
+ with tarfile.open(path) as archive:
+ archive.extractall(target, filter="data")
+ require(
+ (output / "B/uv.lock").read_bytes() == (output / "candidate/uv.lock").read_bytes(), "extracted locks differ"
+ )
+ return manifest
+
+
+def cross_checks(trials: list[dict[str, Any]]) -> dict[str, Any]:
+ results = {}
+ for pair in range(len(ORDERS)):
+ rows = {trial["arm"]: trial for trial in trials if trial["pair"] == pair}
+ baseline = rows["B"]
+ for arm in ("N", "R"):
+ candidate = rows[arm]
+ require(
+ candidate["environment"]["versions"] == baseline["environment"]["versions"],
+ "libraries changed between arms",
+ )
+ require(
+ candidate["environment"]["installed_distributions_sha256"]
+ == baseline["environment"]["installed_distributions_sha256"],
+ "installed distributions changed between arms",
+ )
+ require(candidate["environment"]["device"] == baseline["environment"]["device"], "GPU changed between arms")
+ require(
+ vector_delta(candidate["base_scores"], baseline["base_scores"]) <= RESTORE_ATOL,
+ "cross-process C1 base scores differ",
+ )
+ require(
+ candidate["initial_memory"]["allocated"] == baseline["initial_memory"]["allocated"],
+ "unadapted allocated bytes changed",
+ )
+ for key, oracle in candidate["shape_oracles"].items():
+ require(
+ vector_delta(oracle["scores"], baseline["shape_oracles"][key]["scores"]) <= RESTORE_ATOL,
+ "cross-process shape oracle differs",
+ )
+ # Actual shape attribution is available only in observed untimed
+ # replays. Timed C4/C16 diagnostics are not shape-qualified evidence.
+ for phase in candidate["untimed_replays"].values():
+ for batch in phase["batches"]:
+ key = fingerprint({"queries": batch["queries"], "documents": batch["documents"]})
+ require(
+ vector_delta(batch["scores"], baseline["shape_oracles"][key]["scores"]) <= RESTORE_ATOL,
+ "candidate untimed SDK replay differs from the matched B shape",
+ )
+ delta = candidate["resident_memory"]["allocated"] - baseline["resident_memory"]["allocated"]
+ allowance = candidate.get("adapter_storage", {}).get("rounded_storage_bytes", 0)
+ require(0 <= delta <= allowance, "resident allocated bytes exceed measured adapter storage allowance")
+ results[f"{pair}-{arm}"] = {"allocated_delta": delta, "allowance": allowance, "passed": True}
+ return results
+
+
+def stop(process: subprocess.Popen) -> None:
+ if process.poll() is None:
+ process.send_signal(signal.SIGTERM)
+ try:
+ process.wait(timeout=35)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout=10)
+
+
+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,
+ "passed": False,
+ "source_manifest": manifest,
+ "harness_manifest": harness_manifest(),
+ "smoke": args.smoke,
+ "orders": ORDERS,
+ "trials": [],
+ }
+ summary_path = args.output / "summary.json"
+ absolute_deadline = time.monotonic() + args.deadline_s
+ if args.environment_receipt is not None:
+ summary["environment_preparation"] = {
+ "sha256": digest(args.environment_receipt),
+ "receipt": json.loads(args.environment_receipt.read_text()),
+ }
+ try:
+ schedule = [(0, "R")] if args.smoke else [(pair, arm) for pair, order in enumerate(ORDERS) for arm in order]
+ for pair, arm in schedule:
+ require(
+ time.monotonic() + args.trial_deadline_s + 45 < absolute_deadline,
+ "insufficient time for a complete bounded next trial and cleanup",
+ )
+ directory = args.output / f"trial-{pair}-{arm}"
+ source = (args.output / "sources" / ("B" if arm == "B" else "candidate")).resolve()
+ command = [
+ sys.executable,
+ "-m",
+ "tools.benchmarks.cross_encoder_lora.worker",
+ "--source",
+ str(source),
+ "--fixtures",
+ str(args.fixtures.resolve()),
+ "--output",
+ str(directory.resolve()),
+ "--arm",
+ arm,
+ "--pair",
+ str(pair),
+ "--deadline-s",
+ str(args.trial_deadline_s),
+ ]
+ if args.snapshot:
+ command.extend(["--snapshot", str(args.snapshot.resolve())])
+ if args.smoke:
+ command.append("--smoke")
+ print(f"Starting block {pair + 1}, arm {arm}", flush=True)
+ process = None
+ pending_error: BaseException | None = None
+ returncode = None
+ with (args.output / f"trial-{pair}-{arm}.log").open("w") as log:
+ try:
+ process = subprocess.Popen(
+ command, env=source_environment(source), cwd=source, stdout=log, stderr=subprocess.STDOUT
+ )
+ returncode = process.wait(timeout=args.trial_deadline_s + 45)
+ except BaseException as error: # noqa: BLE001 -- persist the trial, then re-raise after owned cleanup
+ pending_error = error
+ finally:
+ if process is not None:
+ stop(process)
+ returncode = process.returncode
+ trial: dict[str, Any]
+ if (directory / "trial.json").is_file():
+ trial = json.loads((directory / "trial.json").read_text())
+ else:
+ trial = {
+ "pair": pair,
+ "arm": arm,
+ "passed": False,
+ "shutdown_complete": False,
+ "error": "worker produced no terminal record",
+ }
+ trial["process_returncode"] = returncode
+ trial["source_commit"] = manifest["sources"]["B" if arm == "B" else "candidate"]["commit"]
+ trial["terminal_record_sha256"] = (
+ digest(directory / "trial.json") if (directory / "trial.json").exists() else None
+ )
+ if pending_error is not None:
+ trial["passed"] = False
+ trial["runner_error"] = {"type": type(pending_error).__name__, "message": str(pending_error)}
+ summary["trials"].append(trial)
+ atomic_json(summary_path, summary)
+ if pending_error is not None:
+ raise pending_error
+ require(
+ returncode == 0 and trial["passed"] and trial["shutdown_complete"],
+ "trial failed; raw evidence retained",
+ )
+ print(f"Finished block {pair + 1}, arm {arm}", flush=True)
+ if args.smoke:
+ summary["passed"] = True
+ summary["qualification"] = False
+ else:
+ summary["correctness_memory"] = cross_checks(summary["trials"])
+ summary["statistics"] = compare(summary["trials"])
+ summary["passed"] = summary["statistics"]["passed"]
+ require(summary["passed"], "fixed non-inferiority gates did not pass")
+ except BaseException as error:
+ summary["error"] = {"type": type(error).__name__, "message": str(error)}
+ raise
+ finally:
+ atomic_json(summary_path, summary)
+ return summary
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--inputs", type=Path, required=True)
+ parser.add_argument("--fixtures", type=Path, required=True)
+ parser.add_argument("--snapshot", type=Path)
+ parser.add_argument(
+ "--environment-receipt",
+ type=Path,
+ help="Optional operator-owned JSON receipt of environment preparation (no secrets)",
+ )
+ parser.add_argument("--output", type=Path, required=True)
+ parser.add_argument("--deadline-s", type=float, default=2400)
+ parser.add_argument("--trial-deadline-s", type=float, default=120)
+ parser.add_argument("--smoke", action="store_true")
+ args = parser.parse_args()
+ require(
+ 0 < args.deadline_s <= MAX_EXPERIMENT_SECONDS and 0 < args.trial_deadline_s <= MAX_TRIAL_SECONDS,
+ "deadline outside bounded protocol",
+ )
+ signal.signal(signal.SIGTERM, terminate)
+ run(args)
+
+
+def terminate(signum: int, _frame: Any) -> None:
+ # Enter the ordinary owned-child cleanup and atomic evidence finally paths.
+ raise SystemExit(128 + signum)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/benchmarks/cross_encoder_lora/tests/__init__.py b/tools/benchmarks/cross_encoder_lora/tests/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tools/benchmarks/cross_encoder_lora/tests/conftest.py b/tools/benchmarks/cross_encoder_lora/tests/conftest.py
new file mode 100644
index 000000000..08a014d75
--- /dev/null
+++ b/tools/benchmarks/cross_encoder_lora/tests/conftest.py
@@ -0,0 +1,6 @@
+"""Make the public source-only tools namespace importable under pytest's importlib mode."""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[4]))
diff --git a/tools/benchmarks/cross_encoder_lora/tests/test_probe.py b/tools/benchmarks/cross_encoder_lora/tests/test_probe.py
new file mode 100644
index 000000000..eb820a77a
--- /dev/null
+++ b/tools/benchmarks/cross_encoder_lora/tests/test_probe.py
@@ -0,0 +1,334 @@
+"""Real CPU smoke plus negative controls for the public acceptance harness."""
+
+# Owned Python subprocesses run only this checkout's benchmark, without a shell.
+# ruff: noqa: S603
+
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+import tarfile
+from pathlib import Path
+
+import httpx
+import pytest
+import torch
+from transformers import BertConfig, BertForSequenceClassification, BertTokenizerFast
+
+from tools.benchmarks.cross_encoder_lora import prepare as source_preparer
+from tools.benchmarks.cross_encoder_lora.evidence import Evidence, atomic_json, vector_delta
+from tools.benchmarks.cross_encoder_lora.fixtures import prepare
+from tools.benchmarks.cross_encoder_lora.protocol import BASE_REVISION, ORDERS, compare, paired_gate, percentile
+from 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
+
+
+def tiny_snapshot(directory: Path) -> Path:
+ directory.mkdir()
+ vocabulary = [
+ "[PAD]",
+ "[UNK]",
+ "[CLS]",
+ "[SEP]",
+ "[MASK]",
+ "the",
+ "password",
+ "reset",
+ "link",
+ "email",
+ "paris",
+ "account",
+ "support",
+ "billing",
+ "address",
+ ".",
+ "?",
+ "how",
+ "do",
+ "i",
+ "my",
+ "use",
+ "to",
+ "a",
+ "is",
+ "of",
+ "france",
+ ]
+ (directory / "vocab.txt").write_text("\n".join(vocabulary) + "\n")
+ tokenizer = BertTokenizerFast(vocab_file=str(directory / "vocab.txt"))
+ tokenizer.save_pretrained(directory)
+ config = BertConfig(
+ vocab_size=len(vocabulary),
+ hidden_size=16,
+ num_hidden_layers=2,
+ num_attention_heads=2,
+ intermediate_size=32,
+ max_position_embeddings=64,
+ num_labels=1,
+ hidden_dropout_prob=0,
+ attention_probs_dropout_prob=0,
+ )
+ config.sbert_ce_default_activation_function = "torch.nn.modules.linear.Identity"
+ torch.manual_seed(29)
+ BertForSequenceClassification(config).save_pretrained(directory)
+ return directory
+
+
+def test_gate_positive_negative_and_uncertainty() -> None:
+ assert paired_gate([1.0] * 6)["passed"]
+ assert not paired_gate([1.02] * 6)["passed"] # point gate
+ uncertain = paired_gate([0.94, 0.94, 0.94, 1.06, 1.06, 1.06])
+ assert uncertain["geometric_ratio"] < 1.01
+ assert uncertain["one_sided_95_upper"] > 1.03
+ assert not uncertain["passed"]
+ assert not paired_gate([0.97] * 5 + [1.11])["passed"]
+ with pytest.raises(AssertionError, match="six"):
+ paired_gate([1.0] * 5)
+ with pytest.raises(AssertionError, match="invalid"):
+ paired_gate([float("nan")] * 6)
+
+
+def test_nearest_rank() -> None:
+ assert percentile(list(range(1, 21)), 0.95) == 19
+ assert percentile([1, 2, 3], 0.95) == 3
+
+
+def trials() -> list[dict]:
+ performance = {str(c): {"mean_ms": 10.0, "p95_ms": 12.0, "rps": 100.0} for c in (1, 4, 16)}
+ return [
+ {"pair": i, "arm": arm, "passed": True, "shutdown_complete": True, "performance": performance}
+ for i, order in enumerate(ORDERS)
+ for arm in order
+ ]
+
+
+def test_full_schedule_and_cleanup_are_required() -> None:
+ assert compare(trials())["passed"]
+ wrong = trials()
+ wrong[0]["arm"] = "R"
+ with pytest.raises(AssertionError, match="identities"):
+ compare(wrong)
+ incomplete = trials()
+ incomplete[0]["shutdown_complete"] = False
+ with pytest.raises(AssertionError, match="failed"):
+ compare(incomplete)
+
+
[email protected]("value", [-1.0, 0.0, float("nan"), float("inf")])
+def test_raw_metrics_must_be_positive_finite(value: float) -> None:
+ invalid = trials()
+ for trial in invalid:
+ trial["performance"]["1"]["mean_ms"] = value
+ with pytest.raises(AssertionError, match="raw performance"):
+ compare(invalid)
+
+
+def test_nonfinite_evidence_retained_but_never_accepted(tmp_path: Path) -> None:
+ evidence = Evidence(tmp_path / "out")
+ evidence.emit("bad_output", values=[float("nan"), float("inf")])
+ assert json.loads((tmp_path / "out/events.jsonl").read_text())["values"] == ["nan", "inf"]
+ with pytest.raises(AssertionError, match="nonfinite"):
+ vector_delta([float("nan")], [1.0])
+ atomic_json(tmp_path / "out/final.json", {"passed": False})
+ assert json.loads((tmp_path / "out/final.json").read_text()) == {"passed": False}
+
+
[email protected]("arm", ["B", "R"])
+def test_real_loader_sdk_lifecycle(tmp_path: Path, arm: str) -> None:
+ snapshot = tiny_snapshot(tmp_path / "model")
+ fixtures = tmp_path / "fixtures"
+ prepare(fixtures, snapshot, smoke=True)
+ # Use real historical B and committed candidate imports, not the editable
+ # checkout accidentally standing in for both arms. Full clones contain B;
+ # a shallow CI checkout can still run the other deterministic controls.
+ available = subprocess.run(["git", "cat-file", "-e", BASE_REVISION], cwd=ROOT, capture_output=True, check=False) # noqa: S607
+ if available.returncode:
+ pytest.skip("immutable archive smoke requires the documented baseline commit in git history")
+ inputs = tmp_path / "source-inputs"
+ source_preparer.prepare(ROOT, inputs, "HEAD")
+ sources = tmp_path / "sources"
+ extract(inputs, sources)
+ source = sources / ("B" if arm == "B" else "candidate")
+ output = tmp_path / "evidence"
+ command = [
+ sys.executable,
+ "-m",
+ "tools.benchmarks.cross_encoder_lora.worker",
+ "--source",
+ str(source),
+ "--fixtures",
+ str(fixtures),
+ "--output",
+ str(output),
+ "--arm",
+ arm,
+ "--smoke",
+ "--deadline-s",
+ "90",
+ ]
+ result = subprocess.run(
+ command, env=source_environment(source), cwd=source, capture_output=True, text=True, timeout=130, check=False
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+ summary = json.loads((output / "trial.json").read_text())
+ assert summary["passed"]
+ assert summary["shutdown_complete"]
+ assert summary["manager_present"] == (arm == "R")
+ assert summary["environment"]["qualification"] is False
+ assert Path(summary["environment"]["adapter_source"]).is_relative_to(source)
+ events = [json.loads(line) for line in (output / "events.jsonl").read_text().splitlines()]
+ assert {"shape_oracles", "performance", "finished"} <= {event["event"] for event in events}
+ if arm == "R":
+ assert {"effects", "concurrent_batches", "resident_set", "restored_state"} <= {
+ event["event"] for event in events
+ }
+
+
+def test_worker_failure_persists_terminal_record(tmp_path: Path) -> None:
+ output = tmp_path / "failed"
+ command = [
+ sys.executable,
+ "-m",
+ "tools.benchmarks.cross_encoder_lora.worker",
+ "--source",
+ str(ROOT),
+ "--fixtures",
+ str(tmp_path / "missing"),
+ "--output",
+ str(output),
+ "--arm",
+ "R",
+ "--smoke",
+ ]
+ result = subprocess.run(
+ command, env=source_environment(ROOT), cwd=ROOT, capture_output=True, text=True, timeout=45, check=False
+ )
+ assert result.returncode != 0
+ summary = json.loads((output / "trial.json").read_text())
+ assert not summary["passed"]
+ assert summary["error"]["type"] == "FileNotFoundError"
+ assert (output / "events.jsonl").read_text().endswith("\n")
+
+
+def test_source_archive_resolves_moving_refs_once(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ root = tmp_path / "repo"
+ root.mkdir()
+
+ def git(*args: str) -> bytes:
+ return subprocess.check_output(["git", "-C", str(root), *args]) # noqa: S607
+
+ git("init", "-q")
+ source = root / "packages/sie_server/src"
+ source.mkdir(parents=True)
+ (source / "value.txt").write_text("baseline")
+ (root / "uv.lock").write_text("fixed lock")
+ git("add", ".")
+
+ def commit() -> None:
+ git("-c", "user.name=Harness Test", "-c", "[email protected]", "commit", "-qm", "fixture")
+
+ commit()
+ baseline = git("rev-parse", "HEAD").decode().strip()
+ git("checkout", "-qb", "candidate")
+ (source / "value.txt").write_text("candidate before move")
+ git("add", ".")
+ commit()
+ candidate = git("rev-parse", "HEAD").decode().strip()
+ original = source_preparer.git
+
+ def moving_git(path: Path, *arguments: str) -> bytes:
+ value = original(path, *arguments)
+ if arguments[-1] == "candidate^{commit}":
+ (source / "value.txt").write_text("candidate after move")
+ git("add", ".")
+ commit()
+ return value
+
+ monkeypatch.setattr(source_preparer, "BASE_REVISION", baseline)
+ monkeypatch.setattr(source_preparer, "git", moving_git)
+ output = tmp_path / "archives"
+ manifest = source_preparer.prepare(root, output, "candidate", baseline)
+ assert manifest["sources"]["candidate"]["commit"] == candidate
+ assert git("rev-parse", "candidate").decode().strip() != candidate
+ with tarfile.open(output / "candidate.tar") as archive:
+ stream = archive.extractfile("packages/sie_server/src/value.txt")
+ assert stream is not None
+ assert stream.read() == b"candidate before move"
+
+
+def test_tampered_archive_refused_before_extract(tmp_path: Path) -> None:
+ inputs = tmp_path / "input"
+ inputs.mkdir()
+ (inputs / "B.tar").write_bytes(b"not the declared archive")
+ atomic_json(
+ inputs / "manifest.json",
+ {
+ "schema": 1,
+ "dependency_lock_identical": True,
+ "sources": {"B": {"commit": BASE_REVISION, "archive": "B.tar", "sha256": "0" * 64}},
+ },
+ )
+ with pytest.raises(AssertionError, match="archive hash"):
+ extract(inputs, tmp_path / "output")
+
+
+def test_timed_diagnostics_require_one_complete_oracle_vector() -> None:
+ first = [0.0, 1.0, 2.0, 3.0]
+ second = [10.0, 11.0, 12.0, 13.0]
+ oracles = {
+ "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) == []
+
+
+def test_hidden_retry_rejected_and_malformed_error_retained() -> None:
+ row = {
+ "label": "test",
+ "responses": [httpx.Response(200), httpx.Response(200)],
+ "result": {"scores": [{"item_id": f"test:{i}", "score": float(4 - i), "rank": i} for i in range(4)]},
+ }
+ with pytest.raises(AssertionError, match="hidden SDK retry"):
+ validate_response(row)
+ bad = describe_response(httpx.Response(503, content=b"not JSON"))
+ assert bad["body_decode_error"] == "JSONDecodeError"
+ assert bad["status"] == 503
+
+
+def test_live_server_failure_and_failed_evidence_emit_still_cleanup(tmp_path: Path) -> None:
+ snapshot = tiny_snapshot(tmp_path / "model")
+ fixtures = tmp_path / "fixtures"
+ prepare(fixtures, snapshot, smoke=True)
+ output = tmp_path / "failed-live"
+ script = """
+import argparse, asyncio, sys
+from pathlib import Path
+from tools.benchmarks.cross_encoder_lora import worker
+original = worker.Evidence.emit
+def failing_emit(self, event, **fields):
+ if event == 'original_state':
+ raise OSError('injected post-load evidence failure')
+ if event == 'client_wire_responses':
+ raise OSError('injected cleanup evidence failure')
+ return original(self, event, **fields)
+worker.Evidence.emit = failing_emit
+asyncio.run(worker.run(argparse.Namespace(source=Path(sys.argv[1]), fixtures=Path(sys.argv[2]),
+ output=Path(sys.argv[3]), snapshot=None, arm='R', pair=0, smoke=True, deadline_s=60)))
+"""
+ result = subprocess.run(
+ [sys.executable, "-c", script, str(ROOT), str(fixtures), str(output)],
+ env=source_environment(ROOT),
+ cwd=ROOT,
+ capture_output=True,
+ text=True,
+ timeout=100,
+ check=False,
+ )
+ assert result.returncode != 0
+ summary = json.loads((output / "trial.json").read_text())
+ assert not summary["passed"]
+ assert summary["shutdown_complete"]
+ assert summary["error"]["message"] == "injected cleanup evidence failure"
+ assert {row["message"] for row in summary["error"]["context"]} == {"injected post-load evidence failure"}
diff --git a/tools/benchmarks/cross_encoder_lora/worker.py b/tools/benchmarks/cross_encoder_lora/worker.py
new file mode 100644
index 000000000..b8dcd9c8a
--- /dev/null
+++ b/tools/benchmarks/cross_encoder_lora/worker.py
@@ -0,0 +1,867 @@
+"""One fresh-process SDK/worker trial; invoked by runner.py, never provisions compute."""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import gc
+import hashlib
+import importlib.metadata
+import json
+import math
+import os
+import resource
+import socket
+import statistics
+import subprocess
+import sys
+import threading
+import time
+import weakref
+from collections.abc import Iterator
+from concurrent.futures import ThreadPoolExecutor
+from contextlib import ExitStack, contextmanager
+from http import HTTPStatus
+from pathlib import Path
+from typing import Any
+
+import httpx
+import torch
+import uvicorn
+import yaml
+from sie_sdk import SIEClient
+from sie_sdk._msgpack import unpackb
+from sie_sdk.client.errors import RequestError, ServerError
+from sie_server.adapters.cross_encoder import CrossEncoderAdapter
+from sie_server.adapters.peft_lora_mixin import PEFTLoRAMixin
+from sie_server.app.app_factory import AppFactory
+from sie_server.app.app_state_config import AppStateConfig
+from sie_server.types.inputs import Item
+
+from tools.benchmarks.cross_encoder_lora.evidence import Evidence, atomic_json, digest, fingerprint, vector_delta
+from tools.benchmarks.cross_encoder_lora.protocol import (
+ CONCURRENCIES,
+ CPU_ORACLE,
+ DOCUMENTS,
+ EFFECT_DRIFT_MULTIPLIER,
+ EFFECT_FLOOR,
+ EXPECTED_VERSIONS,
+ MAX_BATCH_ITEMS,
+ MAX_TRIAL_SECONDS,
+ MODEL,
+ ORACLE_ATOL,
+ QUERY,
+ RESTORE_ATOL,
+ SEQUENTIAL,
+ STEADY_SECONDS,
+ THREADS,
+ WARMUP,
+ WEIGHTS_SHA256,
+ percentile,
+ require,
+)
+
+HERE = Path(__file__).resolve().parent
+ORDER = sorted(range(len(DOCUMENTS)), key=lambda index: len(DOCUMENTS[index]))
+MAX_LOADING_RETRIES = 10
+MAX_LOADING_DELAY = 5
+RESIDENT_CAPACITY = 2
+REQUEST_ITEMS = len(DOCUMENTS)
+
+
+def error_record(error: BaseException) -> dict[str, Any]:
+ record: dict[str, Any] = {"type": type(error).__name__, "message": str(error), "context": []}
+ seen = {id(error)}
+ cause = error.__cause__ or error.__context__
+ while cause is not None and id(cause) not in seen:
+ seen.add(id(cause))
+ record["context"].append({"type": type(cause).__name__, "message": str(cause)})
+ cause = cause.__cause__ or cause.__context__
+ return record
+
+
+def ordered_workload(copies: int) -> tuple[list[Item], list[Item]]:
+ indices = [index for index in ORDER for _ in range(copies)]
+ return (
+ [Item(text=QUERY["text"]) for _ in indices],
+ [Item(id=f"oracle:{j}", text=DOCUMENTS[index]) for j, index in enumerate(indices)],
+ )
+
+
+def batch_key(row: dict[str, Any]) -> str:
+ require(len(row["documents"]) % 4 == 0, "unexpected partial four-document request batch")
+ copies = len(row["documents"]) // 4
+ require(1 <= copies <= MAX_BATCH_ITEMS // 4, "unexpected batch size")
+ queries, documents = ordered_workload(copies)
+ workload = {"queries": [item.text for item in queries], "documents": [item.text for item in documents]}
+ require(
+ row["queries"] == workload["queries"] and row["documents"] == workload["documents"],
+ "batch order/workload differs from its preregistered oracle",
+ )
+ return fingerprint(workload)
+
+
+def memory() -> dict[str, Any]:
+ gc.collect()
+ if torch.cuda.is_available():
+ torch.cuda.synchronize()
+ return {
+ "allocated": torch.cuda.memory_allocated() if torch.cuda.is_available() else 0,
+ "reserved": torch.cuda.memory_reserved() if torch.cuda.is_available() else 0,
+ "max_rss_platform_units": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,
+ }
+
+
+def telemetry() -> dict[str, Any]:
+ if not torch.cuda.is_available():
+ return {"device": "cpu", "qualification": False}
+ command = [
+ "nvidia-smi",
+ "--query-gpu=name,uuid,driver_version,temperature.gpu,clocks.sm,clocks.mem,power.draw,utilization.gpu,memory.used",
+ "--format=csv,noheader,nounits",
+ ]
+ result = subprocess.run(command, capture_output=True, text=True, timeout=10, check=False) # noqa: S603 -- fixed nvidia-smi argv
+ return {
+ "query": command[1],
+ "returncode": result.returncode,
+ "csv": result.stdout.strip(),
+ "stderr": result.stderr.strip(),
+ }
+
+
+def tensor_state(adapter: Any) -> dict[str, Any]:
+ outer = adapter._model
+ model = outer.model
+ tensors = {}
+ for name, tensor in model.named_parameters():
+ if ".lora_" not in name:
+ value = tensor.detach().cpu().contiguous()
+ tensors[str(id(tensor))] = {
+ "name": name.replace(".base_layer.", "."),
+ "dtype": str(tensor.dtype),
+ "shape": list(tensor.shape),
+ "sha256": hashlib.sha256(value.view(torch.uint8).numpy().tobytes()).hexdigest(),
+ }
+ return {
+ "wrapper_id": id(outer),
+ "model_id": id(model),
+ "tokenizer_id": id(outer.tokenizer),
+ "head_id": id(model.classifier),
+ "activation": str(outer.activation_fn),
+ "tensors": tensors,
+ "tree": {
+ name: [type(module).__module__ + "." + type(module).__qualname__, id(module)]
+ for name, module in model.named_modules()
+ },
+ "hf_peft_config_loaded": bool(getattr(model, "_hf_peft_config_loaded", False)),
+ "peft_config_present": bool(getattr(model, "peft_config", None)),
+ }
+
+
+def base_unchanged(before: dict[str, Any], after: dict[str, Any], *, restored: bool = False) -> None:
+ for key in ("wrapper_id", "model_id", "tokenizer_id", "head_id", "activation", "tensors"):
+ require(before[key] == after[key], f"base state changed: {key}")
+ if restored:
+ for key in ("tree", "hf_peft_config_loaded", "peft_config_present"):
+ require(before[key] == after[key], f"final unload did not restore {key}")
+
+
+def adapter_storage(adapter: Any) -> dict[str, int]:
+ storages = {}
+ for name, tensor in adapter._model.model.named_parameters():
+ if ".lora_" in name:
+ storage = tensor.untyped_storage()
+ storages[(str(tensor.device), storage.data_ptr())] = storage.nbytes()
+ return {
+ "storage_count": len(storages),
+ "tensor_storage_bytes": sum(storages.values()),
+ "rounded_storage_bytes": sum(math.ceil(size / 512) * 512 for size in storages.values()),
+ }
+
+
+class Client:
+ def __init__(self, url: str) -> None:
+ self.responses: list[httpx.Response] = []
+ http = httpx.Client(base_url=url, timeout=30, event_hooks={"response": [self.observe]})
+ self.sdk = SIEClient(url, timeout_s=30, http_client=http)
+
+ def observe(self, response: httpx.Response) -> None:
+ # The only extra HTTP-hook work in timed phases. Decode after clocks stop.
+ self.responses.append(response)
+
+ def score(self, selection: str | None, label: str, *, cold: bool = False, timed: bool = False) -> dict[str, Any]:
+ started = time.perf_counter_ns()
+ wall_started = time.time_ns()
+ first = len(self.responses)
+ # score() currently does not retry LORA_LOADING. These are explicitly
+ # fresh SDK calls for this pre-execution status, never transport retries.
+ for attempt in range(MAX_LOADING_RETRIES + 1):
+ try:
+ result = self.sdk.score(
+ MODEL,
+ {"text": QUERY["text"]},
+ [{"id": f"{label}:{index}", "text": text} for index, text in enumerate(DOCUMENTS)],
+ options={"lora": selection},
+ wait_for_capacity=False,
+ max_oom_retries=0,
+ provision_timeout_s=30,
+ )
+ break
+ except ServerError as error:
+ if (
+ not cold
+ or error.status_code != HTTPStatus.SERVICE_UNAVAILABLE
+ or error.code != "LORA_LOADING"
+ or attempt == MAX_LOADING_RETRIES
+ ):
+ raise
+ delay = error.retry_after if error.retry_after is not None else 0.2
+ require(0 <= delay <= MAX_LOADING_DELAY, "unexpected loading retry delay")
+ time.sleep(delay)
+ elapsed = (time.perf_counter_ns() - started) / 1e6
+ row = {
+ "label": label,
+ "selection": selection,
+ "latency_ms": elapsed,
+ "start_ns": wall_started,
+ "end_ns": time.time_ns(),
+ "result": result,
+ "responses": self.responses[first:],
+ }
+ if not timed:
+ validate_response(row, allow_loading=cold)
+ return row
+
+ def close(self) -> None:
+ self.sdk.close()
+
+
+def describe_response(response: httpx.Response) -> dict[str, Any]:
+ row: dict[str, Any] = {
+ "status": response.status_code,
+ "timing_headers": {
+ name: response.headers[name]
+ for name in (
+ "x-queue-time",
+ "x-tokenization-time",
+ "x-inference-time",
+ "x-postprocessing-time",
+ "x-total-time",
+ )
+ if name in response.headers
+ },
+ }
+ if response.status_code >= HTTPStatus.BAD_REQUEST:
+ response.read()
+ try:
+ body = (
+ unpackb(response.content, numeric_arrays=False)
+ if "msgpack" in response.headers.get("content-type", "")
+ else response.json()
+ )
+ except ValueError as error:
+ row["body_decode_error"] = type(error).__name__
+ body = None
+ error = body.get("error", body.get("detail", body)) if isinstance(body, dict) else None
+ row.update(
+ code=error.get("code") if isinstance(error, dict) else None, retry_after=response.headers.get("retry-after")
+ )
+ return row
+
+
+def serialize_responses(row: dict[str, Any]) -> None:
+ row["responses"] = [
+ describe_response(value) if isinstance(value, httpx.Response) else value for value in row["responses"]
+ ]
+
+
+def validate_response(row: dict[str, Any], *, allow_loading: bool = False) -> None:
+ serialize_responses(row)
+ statuses = row["responses"]
+ require(statuses and statuses[-1]["status"] == HTTPStatus.OK, "missing successful HTTP response")
+ if allow_loading:
+ require(
+ all(
+ value["status"] == HTTPStatus.SERVICE_UNAVAILABLE and value.get("code") == "LORA_LOADING"
+ for value in statuses[:-1]
+ ),
+ "unexpected retry during cold adapter request",
+ )
+ else:
+ require(len(statuses) == 1, "hidden SDK retry disqualifies this request")
+ scores = row["result"]["scores"]
+ expected_ids = [f"{row['label']}:{i}" for i in range(REQUEST_ITEMS)]
+ by_id = {item["item_id"]: item["score"] for item in scores}
+ require(len(scores) == REQUEST_ITEMS and set(by_id) == set(expected_ids), "score result lost or changed item IDs")
+ require([item["rank"] for item in scores] == list(range(REQUEST_ITEMS)), "score ranks changed")
+ values = [by_id[key] for key in expected_ids]
+ row["scores"] = values
+ require(all(math.isfinite(value) for value in values), "nonfinite SDK score")
+ require([item["score"] for item in scores] == sorted(values, reverse=True), "score ranks are unordered")
+
+
+@contextmanager
+def unobserved(adapter: Any) -> Iterator[None]:
+ """Time production methods directly; no model hook, copying or observer lock."""
+ score_pairs, select = adapter.score_pairs, adapter.set_active_lora
+ before = (len(adapter.batch_observations), len(adapter.forward_observations), len(adapter.selection_observations))
+ adapter._observer_handle.remove()
+ adapter._observer_handle = None
+ adapter.score_pairs = CrossEncoderAdapter.score_pairs.__get__(adapter)
+ adapter.set_active_lora = CrossEncoderAdapter.set_active_lora.__get__(adapter)
+ try:
+ require(adapter.score_pairs.__func__ is CrossEncoderAdapter.score_pairs, "timed scoring is instrumented")
+ require(
+ adapter.set_active_lora.__func__ is CrossEncoderAdapter.set_active_lora, "timed selection is instrumented"
+ )
+ yield
+ after = (
+ len(adapter.batch_observations),
+ len(adapter.forward_observations),
+ len(adapter.selection_observations),
+ )
+ require(before == after, "observer activity occurred during production timing")
+ finally:
+ adapter.score_pairs, adapter.set_active_lora = score_pairs, select
+ adapter._observer_handle = adapter._model.model.register_forward_hook(
+ adapter._observe_forward, with_kwargs=True
+ )
+
+
+def matching_vectors(scores: list[float], oracles: dict[str, Any]) -> list[dict[str, Any]]:
+ matches = []
+ for key, oracle_row in oracles.items():
+ 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
+
+
+def performance(url: str, concurrency: int, evidence: Evidence, *, smoke: bool) -> dict[str, Any]:
+ clients = [Client(url) for _ in range(concurrency)]
+ samples: list[dict[str, Any]] = []
+ warmups: list[dict[str, Any]] = []
+ lock = threading.Lock()
+ try:
+ for i in range(2 if smoke else WARMUP):
+ warmups.append(clients[0].score(None, f"warm-C{concurrency}-{i}", timed=True))
+ barrier = threading.Barrier(concurrency + 1)
+ clock: dict[str, float] = {}
+
+ def lane(index: int) -> None:
+ barrier.wait(timeout=30)
+ counter = 0
+ while (
+ counter < (4 if smoke else SEQUENTIAL) if concurrency == 1 else time.perf_counter() < clock["deadline"]
+ ):
+ row = clients[index].score(None, f"C{concurrency}-lane{index}-{counter}", timed=True)
+ with lock:
+ samples.append(row)
+ counter += 1
+
+ with ThreadPoolExecutor(max_workers=concurrency) as executor:
+ futures = [executor.submit(lane, i) for i in range(concurrency)]
+ clock["start"] = time.perf_counter()
+ clock["deadline"] = clock["start"] + (0.15 if smoke else STEADY_SECONDS)
+ barrier.wait(timeout=30)
+ for future in futures:
+ future.result(timeout=90)
+ elapsed = time.perf_counter() - clock["start"]
+ for row in [*warmups, *samples]:
+ validate_response(row)
+ latencies = [row["latency_ms"] for row in samples]
+ return {
+ "concurrency": concurrency,
+ "count": len(samples),
+ "elapsed_s": elapsed,
+ "mean_ms": statistics.mean(latencies),
+ "p95_ms": percentile(latencies, 0.95),
+ "rps": len(samples) / elapsed,
+ "samples": samples,
+ }
+ finally:
+ with ExitStack() as cleanup:
+ for client in clients:
+ cleanup.callback(client.close)
+ for row in [*warmups, *samples]:
+ serialize_responses(row)
+ evidence.emit(
+ "performance_attempt",
+ concurrency=concurrency,
+ completed_samples=samples,
+ warmups=warmups,
+ wire_responses=[describe_response(response) for client in clients for response in client.responses],
+ )
+
+
+def validate_usage(rows: list[dict[str, Any]], batches: list[dict[str, Any]]) -> None:
+ tokens = {
+ item_id: count
+ for batch in batches
+ for item_id, count in zip(batch["item_ids"], batch["input_token_counts"], strict=True)
+ }
+ for row in rows:
+ expected = sum(tokens[f"{row['label']}:{i}"] for i in range(4))
+ require(
+ row["result"]["usage"]["input_tokens"] == expected, "SDK token usage differs from real tokenizer counts"
+ )
+
+
+def replay(url: str, concurrency: int) -> list[dict[str, Any]]:
+ clients = [Client(url) for _ in range(concurrency)]
+ rows = []
+ try:
+ for repeat in range(2):
+ barrier = threading.Barrier(concurrency)
+
+ def lane(index: int) -> dict[str, Any]:
+ barrier.wait(timeout=20)
+ return clients[index].score(None, f"replay-C{concurrency}-{repeat}-{index}")
+
+ with ThreadPoolExecutor(max_workers=concurrency) as executor:
+ rows.extend(executor.map(lane, range(concurrency)))
+ return rows
+ finally:
+ for client in clients:
+ client.close()
+
+
+async def oracle(adapter: Any, worker: Any, selection: str | None, *, smoke: bool) -> dict[str, Any]:
+ result = {}
+ for copies in range(1, MAX_BATCH_ITEMS // 4 + 1):
+ queries, documents = ordered_workload(copies)
+
+ def forward() -> Any:
+ adapter.set_active_lora(selection)
+ return adapter.score_pairs(queries, documents)
+
+ values = []
+ for _ in range(2):
+ output = await worker.run_adapter_mutation(forward)
+ values.append(output.scores.tolist())
+ require(vector_delta(*values) <= RESTORE_ATOL, "preselection shape oracle is unstable")
+ key = fingerprint({"queries": [item.text for item in queries], "documents": [item.text for item in documents]})
+ result[key] = {
+ "copies": copies,
+ "scores": values[0],
+ "repeat": values[1],
+ "input_token_counts": output.input_token_counts,
+ }
+ return result
+
+
+def configs(directory: Path, source: Path, fixtures: Path, arm: str, snapshot: Path, *, smoke: bool) -> None:
+ directory.mkdir()
+ config = yaml.safe_load(
+ (source / "packages/sie_server/models/cross-encoder__ms-marco-MiniLM-L-6-v2.yaml").read_text()
+ )
+ config.pop("hf_id")
+ config["weights_path"] = str(snapshot)
+ if smoke:
+ config["max_sequence_length"] = 64
+ profile = config["profiles"]["default"]
+ profile["adapter_path"] = f"{HERE / 'adapter.py'}:ObservedCrossEncoder"
+ if arm == "R":
+ profile["adapter_options"]["loadtime"] = {
+ "lora_paths": {name: str(fixtures / name) for name in ("a", "b", "c")}
+ }
+ (directory / "model.yaml").write_text(yaml.safe_dump(config))
+
+
+def preflight(args: argparse.Namespace, evidence: Evidence) -> dict[str, Any]:
+ versions = {name: importlib.metadata.version(name) for name in EXPECTED_VERSIONS}
+ try:
+ torchao = importlib.metadata.version("torchao")
+ except importlib.metadata.PackageNotFoundError:
+ torchao = None
+ module_path = sys.modules[CrossEncoderAdapter.__module__].__file__
+ assert module_path is not None
+ actual_source = Path(module_path).resolve()
+ require(actual_source.is_relative_to(args.source.resolve()), "adapter was imported from a different source tree")
+ data = {
+ "versions": versions,
+ "torchao": torchao,
+ "adapter_source": str(actual_source),
+ "adapter_sha256": digest(actual_source),
+ "python": sys.version,
+ "threads": torch.get_num_threads(),
+ "device": str(torch.cuda.get_device_name(0)) if torch.cuda.is_available() else "cpu",
+ "torch_cuda": torch.version.cuda,
+ "qualification": not args.smoke,
+ "installed_distributions": sorted(
+ (dist.metadata["Name"], dist.version) for dist in importlib.metadata.distributions()
+ ),
+ }
+ data["installed_distributions_sha256"] = fingerprint(data["installed_distributions"])
+ evidence.emit("environment", **data)
+ if not args.smoke:
+ require(versions == EXPECTED_VERSIONS, "installed stack differs from the exact public lock")
+ require(torchao is None, "torchao must be absent; benchmark does not mutate dependencies")
+ require(torch.cuda.is_available() and "L4" in data["device"], "qualification requires the declared L4")
+ return data
+
+
+async def experiment(args: argparse.Namespace, evidence: Evidence, summary: dict[str, Any]) -> None:
+ fixtures = args.fixtures.resolve()
+ manifest = json.loads((fixtures / "manifest.json").read_text())
+ snapshot = args.snapshot.resolve() if args.snapshot else Path(manifest["snapshot"])
+ require(bool(manifest["smoke"]) == args.smoke, "fixture smoke/qualification mode differs")
+ for filename, expected in manifest["model_files"].items():
+ require(digest(snapshot / filename) == expected, "model file changed after fixture preparation")
+ if not args.smoke:
+ require(digest(snapshot / "model.safetensors") == WEIGHTS_SHA256, "public checkpoint hash differs")
+ for name, record in manifest["adapters"].items():
+ for filename, expected in record["files"].items():
+ require(digest(fixtures / name / filename) == expected, "LoRA fixture changed")
+ summary["fixtures"] = manifest
+ configs(evidence.directory / "models", args.source, fixtures, args.arm, snapshot, smoke=args.smoke)
+ app = AppFactory.create_app(
+ AppStateConfig(
+ models_dir=evidence.directory / "models",
+ device="cpu" if args.smoke else "cuda:0",
+ remote_serving=False,
+ bind_host="127.0.0.1",
+ )
+ )
+ sock = socket.socket()
+ sock.bind(("127.0.0.1", 0))
+ url = f"http://127.0.0.1:{sock.getsockname()[1]}"
+ server = uvicorn.Server(uvicorn.Config(app, log_level="warning", timeout_graceful_shutdown=20, access_log=False))
+ task = asyncio.create_task(server.serve(sockets=[sock]))
+ client = Client(url)
+ adapter = None
+ try:
+ while not server.started:
+ if task.done():
+ await task
+ raise RuntimeError("server stopped before readiness")
+ await asyncio.sleep(0.05)
+ registry = app.state.registry
+ load_start = time.monotonic()
+ adapter = await registry.load_async(MODEL, "cpu" if args.smoke else "cuda:0")
+ summary["load_s"] = time.monotonic() - load_start
+ loaded = registry._loaded[MODEL]
+ worker = loaded.worker
+ require(worker is not None, "actual model worker is missing")
+ original = await asyncio.to_thread(tensor_state, adapter)
+ evidence.emit("original_state", state=original)
+ expected_dtype = "torch.float32" if args.smoke else "torch.float16"
+ require(
+ {value["dtype"] for value in original["tensors"].values()} == {expected_dtype},
+ "actual base tensor precision differs from the protocol",
+ )
+ summary["actual_precision"] = expected_dtype
+ summary["loaded_before_forward_memory"] = memory()
+ summary["manager_present"] = getattr(adapter, "_lora", None) is not None
+ require(summary["manager_present"] == (args.arm == "R"), "unexpected manager activation")
+
+ async def call(selection: str | None, label: str, *, cold: bool = False) -> dict[str, Any]:
+ row = await asyncio.to_thread(client.score, selection, label, cold=cold)
+ evidence.emit("request", **row)
+ validate_usage([row], adapter.batch_observations)
+ return row
+
+ adapter.observation_phase = "preselection"
+ bases = [await call(None, f"base-{i}") for i in range(3)]
+ baseline = bases[0]["scores"]
+ drift = max(vector_delta(baseline, row["scores"]) for row in bases)
+ require(drift <= RESTORE_ATOL, "preselection SDK baseline is unstable")
+ if not args.smoke:
+ require(vector_delta(baseline, CPU_ORACLE) <= ORACLE_ATOL, "finite public-checkpoint oracle differs")
+ summary["base_scores"] = baseline
+ summary["base_drift"] = drift
+ summary["shape_oracles"] = await oracle(adapter, worker, None, smoke=args.smoke)
+ evidence.emit("shape_oracles", values=summary["shape_oracles"])
+ # The fixed base memory reference is warm and precedes any adapter
+ # selection; CUDA library initialization is not counted as LoRA bytes.
+ summary["initial_memory"] = memory()
+ selected_oracles = {None: summary["shape_oracles"]}
+ if args.arm == "R":
+ before_fetch = len(adapter.fetch_observations)
+ try:
+ await call("undeclared", "undeclared")
+ except RequestError as error:
+ require(error.status_code == HTTPStatus.BAD_REQUEST, "undeclared selection did not return 400")
+ evidence.emit("undeclared_denied", status=error.status_code, code=error.code)
+ else:
+ raise AssertionError("undeclared LoRA accepted")
+ require(len(adapter.fetch_observations) == before_fetch, "undeclared source reached fetch")
+ adapted = {}
+ for alias in ("a", "b"):
+ if alias == "a":
+ cold_clients = [Client(url) for _ in range(4)]
+ cold_barrier = threading.Barrier(4)
+
+ def cold_call(index: int) -> dict[str, Any]:
+ cold_barrier.wait(timeout=20)
+ return cold_clients[index].score("a", f"singleflight-{index}", cold=True)
+
+ try:
+ cold_rows = await asyncio.gather(*(asyncio.to_thread(cold_call, index) for index in range(4)))
+ finally:
+ for other in cold_clients:
+ other.close()
+ evidence.emit("singleflight_requests", requests=cold_rows)
+ require(
+ sum(any(item.get("code") == "LORA_LOADING" for item in row["responses"]) for row in cold_rows)
+ >= RESIDENT_CAPACITY,
+ "cold duplicate requests did not overlap source loading",
+ )
+ require(
+ len(adapter.fetch_observations) - before_fetch == 1, "duplicate cold requests fetched twice"
+ )
+ adapted[alias] = await call(alias, f"cold-{alias}", cold=True)
+ if alias == "b":
+ require(
+ any(
+ row.get("code") == "LORA_LOADING" and row["status"] == HTTPStatus.SERVICE_UNAVAILABLE
+ for row in adapted[alias]["responses"]
+ ),
+ "cold request did not expose LORA_LOADING",
+ )
+ restored = await call(None, f"reset-{alias}")
+ require(vector_delta(baseline, restored["scores"]) <= RESTORE_ATOL, "base restoration failed")
+ effects = {
+ "a_base": vector_delta(adapted["a"]["scores"], baseline),
+ "b_base": vector_delta(adapted["b"]["scores"], baseline),
+ "a_b": vector_delta(adapted["a"]["scores"], adapted["b"]["scores"]),
+ }
+ evidence.emit("effects", **effects)
+ require(
+ min(effects.values()) >= max(EFFECT_FLOOR, EFFECT_DRIFT_MULTIPLIER * drift),
+ "adapter effects not qualified",
+ )
+ require(
+ len(adapter.fetch_observations) - before_fetch == RESIDENT_CAPACITY,
+ "cold adapters fetched more than once",
+ )
+ for alias in ("a", "b"):
+ selected_oracles[alias] = await oracle(adapter, worker, alias, smoke=args.smoke)
+ adapter.observation_phase = "concurrent-isolation"
+ first = len(adapter.batch_observations)
+ clients = [Client(url) for _ in range(12)]
+ barrier = threading.Barrier(len(clients))
+ selections = [None, "a", "b"] * 4
+
+ def concurrent(index: int) -> dict[str, Any]:
+ barrier.wait(timeout=20)
+ return clients[index].score(selections[index], f"isolation-{index}")
+
+ try:
+ rows = await asyncio.gather(*(asyncio.to_thread(concurrent, index) for index in range(len(clients))))
+ finally:
+ for other in clients:
+ other.close()
+ evidence.emit("concurrent_requests", requests=rows)
+ batches = adapter.batch_observations[first:]
+ evidence.emit("concurrent_batches", batches=batches)
+ validate_usage(rows, batches)
+ combined = set()
+ for batch in batches:
+ selections_in_batch = {selections[int(item.split(":")[0].split("-")[-1])] for item in batch["item_ids"]}
+ require(len(selections_in_batch) == 1, "one forward mixed adapter selections")
+ alias = next(iter(selections_in_batch))
+ source = str(fixtures / alias) if alias else None
+ require(batch["selection"] in (alias, source), "actual worker selection differs from request")
+ key = batch_key(batch)
+ require(
+ vector_delta(batch["scores"], selected_oracles[alias][key]["scores"]) <= RESTORE_ATOL,
+ "concurrent selected scores differ from shape-matched oracle",
+ )
+ expected_peft = PEFTLoRAMixin._peft_adapter_name(source) if source else None
+ for forward in batch["forwards"]:
+ enabled = forward["enabled_adapters"]
+ require(bool(enabled) == bool(alias), "actual adapter enable state differs at model forward")
+ require(
+ all(item["adapters"] == [expected_peft] for item in enabled), "wrong PEFT adapter at forward"
+ )
+ if len({item.split(":")[0] for item in batch["item_ids"]}) > 1:
+ combined.add(alias)
+ require(combined == {None, "a", "b"}, "did not observe cross-request batches for base, A and B")
+ require(
+ max(row["start_ns"] for row in rows) < min(row["end_ns"] for row in rows), "SDK calls did not overlap"
+ )
+ await call(None, "before-performance-base")
+ require(set(registry.loaded_lora_names(MODEL)) == {"a", "b"}, "resident set before R measurement differs")
+ summary["adapter_storage"] = adapter_storage(adapter)
+ base_unchanged(original, await asyncio.to_thread(tensor_state, adapter))
+
+ summary["untimed_replays"] = {}
+ adapter.observation_phase = "untimed-shape-qualification"
+ for concurrency in (1, *CONCURRENCIES):
+ first = len(adapter.batch_observations)
+ rows = await asyncio.to_thread(replay, url, concurrency)
+ batches = adapter.batch_observations[first:]
+ evidence.emit("untimed_replay", concurrency=concurrency, requests=rows, batches=batches)
+ summary["untimed_replays"][str(concurrency)] = {"requests": rows, "batches": batches}
+ validate_usage(rows, batches)
+ for batch in batches:
+ key = batch_key(batch)
+ require(
+ vector_delta(batch["scores"], summary["shape_oracles"][key]["scores"]) <= RESTORE_ATOL,
+ "untimed SDK replay differs from preselection shape oracle",
+ )
+ require(batch["selection"] is None, "untimed base replay selected a LoRA")
+ require(
+ all(not forward["enabled_adapters"] for forward in batch["forwards"]),
+ "untimed base replay left a PEFT adapter enabled",
+ )
+ if concurrency > 1:
+ require(
+ any(len({item.split(":")[0] for item in batch["item_ids"]}) > 1 for batch in batches),
+ "untimed concurrent replay did not combine independent SDK requests",
+ )
+ summary["resident_memory"] = memory()
+ summary["performance"] = {}
+ with unobserved(adapter):
+ for concurrency in (1, *CONCURRENCIES):
+ phase = f"performance-C{concurrency}"
+ evidence.emit("gpu_before_phase", phase=phase, telemetry=telemetry())
+ measured = await asyncio.to_thread(performance, url, concurrency, evidence, smoke=args.smoke)
+ summary["performance"][str(concurrency)] = measured
+ evidence.emit("performance", phase=phase, **measured)
+ atomic_json(evidence.directory / "trial.json", summary)
+ for row in measured["samples"]:
+ require(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"])
+ measured["actual_timed_batch_shape"] = "unobserved"
+ evidence.emit(
+ "timed_output_diagnostics",
+ concurrency=concurrency,
+ matches=[
+ {"label": row["label"], "matches": row["diagnostic_matching_oracles"]}
+ for row in measured["samples"]
+ ],
+ )
+ evidence.emit("gpu_after_phase", phase=phase, telemetry=telemetry())
+ adapter.observation_phase = "lifecycle"
+ if args.arm == "R":
+ previous = set(registry.loaded_lora_names(MODEL))
+ evicted = set()
+ for index, alias in enumerate(("c", "a", "b", "c")):
+ await call(alias, f"churn-{index}", cold=True)
+ ready = set(registry.loaded_lora_names(MODEL))
+ require(alias in ready and len(ready) == RESIDENT_CAPACITY, "LRU capacity/readiness differs")
+ evicted.update(previous - ready)
+ evidence.emit("resident_set", selected=alias, ready=sorted(ready))
+ previous = ready
+ require(evicted == {"a", "b", "c"}, "LRU churn failed to evict each dynamic adapter")
+
+ async def unload_adapters() -> None:
+ for name in list(loaded.loras):
+ await registry._unload_lora(loaded, name, model=MODEL)
+ loaded.loras.pop(name)
+
+ await unload_adapters()
+ final_state = await asyncio.to_thread(tensor_state, adapter)
+ evidence.emit("restored_state", state=final_state)
+ base_unchanged(original, final_state, restored=True)
+ restored = await call(None, "final-unloaded-base")
+ require(vector_delta(baseline, restored["scores"]) <= RESTORE_ATOL, "final unload changed base output")
+ summary["unloaded_memory"] = memory()
+ require(
+ summary["unloaded_memory"]["allocated"] == summary["initial_memory"]["allocated"],
+ "adapter unload did not restore allocated GPU bytes",
+ )
+ await call("a", "same-instance-reload", cold=True)
+ require(id(adapter._model) == original["wrapper_id"], "reload replaced outer wrapper")
+ await unload_adapters()
+ base_unchanged(original, await asyncio.to_thread(tensor_state, adapter), restored=True)
+ require(not adapter.mutation_overlap, "adapter mutation overlapped a score forward")
+ evidence.emit(
+ "all_batches",
+ batches=adapter.batch_observations,
+ selections=adapter.selection_observations,
+ fetches=adapter.fetch_observations,
+ )
+ inner_ref = weakref.ref(adapter._model.model)
+ outer_ref = weakref.ref(adapter._model)
+ await registry.unload_async(MODEL)
+ gc.collect()
+ require(
+ adapter._model is None and outer_ref() is None and inner_ref() is None,
+ "full model unload retained wrapper or inner model",
+ )
+ summary["model_unloaded_memory"] = memory()
+ summary["passed"] = True
+ finally:
+ try:
+ evidence.emit(
+ "client_wire_responses", responses=[describe_response(response) for response in client.responses]
+ )
+ if adapter is not None:
+ evidence.emit(
+ "final_batch_snapshot",
+ batches=adapter.batch_observations,
+ fetches=adapter.fetch_observations,
+ mutation_overlap=adapter.mutation_overlap,
+ )
+ finally:
+ try:
+ client.close()
+ finally:
+ server.should_exit = True
+ try:
+ await asyncio.wait_for(asyncio.shield(task), timeout=30)
+ summary["shutdown_complete"] = True
+ finally:
+ sock.close()
+
+
+async def run(args: argparse.Namespace) -> dict[str, Any]:
+ evidence = Evidence(args.output.resolve())
+ summary: dict[str, Any] = {
+ "arm": args.arm,
+ "pair": args.pair,
+ "passed": False,
+ "shutdown_complete": False,
+ "smoke": args.smoke,
+ "pid": os.getpid(),
+ }
+ os.environ.update(
+ {
+ "SIE_TELEMETRY_DISABLED": "1",
+ "SIE_DISK_CACHE_ENABLED": "false",
+ "SIE_MAX_LORAS_PER_MODEL": "2",
+ "SIE_MAX_BATCH_REQUESTS": str(MAX_BATCH_ITEMS),
+ "TOKENIZERS_PARALLELISM": "false",
+ }
+ )
+ torch.set_num_threads(THREADS)
+ torch.set_num_interop_threads(1)
+ try:
+ summary["environment"] = preflight(args, evidence)
+ async with asyncio.timeout(args.deadline_s):
+ await experiment(args, evidence, summary)
+ except BaseException as error:
+ summary["passed"] = False
+ summary["error"] = error_record(error)
+ evidence.emit("failure", **summary["error"])
+ raise
+ finally:
+ atomic_json(evidence.directory / "trial.json", summary)
+ evidence.emit("finished", passed=summary["passed"], shutdown_complete=summary["shutdown_complete"])
+ return summary
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--source", type=Path, required=True)
+ parser.add_argument("--fixtures", type=Path, required=True)
+ parser.add_argument("--snapshot", type=Path)
+ parser.add_argument("--output", type=Path, required=True)
+ parser.add_argument("--arm", choices=("B", "N", "R"), required=True)
+ parser.add_argument("--pair", type=int, default=0)
+ parser.add_argument("--deadline-s", type=float, default=180)
+ parser.add_argument("--smoke", action="store_true")
+ args = parser.parse_args()
+ require(0 < args.deadline_s <= MAX_TRIAL_SECONDS, "worker deadline must be in (0, 300]")
+ asyncio.run(run(args))
+
+
+if __name__ == "__main__":
+ main()