tiny-hash-intent / verify_portable.py
WideChaos's picture
Publish Tiny Hash Intent with model and experiment records
a2bd61d verified
Raw History Blame Contribute Delete
2.35 kB
"""Compare independently executed Node portable inference with CPU representation."""
import json, subprocess
from pathlib import Path
import numpy as np
from model import decode_portable, features, logits_for, probabilities
r = Path(__file__).parent
m = json.loads((r / "run-001/model-int8.json").read_text())
p = decode_portable(m)
cases = [
"Where is my card? It has not arrived.",
"How do I change my PIN?",
"My cash withdrawal is pending.",
"I want a refund for a card payment.",
"Write a poem about the moon.",
"CAFÉ Cafe\u0301",
" hello\u0085world\u001c",
"\ufeffBOM kept",
"中文😀",
"A\u2028B",
"<script>alert(1)</script>",
"x" * 2048,
"",
" ",
"x" * 2049,
]
rows = json.loads(
subprocess.run(
["node", "predict_driver.mjs"],
input=json.dumps(cases),
text=True,
capture_output=True,
check=True,
cwd=r,
).stdout
)
maximum = 0.0
valid = 0
for text, result in zip(cases, rows):
try:
ids, values = features(text)
except ValueError:
assert "error" in result
continue
assert result["features"]["ids"] == ids.tolist()
np.testing.assert_allclose(
result["features"]["values"], values, rtol=1e-14, atol=1e-14
)
logits = logits_for([(ids, values)], p)[0]
for key, T in [("raw", 1), ("calibrated", m["temperature"])]:
actual = result[key]
np.testing.assert_allclose(actual["logits"], logits, rtol=1e-9, atol=1e-9)
prob = probabilities(logits, T)
np.testing.assert_allclose(actual["probabilities"], prob, rtol=1e-9, atol=1e-9)
maximum = max(
maximum, float(np.max(np.abs(np.array(actual["probabilities"]) - prob)))
)
assert actual["predicted_label_id"] == int(np.argmax(logits))
valid += 1
(r / "portable-reference-results.json").write_text(
json.dumps(
{
"status": "PASS",
"total_vectors": len(cases),
"valid_vectors": valid,
"rejected_vectors": len(cases) - valid,
"max_probability_delta": maximum,
"scope": "conformance vectors, not language/OOD performance evidence",
},
indent=2,
)
+ "\n"
)
print(
"PortablePASS", valid, "valid,", len(cases) - valid, "rejected,maxPdelta", maximum
)