File size: 8,353 Bytes
3078a5e d99510b 3078a5e d99510b 3078a5e d99510b 3078a5e d99510b 3078a5e d99510b 3078a5e d99510b 3078a5e d99510b 3078a5e d99510b 3078a5e d99510b 3078a5e d99510b 3078a5e d99510b 3078a5e d99510b 3078a5e d99510b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 | """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())
|