Archived
Stage Spark score outputs and protect inputs from overwrite
This commit is contained in:
1 parent
a4403a1a90
commit
acd256ba25
3 files changed
+91
-36
No files matched your search
@@ -157,7 +157,8 @@ def main():
|
|||||||
}
|
}
|
||||||
env = os.environ.copy()
|
env = os.environ.copy()
|
||||||
env.pop("HF_TOKEN", None)
|
env.pop("HF_TOKEN", None)
|
||||||
server_log = (out / "server.log").open("w+")
|
# Exclusive create refuses existing files and symlinks, including symlinks to inputs.
|
||||||
|
server_log = (out / "server.log").open("x+")
|
||||||
proc = subprocess.Popen(command, env=env, stdout=server_log, stderr=subprocess.STDOUT)
|
proc = subprocess.Popen(command, env=env, stdout=server_log, stderr=subprocess.STDOUT)
|
||||||
url = f"http://127.0.0.1:{port}"
|
url = f"http://127.0.0.1:{port}"
|
||||||
try:
|
try:
|
||||||
@@ -217,7 +218,8 @@ def main():
|
|||||||
sha256(model) != receipt["model_sha256"] or sha256(prompt_path) != prompt_hash):
|
sha256(model) != receipt["model_sha256"] or sha256(prompt_path) != prompt_hash):
|
||||||
raise ValueError("runtime, model, prompt file or plugin inventory changed during the measurement")
|
raise ValueError("runtime, model, prompt file or plugin inventory changed during the measurement")
|
||||||
report = out / "qos.json"
|
report = out / "qos.json"
|
||||||
report.write_text(json.dumps(receipt, indent=2) + "\n")
|
with report.open("x") as stream:
|
||||||
|
stream.write(json.dumps(receipt, indent=2) + "\n")
|
||||||
print(f"QoS receipt: {report}")
|
print(f"QoS receipt: {report}")
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|||||||
+54
-34
@@ -20,6 +20,7 @@ from pathlib import Path
|
|||||||
import struct
|
import struct
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
|
||||||
from spark25_validation import (fnv1a64, plugin_hashes, reference_provenance, sha256,
|
from spark25_validation import (fnv1a64, plugin_hashes, reference_provenance, sha256,
|
||||||
@@ -83,6 +84,21 @@ def main():
|
|||||||
str(ref_dir), "--kld-out", str(out / f"{name}-kld.json")]))
|
str(ref_dir), "--kld-out", str(out / f"{name}-kld.json")]))
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
inputs = [radiance, reference, corpus, *(model for _, model in candidates)]
|
||||||
|
inputs += [path.resolve() for path in (args.provenance, args.calibration_manifest) if path]
|
||||||
|
destinations = [out / "run.json"]
|
||||||
|
for name, _ in candidates:
|
||||||
|
report = out / f"{name}-kld.json"
|
||||||
|
destinations.extend((report, Path(str(report) + ".rows")))
|
||||||
|
if out == home or home in out.parents:
|
||||||
|
p.error("output directory must not be inside the plugin home")
|
||||||
|
for dest in destinations:
|
||||||
|
if dest.is_symlink() or dest.resolve() in inputs:
|
||||||
|
p.error(f"output path collides with an input or symlink: {dest}")
|
||||||
|
if ref_dir.is_symlink():
|
||||||
|
p.error("reference output directory must not be a symlink")
|
||||||
|
if any(path == ref_dir or ref_dir in path.parents for path in inputs):
|
||||||
|
p.error("an input is inside the reference output directory")
|
||||||
out.mkdir(parents=True, exist_ok=True)
|
out.mkdir(parents=True, exist_ok=True)
|
||||||
# A failed retry must not leave a previous run's receipt looking like its result.
|
# A failed retry must not leave a previous run's receipt looking like its result.
|
||||||
(out / "run.json").unlink(missing_ok=True)
|
(out / "run.json").unlink(missing_ok=True)
|
||||||
@@ -155,41 +171,45 @@ def main():
|
|||||||
"status_porcelain": git("status", "--porcelain")}
|
"status_porcelain": git("status", "--porcelain")}
|
||||||
|
|
||||||
expected_rows = ref_meta.get("rows")
|
expected_rows = ref_meta.get("rows")
|
||||||
for name, model in candidates:
|
with tempfile.TemporaryDirectory(prefix=".spark25-score-", dir=out) as staging:
|
||||||
report = out / f"{name}-kld.json"
|
staged_outputs = []
|
||||||
command = [str(radiance), "--model", str(model), *common, "--kld-ref", str(ref_dir),
|
for name, model in candidates:
|
||||||
"--kld-out", str(report)]
|
report = out / f"{name}-kld.json"
|
||||||
candidate_sha256 = sha256(model)
|
row_path = Path(str(report) + ".rows")
|
||||||
row_path = Path(str(report) + ".rows")
|
staged_report = Path(staging) / report.name
|
||||||
# A success without fresh output must never reuse an earlier score on retry.
|
staged_rows = Path(str(staged_report) + ".rows")
|
||||||
report.unlink(missing_ok=True)
|
command = [str(radiance), "--model", str(model), *common, "--kld-ref", str(ref_dir),
|
||||||
row_path.unlink(missing_ok=True)
|
"--kld-out", str(staged_report)]
|
||||||
subprocess.run(command, env=os.environ.copy(), check=True)
|
candidate_sha256 = sha256(model)
|
||||||
scored = json.loads(report.read_text())
|
subprocess.run(command, env=os.environ.copy(), check=True)
|
||||||
validate_report(scored, ref_dir, reference, corpus, model, expected_rows)
|
scored = json.loads(staged_report.read_text())
|
||||||
if sha256(model) != candidate_sha256:
|
validate_report(scored, ref_dir, reference, corpus, model, expected_rows)
|
||||||
p.error(f"{name}: candidate changed during scoring")
|
if sha256(model) != candidate_sha256:
|
||||||
values = scored["all"]["kld"]
|
p.error(f"{name}: candidate changed during scoring")
|
||||||
raw = row_path.read_bytes()
|
values = scored["all"]["kld"]
|
||||||
if len(raw) != expected_rows * 16:
|
raw = staged_rows.read_bytes()
|
||||||
p.error(f"{name}: unexpected per-position rows size {len(raw)}")
|
if len(raw) != expected_rows * 16:
|
||||||
row_values = struct.unpack("<" + "f" * (expected_rows * 4), raw)
|
p.error(f"{name}: unexpected per-position rows size {len(raw)}")
|
||||||
kl = [row_values[i * 4] for i in range(expected_rows)]
|
row_values = struct.unpack("<" + "f" * (expected_rows * 4), raw)
|
||||||
# core/kld.cpp's A/S - log(S) can retain tiny signed roundoff near zero.
|
kl = [row_values[i * 4] for i in range(expected_rows)]
|
||||||
if not all(math.isfinite(value) for value in kl):
|
# core/kld.cpp's A/S - log(S) can retain tiny signed roundoff near zero.
|
||||||
p.error(f"{name}: non-finite coarsened KL row")
|
if not all(math.isfinite(value) for value in kl):
|
||||||
run["candidates"][name] = {"model": str(model), "sha256": candidate_sha256,
|
p.error(f"{name}: non-finite coarsened KL row")
|
||||||
"report": str(report), "report_sha256": sha256(report),
|
run["candidates"][name] = {"model": str(model), "sha256": candidate_sha256,
|
||||||
"rows": str(row_path), "rows_sha256": sha256(row_path),
|
"report": str(report), "report_sha256": sha256(staged_report),
|
||||||
"metrics": scored["all"],
|
"rows": str(row_path), "rows_sha256": sha256(staged_rows),
|
||||||
"positions_over_1_nat": sum(x > 1.0 for x in kl)}
|
"metrics": scored["all"],
|
||||||
print(f"{name}: {expected_rows} positions; ref_form={scored['ref_form']}; "
|
"positions_over_1_nat": sum(x > 1.0 for x in kl)}
|
||||||
f"mean={values['mean']:.6g}, p99={values['p99']:.6g}, "
|
staged_outputs.extend(((staged_report, report), (staged_rows, row_path)))
|
||||||
f"p99.9={values['p99_9']:.6g}, max={values['max']:.6g}, "
|
print(f"{name}: {expected_rows} positions; ref_form={scored['ref_form']}; "
|
||||||
f">1 nat={run['candidates'][name]['positions_over_1_nat']}")
|
f"mean={values['mean']:.6g}, p99={values['p99']:.6g}, "
|
||||||
|
f"p99.9={values['p99_9']:.6g}, max={values['max']:.6g}, "
|
||||||
|
f">1 nat={run['candidates'][name]['positions_over_1_nat']}")
|
||||||
|
|
||||||
verify_inputs()
|
verify_inputs()
|
||||||
reference_provenance(ref_dir, reference_inputs, reuse=True)
|
reference_provenance(ref_dir, reference_inputs, reuse=True)
|
||||||
|
for source, destination in staged_outputs:
|
||||||
|
os.replace(source, destination)
|
||||||
(out / "run.json").write_text(json.dumps(run, indent=2) + "\n")
|
(out / "run.json").write_text(json.dumps(run, indent=2) + "\n")
|
||||||
print(f"Run receipt: {out / 'run.json'}")
|
print(f"Run receipt: {out / 'run.json'}")
|
||||||
print("Per-position rows are available as <name>-kld.json.rows; replay severe positions with "
|
print("Per-position rows are available as <name>-kld.json.rows; replay severe positions with "
|
||||||
|
|||||||
@@ -340,6 +340,39 @@ class MeasurementTests(unittest.TestCase):
|
|||||||
with self.assertRaises(FileNotFoundError):
|
with self.assertRaises(FileNotFoundError):
|
||||||
quality.main()
|
quality.main()
|
||||||
self.assertFalse((self.out / 'run.json').exists())
|
self.assertFalse((self.out / 'run.json').exists())
|
||||||
|
self.assertEqual((self.out / 'full-kld.json').read_bytes(), self.saved_outputs[0])
|
||||||
|
self.assertEqual((self.out / 'full-kld.json.rows').read_bytes(), self.saved_outputs[1])
|
||||||
|
|
||||||
|
def test_quality_rejects_output_collisions_before_deleting_inputs(self):
|
||||||
|
for name in ('full-kld.json', 'full-kld.json.rows', 'run.json'):
|
||||||
|
with self.subTest(name=name):
|
||||||
|
self.out = self.root / ('collision-' + name)
|
||||||
|
self.out.mkdir()
|
||||||
|
colliding = self.out / name
|
||||||
|
colliding.write_bytes(b'irreplaceable input')
|
||||||
|
self.candidate = colliding
|
||||||
|
with patch.object(sys, 'argv', self.quality_args()), \
|
||||||
|
patch.object(quality.subprocess, 'run') as execute, \
|
||||||
|
contextlib.redirect_stderr(io.StringIO()):
|
||||||
|
with self.assertRaises(SystemExit):
|
||||||
|
quality.main()
|
||||||
|
self.assertEqual(colliding.read_bytes(), b'irreplaceable input')
|
||||||
|
execute.assert_not_called()
|
||||||
|
|
||||||
|
def test_qos_log_symlink_cannot_truncate_model(self):
|
||||||
|
output = self.root / 'symlink-qos'
|
||||||
|
output.mkdir()
|
||||||
|
(output / 'server.log').symlink_to(self.candidate)
|
||||||
|
before = self.candidate.read_bytes()
|
||||||
|
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', '--concurrency', '1']
|
||||||
|
with patch.object(sys, 'argv', args), patch.object(qos.subprocess, 'Popen') as start:
|
||||||
|
with self.assertRaises(FileExistsError):
|
||||||
|
qos.main()
|
||||||
|
self.assertEqual(self.candidate.read_bytes(), before)
|
||||||
|
self.assertFalse((output / 'qos.json').exists())
|
||||||
|
start.assert_not_called()
|
||||||
|
|
||||||
def test_qos_rejects_fewer_requests_than_concurrency(self):
|
def test_qos_rejects_fewer_requests_than_concurrency(self):
|
||||||
args = ['spark25_qos.py', '--radiance', str(self.runtime), '--home', str(self.home),
|
args = ['spark25_qos.py', '--radiance', str(self.runtime), '--home', str(self.home),
|
||||||
|
|||||||
Reference in new issue
Block a user