From 6295ba1d925abbc982169e12f97d9cf12b8e311b Mon Sep 17 00:00:00 2001 From: Constantin Date: Sun, 1 Nov 2026 12:25:18 -0500 Subject: [PATCH] Bind Spark quality probes to measured artifacts Hash architecture and quantizer inventories as well as kernels. Bind reusable references to model bytes, corpus, runtime, settings and data. Bind tail replay to scored reports and launch the verified candidate privately. Reject incomplete forced-length QoS responses. Add CPU-only positive and negative attribution tests; no GPU certification is implied. --- docs/SPARK25-IQ8R.md | 34 ++-- tests/CMakeLists.txt | 3 + tests/spark25_kld_tail.py | 268 +++++++++++++++++++---------- tests/spark25_qos.py | 54 +++--- tests/spark25_quality.py | 75 ++++---- tests/spark25_validation.py | 86 ++++++++++ tests/spark25_validation_test.py | 284 +++++++++++++++++++++++++++++++ 7 files changed, 649 insertions(+), 155 deletions(-) create mode 100644 tests/spark25_validation.py create mode 100644 tests/spark25_validation_test.py diff --git a/docs/SPARK25-IQ8R.md b/docs/SPARK25-IQ8R.md index c622ee15..5587931d 100644 --- a/docs/SPARK25-IQ8R.md +++ b/docs/SPARK25-IQ8R.md @@ -102,10 +102,16 @@ required collectives. Calibration itself remains TP=1. ## Reproduce matched KLD and tail replays -Use a private output directory; the reference is immutable once `kld.json` is written. The harness -hashes the checkpoint, executable, corpus, evaluation manifest, loaded kernel shared objects, and -optional source revision into `run.json`. It replays the same corpus against BF16 once and scores -each candidate against that reference, with fixed chunking/cache/TP flags: +Use a private output directory; the reference is immutable once recorded. The harness hashes the +checkpoint, executable, corpus, evaluation manifest, and **kernel, architecture and optional quantizer +shared-object inventories** into `run.json`. This includes the architecture graph plugin, not only +`libr4d.so`; an optional source revision is context, not proof that a binary was built from it. The +inventory must remain unchanged during the measurement. These probes accept one explicit home, not +a colon-separated home search path. They replay the same corpus against BF16 once and score each +candidate with fixed chunking/cache/TP flags. A reference `provenance.json` binds the BF16 model bytes, +corpus, runtime/plugins, settings and recorded data files. `--reuse-reference` requires this binding +to match; legacy unbound references must be recorded afresh, not relabelled with the supplied model. +Reports and per-position score files are hashed into the run receipt as well: ```sh python3 tests/spark25_quality.py \\ @@ -118,16 +124,19 @@ python3 tests/spark25_quality.py \\ --candidate "full=$FULL_IQ8R" --candidate "keep12=$KEEP12" ``` -Run that process inside the host's exclusive GPU/device scope for `libr4d`. For one of the candidate -reports, start that same model as a server with TP=1, BF16 KV, `--max-model-len 4096`, -`--max-num-seqs 1`, `--max-num-batched-tokens 128`, `--num-speculative-tokens 0`, and -`--no-prefix-cache`. Then replay the highest-KL rows with their exact token prefixes from the BF16 -reference (the tool checks the server consumed every prefix token): +Run that process inside the host's exclusive GPU/device scope for `libr4d`. To replay a candidate's +highest-KL rows, run the following **inside the same kind of device scope**. The tool validates the +report's reference/corpus/model identities, report/row hashes, reference binding, and current runtime, +model and plugin hashes against `run.json`, then starts its own private candidate server with the +scoring run's TP, BF16 KV, model/chunk limits, speculation0 and prefix-cache-off settings. It verifies +the private served ID and the consumed prefix/completion/cache counts. Arbitrary external `--url` +servers are not accepted: a served alias alone cannot prove which checkpoint was loaded. ```sh python3 tests/spark25_kld_tail.py \\ + --run "$RUN/run.json" \\ --reference "$RUN/bf16-top128-ref" --report "$RUN/full-kld.json" \\ - --url http://127.0.0.1:5914 --model spark --out "$RUN/full-tail-replay.json" + --out "$RUN/full-tail-replay.json" ``` The replay compares candidate top-20 log-probabilities with the stored reference top-20 for the @@ -140,7 +149,10 @@ Run this separately for each model, one process/container at a time and under an scope. It reuses the same evaluation prompts, disables prefix caching and speculation, and stores per-request latency plus p50/p95/max and aggregate generated-token throughput at each concurrency. These are end-to-end request measurements (prefill plus decode and service overhead), not decode-only -throughput or task scores: +throughput or task scores. Every response must report positive integer prompt usage and exactly +`--max-tokens` generated tokens with a `length` finish (EOS is ignored for this fixed-work smoke). +Missing, zero or short counts fail the run rather than producing a successful throughput receipt. +Runtime/model/plugin hashes are checked again before writing the receipt; use a fresh `--out`: ```sh python3 tests/spark25_qos.py \\ diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index cffd1652..a338c3b9 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -799,6 +799,9 @@ find_program(RAD_PYTHON3 NAMES python3) if(RAD_PYTHON3) add_test(NAME rad_export_test COMMAND ${RAD_PYTHON3} ${CMAKE_CURRENT_SOURCE_DIR}/rad_export_test.py) set_tests_properties(rad_export_test PROPERTIES LABELS "unit;fast" TIMEOUT ${RAD_TEST_TIMEOUT}) + add_test(NAME spark25_validation_test + COMMAND ${RAD_PYTHON3} ${CMAKE_CURRENT_SOURCE_DIR}/spark25_validation_test.py) + set_tests_properties(spark25_validation_test PROPERTIES LABELS "unit;fast" TIMEOUT ${RAD_TEST_TIMEOUT}) endif() # ================================================================== the shipped plugins, out of tree diff --git a/tests/spark25_kld_tail.py b/tests/spark25_kld_tail.py index 94088c73..ae3df955 100644 --- a/tests/spark25_kld_tail.py +++ b/tests/spark25_kld_tail.py @@ -1,123 +1,218 @@ #!/usr/bin/env python3 -"""Replay the largest matched-reference IQ8R KLD rows as one-token requests. +"""Replay severe sparse-KL rows with a private, artifact-bound candidate server. -Uses the exact token prefixes recorded with --kld-record and verifies the server consumed each -entire prefix. Run against one candidate server configured with the same TP, BF16 KV, chunk limit, -no speculation, and no prefix cache as the KLD scoring run. The report stores only row metadata and -top candidates, not the prompt token sequence. +Requires run.json from spark25_quality.py. The server is started here, using that +run's candidate, executable, plugins and settings; an arbitrary external URL or +served-model alias cannot establish the model's identity. Run the whole command +inside the same exclusive GPU/device scope as the original measurement. """ import argparse +from contextlib import contextmanager import json +import math +import os from pathlib import Path +import socket import struct +import subprocess import sys +import time import urllib.error import urllib.request +import uuid + +from spark25_validation import (plugin_hashes, reference_provenance, same_path, sha256, + validate_reference, validate_report) -def post(url, body, timeout): - req = urllib.request.Request(url.rstrip("/") + "/v1/completions", - json.dumps(body).encode(), - {"Content-Type": "application/json"}) - with urllib.request.urlopen(req, timeout=timeout) as response: +def bound_run(run_path, ref_dir, report_path): + run = json.loads(Path(run_path).read_text()) + ref = json.loads((ref_dir / "kld.json").read_text()) + report = json.loads(report_path.read_text()) + same_path(run["reference_dir"], ref_dir, "run reference directory") + validate_reference(ref, run["reference_model"], run["corpus"]) + if run["reference_manifest"] != ref: + raise ValueError("run reference manifest differs from the supplied reference") + matches = [item for item in run["candidates"].values() + if Path(item["report"]).resolve() == report_path] + if len(matches) != 1: + raise ValueError("report must identify exactly one candidate in run.json") + candidate = matches[0] + validate_report(report, ref_dir, run["reference_model"], run["corpus"], + candidate["model"], ref["rows"]) + same_path(candidate["rows"], str(report_path) + ".rows", "candidate row file") + for path, expected in ((report_path, candidate["report_sha256"]), + (candidate["rows"], candidate["rows_sha256"]), + (candidate["model"], candidate["sha256"]), + (run["reference_model"], run["reference_sha256"]), + (run["corpus"], run["corpus_sha256"]), + (run["radiance"], run["radiance_sha256"])): + if sha256(path) != expected: + raise ValueError(f"artifact hash differs from run.json: {path}") + plugins = plugin_hashes(run["radiance_home"]) + if any(run[key] != value for key, value in plugins.items()): + raise ValueError("plugin inventory differs from the scored run") + common = ["--radiance-home", run["radiance_home"], "--kernels", run["kernel_selector"], + "--tp", str(run["tp"]), "--kv-cache-dtype", "bf16", "--max-num-seqs", "1", + "--max-model-len", str(run["max_model_len"]), "--max-num-batched-tokens", + str(run["max_num_batched_tokens"]), "--gpu-headroom-mib", + str(run["gpu_headroom_mib"]), "--num-speculative-tokens", "0", "--no-prefix-cache"] + inputs = {key: run[key] for key in ("reference_model", "reference_sha256", "corpus", + "corpus_sha256", "corpus_fnv1a64", "radiance", + "radiance_sha256")} + inputs.update(plugins=plugins, arguments=common) + if reference_provenance(ref_dir, inputs, reuse=True) != run["reference_provenance"]: + raise ValueError("run reference provenance differs from the scored baseline") + return run, candidate, ref, report, common + + +def get(url, timeout): + with urllib.request.urlopen(url, timeout=timeout) as response: return json.load(response) -def main(): - p = argparse.ArgumentParser(description=__doc__) - p.add_argument("--reference", required=True, type=Path, - help="directory from --kld-record (top-128 + tail)") - p.add_argument("--report", required=True, type=Path, - help="candidate --kld-out JSON; matching .rows file must be present") - p.add_argument("--url", required=True, help="candidate Radiance base URL, e.g. http://127.0.0.1:5914") - p.add_argument("--model", default="spark", help="served model name") - p.add_argument("--out", required=True, type=Path) - p.add_argument("--limit", type=int, default=20, help="replay this many largest-KL rows") - p.add_argument("--threshold", type=float, default=1.0, - help="also include every row above this coarsened KL threshold") - p.add_argument("--timeout", type=float, default=120) - args = p.parse_args() +def post(url, model, prompt, timeout): + request = urllib.request.Request(url + "/v1/completions", json.dumps({ + "model": model, "prompt": prompt, "max_tokens": 1, "temperature": 0, + "ignore_eos": True, "logprobs": 20}).encode(), {"Content-Type": "application/json"}) + with urllib.request.urlopen(request, timeout=timeout) as response: + return json.load(response) - ref_dir, report_path, out = args.reference.resolve(), args.report.resolve(), args.out.resolve() - ref = json.loads((ref_dir / "kld.json").read_text()) - report = json.loads(report_path.read_text()) - if ref.get("format") != "radiance-kld-top-1" or ref.get("top") != 128: - p.error("reference must be radiance-kld-top-1 with top=128") - if report.get("ref_form") != "top-128 + tail": - p.error("candidate report was not scored against the top-128-plus-tail reference") - n = int(ref["rows"]) - if report.get("all", {}).get("positions") != n: - p.error("candidate report position count differs from the reference") - raw_rows = Path(str(report_path) + ".rows").read_bytes() - if len(raw_rows) != n * 4 * 4: - p.error("candidate .rows file has an unexpected size") + +@contextmanager +def candidate_server(run, candidate, common, log_path): + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + model = "spark-tail-" + uuid.uuid4().hex + url = f"http://127.0.0.1:{port}" + command = [run["radiance"], "--model", candidate["model"], *common, + "--host", "127.0.0.1", "--port", str(port), "--served-model-name", model] + with log_path.open("w") as log: + env = os.environ.copy() + env.pop("HF_TOKEN", None) + proc = subprocess.Popen(command, env=env, stdout=log, stderr=subprocess.STDOUT) + try: + deadline = time.monotonic() + 240 + while time.monotonic() < deadline: + if proc.poll() is not None: + raise RuntimeError(f"candidate server exited; see {log_path}") + try: + get(url + "/health", 1) + break + except (OSError, urllib.error.URLError): + time.sleep(0.2) + else: + raise TimeoutError(f"candidate server readiness timeout; see {log_path}") + models = get(url + "/v1/models", 5) + if (proc.poll() is not None or + model not in {item.get("id") for item in models.get("data", [])}): + raise ValueError("private server identity does not match the launched candidate") + yield {"url": url, "model": model, "pid": proc.pid, "command": command} + finally: + proc.terminate() + try: + proc.wait(timeout=30) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--run", required=True, type=Path, help="bound quality run.json") + parser.add_argument("--reference", required=True, type=Path) + parser.add_argument("--report", required=True, type=Path, help="candidate KLD JSON with .rows") + parser.add_argument("--out", required=True, type=Path) + parser.add_argument("--limit", type=int, default=20) + parser.add_argument("--threshold", type=float, default=1.0) + parser.add_argument("--timeout", type=float, default=120) + args = parser.parse_args() + if (args.limit < 1 or not math.isfinite(args.threshold) or args.threshold < 0 or + not math.isfinite(args.timeout) or args.timeout <= 0): + parser.error("limit/timeout must be positive and threshold finite and nonnegative") + run_path, ref_dir = args.run.resolve(), args.reference.resolve() + report_path, out = args.report.resolve(), args.out.resolve() + if out.exists(): + parser.error("replay receipt already exists; choose a fresh --out") + run_digest = sha256(run_path) + run, candidate, ref, report, common = bound_run(run_path, ref_dir, report_path) + n = ref["rows"] + raw_rows = Path(candidate["rows"]).read_bytes() + if len(raw_rows) != n * 16: + raise ValueError("candidate .rows file has an unexpected size") values = struct.unpack("<" + "f" * (n * 4), raw_rows) kls = [values[4 * i] for i in range(n)] + # Preserve signed roundoff near zero from core/kld.cpp rather than clamp the data. + if not all(math.isfinite(kl) for kl in kls): + raise ValueError("candidate has non-finite coarsened KL rows") above = [i for i, kl in enumerate(kls) if kl > args.threshold] selected = set(sorted(range(n), key=kls.__getitem__, reverse=True)[:args.limit]) selected.update(above) selected = sorted(selected, key=kls.__getitem__, reverse=True) - docs = ref["docs"] tokens_raw = (ref_dir / "tokens.i32").read_bytes() if len(tokens_raw) % 4: - p.error("tokens.i32 has an unexpected size") + raise ValueError("tokens.i32 has an unexpected size") tokens = struct.unpack("<" + "i" * (len(tokens_raw) // 4), tokens_raw) - token_starts = [] - total = 0 + token_starts, total = [], 0 for doc in docs: token_starts.append(total) total += int(doc["tokens"]) if total != len(tokens): - p.error("tokens.i32 length does not match the reference manifest") + raise ValueError("tokens.i32 length does not match the reference manifest") spans = [(int(d["row0"]), int(d["row0"]) + int(d["tokens"]) - int(d["score_from"]) - 1) for d in docs] - top_count = int(ref["top"]) top_raw = (ref_dir / "top.bin").read_bytes() - if len(top_raw) != n * top_count * 8: - p.error("top.bin has an unexpected size") - + if len(top_raw) != n * 128 * 8: + raise ValueError("top.bin has an unexpected size") results = [] - for row in selected: - doc_index = next((i for i, (lo, hi) in enumerate(spans) if lo <= row < hi), None) - if doc_index is None: - p.error(f"row {row} is outside every reference document") - doc = docs[doc_index] - token_pos = int(doc["score_from"]) + row - int(doc["row0"]) - begin = token_starts[doc_index] - prompt = list(tokens[begin:begin + token_pos + 1]) - if not prompt: - p.error(f"row {row} produced an empty replay prompt") - ref_entries = [struct.unpack_from(" 1.0 for x in kl)} print(f"{name}: {expected_rows} positions; ref_form={scored['ref_form']}; " @@ -178,6 +169,10 @@ def main(): f"p99.9={values['p99_9']:.6g}, max={values['max']:.6g}, " f">1 nat={run['candidates'][name]['positions_over_1_nat']}") + if (plugin_hashes(home) != plugins or sha256(radiance) != run["radiance_sha256"] or + sha256(reference) != run["reference_sha256"]): + p.error("runtime, reference model or plugin inventory changed during the run") + reference_provenance(ref_dir, reference_inputs, reuse=True) (out / "run.json").write_text(json.dumps(run, indent=2) + "\n") print(f"Run receipt: {out / 'run.json'}") print("Per-position rows are available as -kld.json.rows; replay severe positions with " @@ -186,4 +181,8 @@ def main(): if __name__ == "__main__": - sys.exit(main()) + try: + sys.exit(main()) + except (KeyError, OSError, ValueError, subprocess.CalledProcessError) as exc: + print(f"spark25_quality: {exc}", file=sys.stderr) + sys.exit(1) diff --git a/tests/spark25_validation.py b/tests/spark25_validation.py new file mode 100644 index 00000000..614e4935 --- /dev/null +++ b/tests/spark25_validation.py @@ -0,0 +1,86 @@ +"""Artifact and reference bindings shared by the real-container Spark probes.""" +import hashlib +import json +from pathlib import Path + + +def sha256(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for block in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def fnv1a64(path): + # core/kld.cpp hashes each getline without its terminating LF. + value = 1469598103934665603 + with Path(path).open("rb") as stream: + for line in stream: + if line.endswith(b"\n"): + line = line[:-1] + for byte in line: + value = ((value ^ byte) * 1099511628211) & 0xffffffffffffffff + return f"{value:016x}" + + +def plugin_hashes(home): + home = Path(home).resolve() + if ":" in str(home): + raise ValueError("these probes require one explicit RADIANCE_HOME, not a search path") + result = {} + for directory, key in (("kernels", "kernel_shared_objects"), + ("architectures", "architecture_shared_objects"), + ("quantizers", "quantizer_shared_objects")): + result[key] = {str(path.relative_to(home)): sha256(path) + for path in sorted((home / directory).rglob("*.so"))} + if directory != "quantizers" and not result[key]: + raise ValueError(f"no shared objects found in {home / directory}") + return result + + +def same_path(value, expected, label): + if not isinstance(value, str) or not value or Path(value).resolve() != Path(expected).resolve(): + raise ValueError(f"{label} does not match {expected}") + + +def validate_reference(meta, reference, corpus): + if meta.get("format") != "radiance-kld-top-1" or meta.get("top") != 128: + raise ValueError("reference must be radiance-kld-top-1 with top=128") + same_path(meta.get("model"), reference, "reference model") + same_path(meta.get("corpus"), corpus, "reference corpus") + if meta.get("corpus_fnv1a64") != fnv1a64(corpus): + raise ValueError("reference corpus hash does not match the corpus") + if type(meta.get("rows")) is not int or meta["rows"] <= 0: + raise ValueError("reference must have a positive integer row count") + + +def validate_report(report, ref_dir, reference, corpus, candidate, rows): + if report.get("ref_form") != "top-128 + tail": + raise ValueError("report must use the top-128-plus-tail reference") + for key, expected in (("ref_dir", ref_dir), ("reference", reference), + ("corpus", corpus), ("model", candidate)): + same_path(report.get(key), expected, f"report {key}") + if report.get("all", {}).get("positions") != rows: + raise ValueError("report row count does not match the reference") + + +def reference_provenance(ref_dir, inputs, reuse): + """Reject legacy/unbound references rather than relabel their baseline in a new receipt.""" + ref_dir = Path(ref_dir) + path = ref_dir / "provenance.json" + current = {"format": "spark25-reference-provenance-1", "inputs": inputs, + "files": {name: sha256(ref_dir / name) + for name in ("kld.json", "tokens.i32", "top.bin", "rows.f32")}} + if reuse: + if not path.is_file(): + raise ValueError("reference lacks provenance.json; record a fresh bound reference") + if json.loads(path.read_text()) != current: + raise ValueError("reused reference baseline, runtime, settings or data identity differs") + else: + if path.exists(): + raise ValueError(f"refusing to replace existing reference provenance: {path}") + temporary = path.with_suffix(".json.tmp") + temporary.write_text(json.dumps(current, indent=2) + "\n") + temporary.replace(path) + return current diff --git a/tests/spark25_validation_test.py b/tests/spark25_validation_test.py new file mode 100644 index 00000000..a2099381 --- /dev/null +++ b/tests/spark25_validation_test.py @@ -0,0 +1,284 @@ +#!/usr/bin/env python3 +"""CPU-only positive/negative controls for Spark measurement attribution (not GPU evidence).""" +import contextlib +import copy +import io +import json +from pathlib import Path +import struct +import sys +import tempfile +import unittest +from unittest.mock import Mock, patch + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import spark25_kld_tail as tail +import spark25_qos as qos +import spark25_quality as quality +from spark25_validation import fnv1a64, plugin_hashes, sha256, validate_report + + +class MeasurementTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.home = self.root / "home" + for directory in ("kernels", "architectures", "quantizers"): + (self.home / directory).mkdir(parents=True) + (self.home / directory / "fixture.so").write_bytes(directory.encode()) + self.reference = self.root / "bf16.rad" + self.candidate = self.root / "candidate.rad" + self.runtime = self.root / "radiance" + self.corpus = self.root / "corpus.jsonl" + self.reference.write_bytes(b"BF16 checkpoint") + self.candidate.write_bytes(b"IQ8R checkpoint") + self.runtime.write_bytes(b"not executed; subprocess is mocked") + self.corpus.write_text('{"prompt":"a b", "score_from":0}\n') + self.out = self.root / "quality" + self.score_kl = .1 + + def fake_runtime(self, command, **kwargs): + def arg(name): + return command[command.index(name) + 1] + if "--kld-record" in command: + directory = Path(arg("--kld-record")) + meta = {"format": "radiance-kld-top-1", "model": arg("--model"), + "corpus": arg("--kld-corpus"), "corpus_fnv1a64": fnv1a64(self.corpus), + "top": 128, "rows": 1, + "docs": [{"tokens": 2, "score_from": 0, "row0": 0, "source": "fixture"}]} + (directory / "kld.json").write_text(json.dumps(meta)) + (directory / "tokens.i32").write_bytes(struct.pack("