windtunnel-response-cross-wave / predict_cross_wave.py
Giuliocc's picture
Add verified offline batch replay and result receipts
d99510b verified
Raw History Blame Contribute Delete
8.35 kB
"""Replay a published Wind Tunnel cross-wave estimate with Python 3.10+."""
import argparse
import hashlib
import json
import math
from pathlib import Path
import re
import sys
METHOD = "ces_cross_wave_research_v1"
HISTORICAL = "2022-historical"
CALIBRATED = "2024-development-calibrated"
RECEIPT_VERSION = "windtunnel-cross-wave-result-v1"
SHA256 = re.compile(r"[0-9a-f]{64}")
IDENTIFIER = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")
REQUEST_FIELDS = {"request_id", "question_id", "instrument_hash", "cell_id", "mode"}
class UnsupportedRequest(ValueError):
def __init__(self, code, message):
super().__init__(message)
self.code = code
def predict(model, question, instrument_hash, cell, calibrated=False):
if model["method"] != METHOD:
raise ValueError("This runner requires a CES cross-wave v1 model.")
item = next((item for item in model["items"] if item["question_id"] == question), None)
if item is None:
raise UnsupportedRequest("unsupported_question", "Use a supported question and its exact 2024 instrument hash.")
if instrument_hash != item["instrument_hash"]:
raise UnsupportedRequest("instrument_mismatch", "Use a supported question and its exact 2024 instrument hash.")
if cell not in item["supported_cells"]:
raise UnsupportedRequest("unsupported_population_cell", "This question does not support the selected population cell.")
features = model["cell_features"][cell]
offsets = item["intercept_offsets_from_target_dev"] if calibrated else [0.0] * len(item["option_ids"])
logits = [
intercept + offset + math.fsum(weight * feature for weight, feature in zip(weights, features, strict=True))
for weights, intercept, offset in zip(item["coefficients"], item["intercepts"], offsets, strict=True)
]
largest = max(logits)
exponentials = [math.exp(logit - largest) for logit in logits]
total = math.fsum(exponentials)
probabilities = {option: value / total for option, value in zip(item["option_ids"], exponentials, strict=True)}
return {
"benchmark_id": model["benchmark_id"],
"question_id": question,
"instrument_hash": instrument_hash,
"cell_id": cell,
"mode": CALIBRATED if calibrated else HISTORICAL,
"probabilities": probabilities,
}
def load_model(path, expected_sha256):
if expected_sha256 is not None and not SHA256.fullmatch(expected_sha256):
raise ValueError("--model-sha256 requires a lowercase, 64-character SHA-256.")
content = path.read_bytes()
digest = hashlib.sha256(content).hexdigest()
if expected_sha256 is not None and digest != expected_sha256:
raise ValueError(f"Model SHA-256 mismatch. Expected {expected_sha256}; got {digest}.")
model = json.loads(content)
if model["method"] != METHOD:
raise ValueError("This runner requires a CES cross-wave v1 model.")
return model, digest
def identifier(value):
return isinstance(value, str) and IDENTIFIER.fullmatch(value) is not None
def unique_object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError("Duplicate JSON key")
result[key] = value
return result
def reject_constant(_):
raise ValueError("JSON numbers must be finite")
def valid_request(row):
return (
row.keys() == REQUEST_FIELDS
and identifier(row["question_id"])
and identifier(row["cell_id"])
and isinstance(row["instrument_hash"], str)
and SHA256.fullmatch(row["instrument_hash"]) is not None
and row["mode"] in (HISTORICAL, CALIBRATED)
)
def batch_receipts(model, model_digest, lines):
provenance = {
"schema_version": RECEIPT_VERSION,
"benchmark_id": model["benchmark_id"],
"method_id": model["method"],
"model_artifact_sha256": model_digest,
"target_frozen_split_sha256": model["target_frozen_split_sha256"],
"validation_track": "retrospective_cross_wave",
"evidence_scope": "Exact historical CES instrument and supported age-by-education cell.",
}
seen = set()
for number, line in enumerate(lines, 1):
if not line.strip():
continue
receipt = {**provenance, "line_number": number, "request_id": None, "prediction": None}
try:
row = json.loads(line.decode("utf-8"), object_pairs_hook=unique_object, parse_constant=reject_constant)
except (ValueError, RecursionError):
yield {**receipt, "status": "error", "reason": {
"code": "invalid_json", "message": "Each nonblank line must contain one valid UTF-8 JSON value.",
}}
continue
request_id = row.get("request_id") if isinstance(row, dict) else None
if not identifier(request_id):
yield {**receipt, "status": "error", "reason": {
"code": "invalid_request", "message": "Provide a valid request_id using the documented identifier syntax.",
}}
continue
receipt["request_id"] = request_id
if request_id in seen:
yield {**receipt, "status": "error", "reason": {
"code": "duplicate_request_id", "message": "Request IDs must be unique within a batch.",
}}
continue
seen.add(request_id)
if not valid_request(row):
yield {**receipt, "status": "error", "reason": {
"code": "invalid_request",
"message": "Use the documented fields, identifier syntax, lowercase SHA-256 and replay mode.",
}}
continue
try:
prediction = predict(model, row["question_id"], row["instrument_hash"], row["cell_id"],
row["mode"] == CALIBRATED)
except UnsupportedRequest as error:
yield {**receipt, "status": "abstained", "reason": {"code": error.code, "message": str(error)}}
else:
yield {**receipt, "status": "ok", "prediction": prediction, "reason": None}
def write_batch(model, model_digest, lines):
success = True
for receipt in batch_receipts(model, model_digest, lines):
print(json.dumps(receipt, allow_nan=False, separators=(",", ":")))
success = success and receipt["status"] == "ok"
return 0 if success else 1
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("question", nargs="?", help="The 2024 question ID.")
parser.add_argument("instrument_hash", nargs="?", help="Exact 2024 instrument SHA-256.")
parser.add_argument("cell", nargs="?", help="A supported age-by-education cell ID.")
parser.add_argument("--model", type=Path, default=Path(__file__).with_name("research-model.json"))
parser.add_argument("--model-sha256", help="Expected SHA-256 of the exact model JSON bytes. Required for batches.")
parser.add_argument("--batch", metavar="FILE", help="Replay a JSONL file or '-' for standard input.")
parser.add_argument("--calibrated", action="store_true", help="Apply the offsets fitted from separate 2024 development labels.")
args = parser.parse_args()
positionals = (args.question, args.instrument_hash, args.cell)
if args.batch is not None:
if any(value is not None for value in positionals) or args.calibrated:
parser.error("--batch replaces positional arguments and --calibrated. Select mode per request.")
if args.model_sha256 is None:
parser.error("--batch requires --model-sha256 from the pinned release manifest.")
elif any(value is None for value in positionals):
parser.error("Provide question, instrument_hash and cell, or use --batch FILE.")
try:
model, digest = load_model(args.model, args.model_sha256)
if args.batch == "-":
return write_batch(model, digest, sys.stdin.buffer)
if args.batch is not None:
with Path(args.batch).open("rb") as lines:
return write_batch(model, digest, lines)
result = predict(model, *positionals, args.calibrated)
print(json.dumps(result, indent=2, allow_nan=False))
except (KeyError, TypeError, ValueError, OSError) as error:
parser.error(str(error))
if __name__ == "__main__":
sys.exit(main())