"""Evaluate the validation-selected exporter with locked model predictions.""" import json from pathlib import Path from shutil import copy2 import numpy as np from transformers import AutoTokenizer import train from repair_export import logits def main(): root = Path(__file__).resolve().parent stage, work = root / "stage", root / "work" repair = work / "export-repair" selection = json.loads((repair / "selection.json").read_text()) selected = selection["selected"] if not selected or not selected["eligible"]: raise RuntimeError("No validation-qualified export; leave the candidate withheld") if selection["repair_plan_sha256"] != train.fingerprint(root / "EXPORT_REPAIR.md"): raise RuntimeError("Export repair plan changed after validation selection") source = repair / f"{selected['name']}.onnx" if train.fingerprint(source) != selected["sha256"]: raise RuntimeError("The validation-selected graph changed") evaluation = json.loads((repair / "gather-default-EVALUATION.json").read_text()) predictions = [json.loads(line) for line in (repair / "gather-default-test_predictions.jsonl").read_text().splitlines()] tokenizer = AutoTokenizer.from_pretrained(work / "selected-native", local_files_only=True) test = train.rows("test") if train.fingerprint(train.BENCHMARK / "test.jsonl") != evaluation["data_lock"]["test"]["sha256"]: raise RuntimeError("Test data changed") assert [row["id"] for row in test] == [row["id"] for row in predictions] values = logits(test, tokenizer, source, batch=1) labels = values.argmax(1) y = train.labels(test) native = np.array([row["candidate_label"] for row in predictions]) calibration = json.loads((stage / "calibration.json").read_text()) probability = train.probability(values, calibration["temperature"]) metrics = train.scores(y, labels, probability) keep = np.maximum(probability, 1 - probability) >= calibration["threshold"] metrics["resolved_coverage"] = float(keep.mean()) metrics["resolved_macro_f1"] = train.scores(y[keep], labels[keep])["macro_f1"] if keep.any() else None agreement = float((labels == native).mean()) evaluation["quantized"] = metrics evaluation["native_quantized_agreement"] = agreement evaluation["quantized_bytes"] = source.stat().st_size evaluation["quantized_batch_size"] = 1 evaluation["quantized_macro_f1_gain"] = metrics["macro_f1"] - evaluation["controls"][evaluation["strongest_control"]]["macro_f1"] control = np.array([row["controls"][evaluation["strongest_control"]] for row in predictions]) evaluation["quantized_bootstrap"] = train.bootstrap(y, labels, control, [row["group_id"] for row in test]) evaluation["export_repair"] = {"plan_sha256": selection["repair_plan_sha256"], "selected_settings": selected, "selection_used_test": False, "timing": "Export engineering followed initial held-out native/export measurement; learned weights and calibration stayed locked."} evaluation["benchmark_release"] = {"id": "Giuliocc/doxa-wording-benchmark", "revision": "bea9a3f2d53b03069b0d814094ea860d75f1c322"} gate = evaluation["release_gate"] gate["quantized"] = agreement >= .98 and abs(metrics["macro_f1"] - evaluation["candidate"]["macro_f1"]) <= .01 gate["size"] = source.stat().st_size < 40_000_000 gate["passed"] = gate["native"] and gate["quantized"] and gate["size"] for i, row in enumerate(predictions): row["quantized_label"] = int(labels[i]) row["quantized_model_score"] = float(probability[i]) row["quantized_resolved"] = bool(keep[i]) copy2(source, stage / "onnx/model_quantized.onnx") manifest = json.loads((stage / "runtime_manifest.json").read_text()) manifest["files"]["weights"].update({"sha256": train.fingerprint(source), "bytes": source.stat().st_size}) train.write_json(stage / "runtime_manifest.json", manifest) train.write_json(stage / "EVALUATION.json", evaluation) train.write_json(work / "results.json", evaluation) (stage / "test_predictions.jsonl").write_text("".join(json.dumps(row) + "\n" for row in predictions)) attempts = [] for name, path, graph in (("matrix_only_default", work / "initial_export_results.json", work / "initial_matrix_quantized.onnx"), ("matrix_gather_default", repair / "gather-default-EVALUATION.json", repair / "gather-default.onnx")): receipt = json.loads(path.read_text()) attempts.append({"name": name, "quantized": receipt["quantized"], "native_quantized_agreement": receipt["native_quantized_agreement"], "bytes": receipt["quantized_bytes"], "sha256": train.fingerprint(graph), "release_gate": receipt["release_gate"]}) train.write_json(stage / "EXPORT_ATTEMPTS.json", {"failed_initial_exports": attempts, "final_selected_representation": selected["name"], "training_or_checkpoint_changed": False}) copy2(repair / "selection.json", stage / "EXPORT_VALIDATION.json") eligible = [(row, prediction) for row, prediction in zip(test, predictions) if prediction["within_deployment_limit"]] fixtures = [{"id": row["id"], "text": row["text"], "expected_label": prediction["quantized_label"]} for row, prediction in eligible[:128]] fixtures.append({"id": "authored_long_input_control", "text": "LOCAL-WORDING-PRIVATE " + "context " * 400, "expected_label": None}) train.write_json(work / "browser-fixtures.json", fixtures) print(json.dumps({"quantized": metrics, "native_quantized_agreement": agreement, "bytes": source.stat().st_size, "release_gate": gate, "quantized_gain": evaluation["quantized_macro_f1_gain"], "quantized_bootstrap": evaluation["quantized_bootstrap"]}, indent=2)) if __name__ == "__main__": main()