Archived
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.
This commit is contained in:
1 parent
40442cc81b
commit
6295ba1d92
7 files changed
+649
-155
No files matched your search
+23
-11
@@ -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 \\
|
||||
|
||||
@@ -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
|
||||
|
||||
+182
-86
@@ -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("<if", top_raw, (row * top_count + i) * 8)
|
||||
for i in range(top_count)]
|
||||
ref_top = sorted(ref_entries, key=lambda item: (-item[1], item[0]))[:20]
|
||||
response = post(args.url, {"model": args.model, "prompt": prompt, "max_tokens": 1,
|
||||
"temperature": 0, "ignore_eos": True, "logprobs": 20},
|
||||
args.timeout)
|
||||
if int(response.get("usage", {}).get("prompt_tokens", -1)) != len(prompt):
|
||||
p.error(f"row {row}: server did not consume the full {len(prompt)}-token replay prefix")
|
||||
choice = response["choices"][0]
|
||||
content = choice["logprobs"]["content"]
|
||||
if len(content) != 1:
|
||||
p.error(f"row {row}: expected one scored output token, got {len(content)}")
|
||||
got = content[0]["top_logprobs"]
|
||||
got_top = [{"token_id": int(item["id"]), "logprob": float(item["logprob"])}
|
||||
for item in got]
|
||||
result = {
|
||||
"row": row, "source": doc.get("source", ""), "document_index": doc_index,
|
||||
"token_position": token_pos, "prompt_tokens": len(prompt), "coarsened_kl": kls[row],
|
||||
"top1_agreement_from_kld": bool(values[4 * row + 3]),
|
||||
"reference_top20": [{"token_id": int(i), "logprob": float(lp)} for i, lp in ref_top],
|
||||
"candidate_top20": got_top,
|
||||
}
|
||||
results.append(result)
|
||||
print(f"row={row} source={result['source']} token={token_pos} prompt={len(prompt)} "
|
||||
f"top128+tail-KL={kls[row]:.6g} top1-agree={result['top1_agreement_from_kld']}")
|
||||
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(json.dumps({"reference": str(ref_dir), "candidate_report": str(report_path),
|
||||
"ref_form": report["ref_form"], "threshold": args.threshold,
|
||||
"rows_above_threshold": len(above), "replayed": results}, indent=2) + "\n")
|
||||
with candidate_server(run, candidate, common, out.with_suffix(".server.log")) as server:
|
||||
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:
|
||||
raise ValueError(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:
|
||||
raise ValueError(f"row {row} produced an empty replay prompt")
|
||||
ref_entries = [struct.unpack_from("<if", top_raw, (row * 128 + i) * 8)
|
||||
for i in range(128)]
|
||||
ref_top = sorted(ref_entries, key=lambda item: (-item[1], item[0]))[:20]
|
||||
response = post(server["url"], server["model"], prompt, args.timeout)
|
||||
usage = response.get("usage", {})
|
||||
if (usage.get("prompt_tokens") != len(prompt) or usage.get("completion_tokens") != 1 or
|
||||
usage.get("prompt_tokens_details", {}).get("cached_tokens") != 0):
|
||||
raise ValueError(f"row {row}: prefix, completion or cold-cache accounting mismatch")
|
||||
content = response["choices"][0]["logprobs"]["content"]
|
||||
if len(content) != 1 or len(content[0]["top_logprobs"]) != 20:
|
||||
raise ValueError(f"row {row}: expected one scored output with top20")
|
||||
got_top = [{"token_id": int(item["id"]), "logprob": float(item["logprob"])}
|
||||
for item in content[0]["top_logprobs"]]
|
||||
if not all(math.isfinite(item["logprob"]) for item in got_top):
|
||||
raise ValueError(f"row {row}: non-finite candidate logprob")
|
||||
result = {"row": row, "source": doc.get("source", ""), "document_index": doc_index,
|
||||
"token_position": token_pos, "prompt_tokens": len(prompt), "coarsened_kl": kls[row],
|
||||
"top1_agreement_from_kld": bool(values[4 * row + 3]),
|
||||
"reference_top20": [{"token_id": int(i), "logprob": float(lp)} for i, lp in ref_top],
|
||||
"candidate_top20": got_top}
|
||||
results.append(result)
|
||||
print(f"row={row} source={result['source']} token={token_pos} prompt={len(prompt)} "
|
||||
f"top128+tail-KL={kls[row]:.6g} top1-agree={result['top1_agreement_from_kld']}")
|
||||
# A changed binary/model/report cannot silently acquire a successful replay receipt.
|
||||
bound_run(run_path, ref_dir, report_path)
|
||||
if sha256(run_path) != run_digest:
|
||||
raise ValueError("run.json changed during replay")
|
||||
out.write_text(json.dumps({"source_run": str(run_path), "source_run_sha256": run_digest,
|
||||
"reference": str(ref_dir), "candidate_report": str(report_path),
|
||||
"candidate_model": candidate["model"], "candidate_sha256": candidate["sha256"],
|
||||
"radiance_sha256": run["radiance_sha256"], "server": server,
|
||||
**{key: run[key] for key in plugin_hashes(run["radiance_home"])},
|
||||
"ref_form": report["ref_form"], "threshold": args.threshold,
|
||||
"rows_above_threshold": len(above), "replayed": results}, indent=2) + "\n")
|
||||
print(f"Replay receipt: {out}")
|
||||
return 0
|
||||
|
||||
@@ -125,6 +220,7 @@ def main():
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except (KeyError, OSError, ValueError, struct.error, urllib.error.URLError) as exc:
|
||||
except (KeyError, OSError, ValueError, TypeError, struct.error, urllib.error.URLError,
|
||||
TimeoutError, RuntimeError) as exc:
|
||||
print(f"spark25_kld_tail: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
+34
-20
@@ -8,8 +8,8 @@ latency, and aggregate generated-token throughput; it does not claim task qualit
|
||||
"""
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
@@ -20,12 +20,7 @@ import urllib.error
|
||||
import urllib.request
|
||||
|
||||
|
||||
def sha256(path):
|
||||
h = hashlib.sha256()
|
||||
with Path(path).open("rb") as f:
|
||||
for block in iter(lambda: f.read(8 * 1024 * 1024), b""):
|
||||
h.update(block)
|
||||
return h.hexdigest()
|
||||
from spark25_validation import plugin_hashes, sha256
|
||||
|
||||
|
||||
def quantile(values, q):
|
||||
@@ -43,8 +38,8 @@ def prompts_from(path):
|
||||
if not line:
|
||||
continue
|
||||
row = json.loads(line)
|
||||
if not isinstance(row.get("prompt"), str):
|
||||
raise ValueError(f"{path}:{line_no}: expected a string prompt")
|
||||
if not isinstance(row.get("prompt"), str) or not row["prompt"].strip():
|
||||
raise ValueError(f"{path}:{line_no}: expected a nonempty string prompt")
|
||||
prompts.append({"source": row.get("source", ""), "prompt": row["prompt"]})
|
||||
if not prompts:
|
||||
raise ValueError(f"{path}: no prompts")
|
||||
@@ -60,10 +55,21 @@ def request(url, model, prompt, max_tokens, timeout):
|
||||
with urllib.request.urlopen(req, timeout=timeout) as response:
|
||||
data = json.load(response)
|
||||
elapsed = time.perf_counter() - start
|
||||
usage = data.get("usage", {})
|
||||
return {"seconds": elapsed, "prompt_tokens": int(usage.get("prompt_tokens", 0)),
|
||||
"completion_tokens": int(usage.get("completion_tokens", 0)),
|
||||
"finish_reason": data["choices"][0].get("finish_reason")}
|
||||
usage = data.get("usage")
|
||||
if not isinstance(usage, dict):
|
||||
raise ValueError("response is missing usage")
|
||||
prompt_tokens, completed = usage.get("prompt_tokens"), usage.get("completion_tokens")
|
||||
if type(prompt_tokens) is not int or prompt_tokens <= 0:
|
||||
raise ValueError("response must report a positive integer prompt_tokens count")
|
||||
if type(completed) is not int or completed != max_tokens:
|
||||
raise ValueError(f"response must report exactly {max_tokens} completion tokens, got {completed!r}")
|
||||
choices = data.get("choices", [])
|
||||
if len(choices) != 1 or choices[0].get("finish_reason") != "length":
|
||||
raise ValueError("forced-length QoS response did not finish at its requested length")
|
||||
if not math.isfinite(elapsed) or elapsed <= 0:
|
||||
raise ValueError("request duration is not a positive finite measurement")
|
||||
return {"seconds": elapsed, "prompt_tokens": prompt_tokens,
|
||||
"completion_tokens": completed, "finish_reason": "length"}
|
||||
|
||||
|
||||
def main():
|
||||
@@ -92,12 +98,17 @@ def main():
|
||||
concurrencies = [int(x) for x in args.concurrency.split(",")]
|
||||
if not concurrencies or any(x < 1 for x in concurrencies):
|
||||
p.error("--concurrency must be comma-separated positive integers")
|
||||
if args.requests < 1 or args.repeats < 1 or args.max_tokens < 1:
|
||||
p.error("requests, repeats, and max-tokens must be positive")
|
||||
if (args.requests < 1 or args.repeats < 1 or args.max_tokens < 1 or args.tp < 1 or
|
||||
args.max_model_len < 1 or args.max_num_batched_tokens < 1 or args.gpu_headroom_mib < 0 or
|
||||
not math.isfinite(args.timeout) or args.timeout <= 0):
|
||||
p.error("counts/limits/timeout must be positive and finite; headroom must be nonnegative")
|
||||
for path in (radiance, model):
|
||||
if not path.is_file():
|
||||
p.error(f"not a file: {path}")
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
if (out / "qos.json").exists():
|
||||
p.error("qos.json already exists; choose a fresh --out for this measurement")
|
||||
plugins = plugin_hashes(home)
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
port = sock.getsockname()[1]
|
||||
@@ -119,11 +130,7 @@ def main():
|
||||
"max_num_batched_tokens": args.max_num_batched_tokens,
|
||||
"gpu_headroom_mib": args.gpu_headroom_mib,
|
||||
"requests_per_repeat": args.requests, "repeats": args.repeats,
|
||||
"max_tokens": args.max_tokens, "command": command, "results": {}}
|
||||
kernel_dir = home / "kernels"
|
||||
if kernel_dir.is_dir():
|
||||
receipt["kernel_shared_objects"] = {
|
||||
str(f.relative_to(home)): sha256(f) for f in sorted(kernel_dir.rglob("*.so"))}
|
||||
"max_tokens": args.max_tokens, "command": command, **plugins, "results": {}}
|
||||
if args.source_root:
|
||||
root = args.source_root.resolve()
|
||||
receipt["source"] = {
|
||||
@@ -166,6 +173,10 @@ def main():
|
||||
wall = time.perf_counter() - started
|
||||
latencies = [x["seconds"] for x in samples]
|
||||
generated = sum(x["completion_tokens"] for x in samples)
|
||||
if (len(samples) != args.requests * args.repeats or
|
||||
generated != args.requests * args.repeats * args.max_tokens or
|
||||
not math.isfinite(wall) or wall <= 0):
|
||||
raise ValueError("QoS measurement did not complete the expected work")
|
||||
summary = {"requests": len(samples), "wall_seconds": wall,
|
||||
"latency_seconds": {"p50": quantile(latencies, 0.50),
|
||||
"p95": quantile(latencies, 0.95),
|
||||
@@ -185,6 +196,9 @@ def main():
|
||||
proc.kill()
|
||||
proc.wait()
|
||||
server_log.close()
|
||||
if (plugin_hashes(home) != plugins or sha256(radiance) != receipt["radiance_sha256"] or
|
||||
sha256(model) != receipt["model_sha256"]):
|
||||
raise ValueError("runtime, model or plugin inventory changed during the measurement")
|
||||
report = out / "qos.json"
|
||||
report.write_text(json.dumps(receipt, indent=2) + "\n")
|
||||
print(f"QoS receipt: {report}")
|
||||
|
||||
+37
-38
@@ -13,8 +13,8 @@ Example (run inside an externally managed GPU scope when using libr4d):
|
||||
--candidate keep12=/models/spark-iq8r-keep12.rad
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import struct
|
||||
@@ -22,29 +22,13 @@ import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def sha256(path):
|
||||
h = hashlib.sha256()
|
||||
with Path(path).open("rb") as f:
|
||||
for block in iter(lambda: f.read(8 * 1024 * 1024), b""):
|
||||
h.update(block)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def fnv1a64(path):
|
||||
# Match core/kld.cpp: getline hashes each line without its terminating LF.
|
||||
h = 1469598103934665603
|
||||
with Path(path).open("rb") as f:
|
||||
for line in f:
|
||||
if line.endswith(b"\n"):
|
||||
line = line[:-1]
|
||||
for b in line:
|
||||
h = ((h ^ b) * 1099511628211) & 0xffffffffffffffff
|
||||
return f"{h:016x}"
|
||||
from spark25_validation import (fnv1a64, plugin_hashes, reference_provenance, sha256,
|
||||
validate_reference, validate_report)
|
||||
|
||||
|
||||
def parse_candidate(spec):
|
||||
name, sep, path = spec.partition("=")
|
||||
if not sep or not name or not path:
|
||||
if not sep or not name or not path or Path(name).name != name or name in (".", ".."):
|
||||
raise argparse.ArgumentTypeError("candidate must be NAME=/path/to/model.rad")
|
||||
return name, Path(path).resolve()
|
||||
|
||||
@@ -72,6 +56,9 @@ def main():
|
||||
help="reuse an existing compatible top-128 reference instead of recording it")
|
||||
p.add_argument("--dry-run", action="store_true")
|
||||
args = p.parse_args()
|
||||
if (args.tp < 1 or args.max_model_len < 1 or args.max_num_batched_tokens < 1 or
|
||||
args.gpu_headroom_mib < 0):
|
||||
p.error("TP/model/chunk limits must be positive and headroom nonnegative")
|
||||
|
||||
radiance, home, reference = args.radiance.resolve(), args.home.resolve(), args.reference.resolve()
|
||||
corpus, out = args.corpus.resolve(), args.out.resolve()
|
||||
@@ -96,15 +83,19 @@ def main():
|
||||
str(ref_dir), "--kld-out", str(out / f"{name}-kld.json")]))
|
||||
return 0
|
||||
|
||||
plugins = plugin_hashes(home)
|
||||
reference_inputs = {
|
||||
"reference_model": str(reference), "reference_sha256": sha256(reference),
|
||||
"corpus": str(corpus), "corpus_sha256": sha256(corpus),
|
||||
"corpus_fnv1a64": fnv1a64(corpus), "radiance": str(radiance),
|
||||
"radiance_sha256": sha256(radiance), "plugins": plugins, "arguments": common,
|
||||
}
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
ref_meta_path = ref_dir / "kld.json"
|
||||
if args.reuse_reference:
|
||||
if not ref_meta_path.is_file():
|
||||
p.error(f"--reuse-reference requested but {ref_meta_path} is missing")
|
||||
ref_meta = json.loads(ref_meta_path.read_text())
|
||||
if (ref_meta.get("format") != "radiance-kld-top-1" or ref_meta.get("top") != 128 or
|
||||
ref_meta.get("corpus_fnv1a64") != fnv1a64(corpus)):
|
||||
p.error("existing reference is not the same top-128 reference for this corpus")
|
||||
else:
|
||||
if ref_dir.exists():
|
||||
p.error(f"reference directory already exists: {ref_dir}; choose another --out or use --reuse-reference")
|
||||
@@ -113,10 +104,8 @@ def main():
|
||||
subprocess.run(record, env=env, check=True)
|
||||
ref_meta = json.loads(ref_meta_path.read_text())
|
||||
|
||||
if ref_meta.get("format") != "radiance-kld-top-1" or ref_meta.get("top") != 128:
|
||||
p.error("reference is not radiance-kld-top-1 with top=128")
|
||||
if ref_meta.get("corpus_fnv1a64") != fnv1a64(corpus):
|
||||
p.error("KLD reference corpus hash does not match --corpus")
|
||||
validate_reference(ref_meta, reference, corpus)
|
||||
bound_reference = reference_provenance(ref_dir, reference_inputs, args.reuse_reference)
|
||||
|
||||
run = {
|
||||
"reference_model": str(reference), "reference_sha256": sha256(reference),
|
||||
@@ -130,8 +119,8 @@ def main():
|
||||
"max_num_batched_tokens": args.max_num_batched_tokens,
|
||||
"gpu_headroom_mib": args.gpu_headroom_mib,
|
||||
"speculation": 0, "prefix_cache": False,
|
||||
"reference_manifest": ref_meta,
|
||||
"candidates": {},
|
||||
"reference_manifest": ref_meta, "reference_provenance": bound_reference,
|
||||
**plugins, "candidates": {},
|
||||
}
|
||||
if args.provenance:
|
||||
prov = args.provenance.resolve()
|
||||
@@ -148,20 +137,18 @@ def main():
|
||||
stdout=subprocess.PIPE, text=True).stdout.strip()
|
||||
run["source"] = {"root": str(root), "revision": git("rev-parse", "HEAD"),
|
||||
"status_porcelain": git("status", "--porcelain")}
|
||||
kernel_dir = home / "kernels"
|
||||
if kernel_dir.is_dir():
|
||||
run["kernel_shared_objects"] = {str(f.relative_to(home)): sha256(f)
|
||||
for f in sorted(kernel_dir.rglob("*.so"))}
|
||||
|
||||
expected_rows = ref_meta.get("rows")
|
||||
for name, model in candidates:
|
||||
report = out / f"{name}-kld.json"
|
||||
command = [str(radiance), "--model", str(model), *common, "--kld-ref", str(ref_dir),
|
||||
"--kld-out", str(report)]
|
||||
candidate_sha256 = sha256(model)
|
||||
subprocess.run(command, env=os.environ.copy(), check=True)
|
||||
scored = json.loads(report.read_text())
|
||||
if scored.get("ref_form") != "top-128 + tail" or scored.get("all", {}).get("positions") != expected_rows:
|
||||
p.error(f"{name}: candidate report is not matched to the top-128 reference rows")
|
||||
validate_report(scored, ref_dir, reference, corpus, model, expected_rows)
|
||||
if sha256(model) != candidate_sha256:
|
||||
p.error(f"{name}: candidate changed during scoring")
|
||||
values = scored["all"]["kld"]
|
||||
row_path = Path(str(report) + ".rows")
|
||||
raw = row_path.read_bytes()
|
||||
@@ -169,8 +156,12 @@ def main():
|
||||
p.error(f"{name}: unexpected per-position rows size {len(raw)}")
|
||||
row_values = struct.unpack("<" + "f" * (expected_rows * 4), raw)
|
||||
kl = [row_values[i * 4] for i in range(expected_rows)]
|
||||
run["candidates"][name] = {"model": str(model), "sha256": sha256(model),
|
||||
"report": str(report), "rows": str(row_path),
|
||||
# core/kld.cpp's A/S - log(S) can retain tiny signed roundoff near zero.
|
||||
if not all(math.isfinite(value) for value in kl):
|
||||
p.error(f"{name}: non-finite coarsened KL row")
|
||||
run["candidates"][name] = {"model": str(model), "sha256": candidate_sha256,
|
||||
"report": str(report), "report_sha256": sha256(report),
|
||||
"rows": str(row_path), "rows_sha256": sha256(row_path),
|
||||
"metrics": scored["all"],
|
||||
"positions_over_1_nat": sum(x > 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 <name>-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)
|
||||
@@ -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
|
||||
@@ -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("<ii", 1, 2))
|
||||
(directory / "rows.f32").write_bytes(struct.pack("<fff", 0, 0, 0))
|
||||
(directory / "top.bin").write_bytes(b"".join(struct.pack("<if", i, -float(i + 1))
|
||||
for i in range(128)))
|
||||
else:
|
||||
directory = Path(arg("--kld-ref"))
|
||||
meta = json.loads((directory / "kld.json").read_text())
|
||||
report = {"model": arg("--model"), "reference": meta["model"],
|
||||
"ref_dir": str(directory), "corpus": meta["corpus"],
|
||||
"ref_form": "top-128 + tail", "all": {"positions": 1,
|
||||
"kld": {key: self.score_kl for key in ("mean", "p99", "p99_9", "max")}}}
|
||||
path = Path(arg("--kld-out"))
|
||||
path.write_text(json.dumps(report))
|
||||
Path(str(path) + ".rows").write_bytes(struct.pack("<ffff", self.score_kl, 0, 0, 1))
|
||||
|
||||
def quality_args(self, *extra):
|
||||
return ["spark25_quality.py", "--radiance", str(self.runtime), "--home", str(self.home),
|
||||
"--reference", str(self.reference), "--corpus", str(self.corpus),
|
||||
"--candidate", "full=" + str(self.candidate), "--out", str(self.out), *extra]
|
||||
|
||||
def record_quality(self, *extra):
|
||||
with patch.object(sys, "argv", self.quality_args(*extra)), \
|
||||
patch.object(quality.subprocess, "run", side_effect=self.fake_runtime) as execute, \
|
||||
contextlib.redirect_stdout(io.StringIO()):
|
||||
self.assertEqual(quality.main(), 0)
|
||||
return execute
|
||||
|
||||
def test_plugin_inventory_includes_architecture_and_optional_quantizer(self):
|
||||
inventory = plugin_hashes(self.home)
|
||||
for directory, key in (("kernels", "kernel_shared_objects"),
|
||||
("architectures", "architecture_shared_objects"),
|
||||
("quantizers", "quantizer_shared_objects")):
|
||||
self.assertEqual(inventory[key][directory + "/fixture.so"],
|
||||
sha256(self.home / directory / "fixture.so"))
|
||||
|
||||
def test_missing_architecture_inventory_rejected(self):
|
||||
(self.home / "architectures/fixture.so").unlink()
|
||||
with self.assertRaisesRegex(ValueError, "no shared objects"):
|
||||
plugin_hashes(self.home)
|
||||
|
||||
def test_valid_quality_receipt_and_reuse_are_bound(self):
|
||||
self.record_quality()
|
||||
run = json.loads((self.out / "run.json").read_text())
|
||||
self.assertIn("architectures/fixture.so", run["architecture_shared_objects"])
|
||||
self.assertEqual(run["reference_provenance"]["inputs"]["reference_sha256"], sha256(self.reference))
|
||||
self.assertEqual(run["candidates"]["full"]["report_sha256"], sha256(self.out / "full-kld.json"))
|
||||
execute = self.record_quality("--reuse-reference")
|
||||
self.assertEqual(execute.call_count, 1) # score only, no new reference recording
|
||||
|
||||
def test_signed_kl_roundoff_is_preserved(self):
|
||||
self.score_kl = -1e-10
|
||||
self.record_quality()
|
||||
self.bind_tail()
|
||||
raw = (self.out / "full-kld.json.rows").read_bytes()
|
||||
self.assertLess(struct.unpack_from("<f", raw)[0], 0)
|
||||
|
||||
def test_nonfinite_kl_does_not_emit_success_receipt(self):
|
||||
for value in (float("nan"), float("inf")):
|
||||
with self.subTest(value=value):
|
||||
self.out = self.root / str(value)
|
||||
self.score_kl = value
|
||||
with patch.object(sys, "argv", self.quality_args()), \
|
||||
patch.object(quality.subprocess, "run", side_effect=self.fake_runtime), \
|
||||
contextlib.redirect_stderr(io.StringIO()):
|
||||
with self.assertRaises(SystemExit):
|
||||
quality.main()
|
||||
self.assertFalse((self.out / "run.json").exists())
|
||||
|
||||
def test_reuse_rejects_changed_baseline_bytes_at_same_path(self):
|
||||
self.record_quality()
|
||||
self.reference.write_bytes(b"different BF16 checkpoint at the same path")
|
||||
with patch.object(sys, "argv", self.quality_args("--reuse-reference")), \
|
||||
patch.object(quality.subprocess, "run") as execute:
|
||||
with self.assertRaisesRegex(ValueError, "baseline, runtime, settings or data"):
|
||||
quality.main()
|
||||
execute.assert_not_called()
|
||||
|
||||
def test_reuse_rejects_changed_architecture_before_scoring(self):
|
||||
self.record_quality()
|
||||
(self.home / "architectures/fixture.so").write_bytes(b"stale or rebuilt graph")
|
||||
with patch.object(sys, "argv", self.quality_args("--reuse-reference")), \
|
||||
patch.object(quality.subprocess, "run") as execute:
|
||||
with self.assertRaises(ValueError):
|
||||
quality.main()
|
||||
execute.assert_not_called()
|
||||
|
||||
def test_reuse_rejects_unbound_legacy_reference(self):
|
||||
self.record_quality()
|
||||
(self.out / "bf16-top128-ref/provenance.json").unlink()
|
||||
with patch.object(sys, "argv", self.quality_args("--reuse-reference")):
|
||||
with self.assertRaisesRegex(ValueError, "lacks provenance"):
|
||||
quality.main()
|
||||
|
||||
def test_reuse_rejects_changed_reference_payload(self):
|
||||
self.record_quality()
|
||||
(self.out / "bf16-top128-ref/top.bin").write_bytes(b"changed")
|
||||
with patch.object(sys, "argv", self.quality_args("--reuse-reference")):
|
||||
with self.assertRaises(ValueError):
|
||||
quality.main()
|
||||
|
||||
def test_report_mismatches_rejected_even_with_equal_row_counts(self):
|
||||
self.record_quality()
|
||||
report = json.loads((self.out / "full-kld.json").read_text())
|
||||
for key in ("ref_dir", "reference", "corpus", "model"):
|
||||
with self.subTest(key=key):
|
||||
bad = copy.deepcopy(report)
|
||||
bad[key] = str(self.root / "different-but-same-row-count")
|
||||
with self.assertRaisesRegex(ValueError, "does not match"):
|
||||
validate_report(bad, self.out / "bf16-top128-ref", self.reference,
|
||||
self.corpus, self.candidate, 1)
|
||||
|
||||
def bind_tail(self):
|
||||
return tail.bound_run(self.out / "run.json", self.out / "bf16-top128-ref",
|
||||
self.out / "full-kld.json")
|
||||
|
||||
def test_tail_binds_report_reference_candidate_and_runtime(self):
|
||||
self.record_quality()
|
||||
run, candidate, _, _, common = self.bind_tail()
|
||||
self.assertEqual(candidate["model"], str(self.candidate))
|
||||
self.assertIn(str(self.home), common)
|
||||
self.assertEqual(run["architecture_shared_objects"], plugin_hashes(self.home)["architecture_shared_objects"])
|
||||
|
||||
def test_tail_rejects_report_from_other_candidate(self):
|
||||
self.record_quality()
|
||||
path = self.out / "full-kld.json"
|
||||
report = json.loads(path.read_text())
|
||||
report["model"] = str(self.root / "other.rad")
|
||||
path.write_text(json.dumps(report))
|
||||
with self.assertRaisesRegex(ValueError, "report model"):
|
||||
self.bind_tail()
|
||||
|
||||
def test_tail_rejects_changed_candidate_or_row_scores(self):
|
||||
for changed in ("candidate", "rows"):
|
||||
with self.subTest(changed=changed):
|
||||
# Each subcase starts from one valid run, then invalidates exactly one artifact.
|
||||
if self.out.exists():
|
||||
import shutil
|
||||
shutil.rmtree(self.out)
|
||||
self.record_quality()
|
||||
path = self.candidate if changed == "candidate" else self.out / "full-kld.json.rows"
|
||||
path.write_bytes(path.read_bytes() + b"changed")
|
||||
with self.assertRaisesRegex(ValueError, "artifact hash"):
|
||||
self.bind_tail()
|
||||
|
||||
def test_private_server_uses_bound_candidate_and_rejects_foreign_alias(self):
|
||||
self.record_quality()
|
||||
run, candidate, _, _, common = self.bind_tail()
|
||||
for foreign in (False, True):
|
||||
with self.subTest(foreign=foreign):
|
||||
proc = Mock(pid=123)
|
||||
proc.poll.return_value = None
|
||||
commands = []
|
||||
def start(command, **kwargs):
|
||||
commands.append(command)
|
||||
return proc
|
||||
def get(url, timeout):
|
||||
return {"data": [{"id": "different-server" if foreign else commands[0][-1]}]}
|
||||
with patch.object(tail.subprocess, "Popen", side_effect=start), patch.object(tail, "get", side_effect=get):
|
||||
if foreign:
|
||||
with self.assertRaisesRegex(ValueError, "private server identity"):
|
||||
with tail.candidate_server(run, candidate, common, self.root / "server.log"):
|
||||
self.fail("must not expose an unrelated server")
|
||||
else:
|
||||
with tail.candidate_server(run, candidate, common, self.root / "server.log") as server:
|
||||
command = server["command"]
|
||||
self.assertEqual(command[command.index("--model") + 1], str(self.candidate))
|
||||
self.assertTrue(server["model"].startswith("spark-tail-"))
|
||||
proc.terminate.assert_called_once()
|
||||
|
||||
def response(self, data):
|
||||
return io.BytesIO(json.dumps(data).encode())
|
||||
|
||||
def test_qos_requires_complete_positive_usage(self):
|
||||
valid = {"usage": {"prompt_tokens": 3, "completion_tokens": 2},
|
||||
"choices": [{"finish_reason": "length"}]}
|
||||
with patch.object(qos.urllib.request, "urlopen", return_value=self.response(valid)):
|
||||
measured = qos.request("http://localhost", "spark", "a b", 2, 1)
|
||||
self.assertEqual(measured["completion_tokens"], 2)
|
||||
variants = [{}, {"usage": {}}, {"usage": None}]
|
||||
for missing in ("prompt_tokens", "completion_tokens"):
|
||||
bad = copy.deepcopy(valid)
|
||||
del bad["usage"][missing]
|
||||
variants.append(bad)
|
||||
for field, value in (("prompt_tokens", 0), ("prompt_tokens", "3"),
|
||||
("prompt_tokens", True), ("completion_tokens", 0),
|
||||
("completion_tokens", 1), ("completion_tokens", 3),
|
||||
("completion_tokens", "2"), ("completion_tokens", True)):
|
||||
bad = copy.deepcopy(valid)
|
||||
bad["usage"][field] = value
|
||||
variants.append(bad)
|
||||
bad = copy.deepcopy(valid)
|
||||
bad["choices"][0]["finish_reason"] = "stop"
|
||||
variants.append(bad)
|
||||
for bad in variants:
|
||||
with self.subTest(response=bad), \
|
||||
patch.object(qos.urllib.request, "urlopen", return_value=self.response(bad)):
|
||||
with self.assertRaises(ValueError):
|
||||
qos.request("http://localhost", "spark", "a b", 2, 1)
|
||||
|
||||
def test_complete_qos_records_architecture_and_expected_work(self):
|
||||
output = self.root / "complete-qos"
|
||||
args = ["spark25_qos.py", "--radiance", str(self.runtime), "--home", str(self.home),
|
||||
"--model", str(self.candidate), "--prompts", str(self.corpus), "--out", str(output),
|
||||
"--requests", "1", "--repeats", "1", "--concurrency", "1", "--max-tokens", "2"]
|
||||
proc = Mock()
|
||||
proc.poll.return_value = None
|
||||
response = {"usage": {"prompt_tokens": 3, "completion_tokens": 2},
|
||||
"choices": [{"finish_reason": "length"}]}
|
||||
with patch.object(sys, "argv", args), patch.object(qos.subprocess, "Popen", return_value=proc), \
|
||||
patch.object(qos.urllib.request, "urlopen", side_effect=lambda *a, **k: self.response(response)), \
|
||||
contextlib.redirect_stdout(io.StringIO()):
|
||||
self.assertEqual(qos.main(), 0)
|
||||
receipt = json.loads((output / "qos.json").read_text())
|
||||
self.assertIn("architectures/fixture.so", receipt["architecture_shared_objects"])
|
||||
self.assertEqual(receipt["results"]["1"]["generated_tokens"], 2)
|
||||
proc.terminate.assert_called_once()
|
||||
|
||||
def test_failed_qos_does_not_emit_success_receipt(self):
|
||||
output = self.root / "qos"
|
||||
args = ["spark25_qos.py", "--radiance", str(self.runtime), "--home", str(self.home),
|
||||
"--model", str(self.candidate), "--prompts", str(self.corpus), "--out", str(output),
|
||||
"--requests", "1", "--repeats", "1", "--concurrency", "1", "--max-tokens", "2"]
|
||||
proc = Mock()
|
||||
proc.poll.return_value = None
|
||||
with patch.object(sys, "argv", args), patch.object(qos.subprocess, "Popen", return_value=proc), \
|
||||
patch.object(qos.urllib.request, "urlopen", side_effect=lambda *a, **k: self.response({})):
|
||||
with self.assertRaisesRegex(ValueError, "missing usage"):
|
||||
qos.main()
|
||||
proc.terminate.assert_called_once()
|
||||
self.assertFalse((output / "qos.json").exists())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user