"""OPTIONAL, NOT EXECUTED IN THE PREPARATION ENVIRONMENT. Export a trusted lab checkpoint at fixed batch size 1 and check CPU parity. Install compatible onnx, onnxscript and onnxruntime versions separately; record the versions actually used. The core course does not require them. """ from pathlib import Path import argparse import importlib.util import json import torch from .models import load_model def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("checkpoint", type=Path) parser.add_argument("output", type=Path) args = parser.parse_args() missing = [p for p in ("onnx", "onnxscript", "onnxruntime") if importlib.util.find_spec(p) is None] if missing: parser.error("Missing optional dependencies: " + ", ".join(missing)) import onnx import onnxruntime as ort import onnxscript model = load_model(args.checkpoint) if args.output.exists(): parser.error("Refusing to replace an existing model file.") args.output.parent.mkdir(parents=True, exist_ok=True) generator = torch.Generator().manual_seed(90210) x = torch.randn(1, model.config.inputs, generator=generator) torch.onnx.export(model, (x,), str(args.output), input_names=["features"], output_names=["logits"], opset_version=18, dynamo=True, external_data=False) onnx.checker.check_model(str(args.output)) parity_path = args.output.with_suffix(".parity.json") try: session = ort.InferenceSession(str(args.output), providers=["CPUExecutionProvider"]) worst_error = 0.0 with torch.inference_mode(): for _ in range(32): x = torch.randn(1, model.config.inputs, generator=generator) actual = torch.from_numpy(session.run(["logits"], {"features": x.numpy()})[0]) expected = model(x) torch.testing.assert_close(actual, expected, rtol=1e-4, atol=1e-5) worst_error = max(worst_error, float((actual - expected).abs().max())) except BaseException: # Never leave a rejected graph on disk beside a record that says it passed: # that is the one state this script exists to prevent. Removing the output # also unblocks the corrected re-export, which the exists() guard would # otherwise refuse. session = None args.output.unlink(missing_ok=True) parity_path.unlink(missing_ok=True) raise # A parity failure must not leave a rejected graph on disk next to a stale # record that says the previous export passed. report = {"status": "executed_by_this_script", "tested_inputs": 32, "max_abs_error": worst_error, "fixed_shape": [1, model.config.inputs], "torch": torch.__version__, "onnx": onnx.__version__, "onnxruntime": ort.__version__, "onnxscript": onnxscript.__version__, "scope": "CPU numeric parity, not Android or task quality"} args.output.with_suffix(".parity.json").write_text(json.dumps(report, indent=2)) print(json.dumps(report, indent=2)) if __name__ == "__main__": main()