grintools 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
grintools/onnx.py ADDED
@@ -0,0 +1,186 @@
1
+ """
2
+ grin_onnx.py: torch-free GRIN inference from the exported ONNX model.
3
+
4
+ This is the distributable wrapper. It depends only on numpy + onnxruntime. Retrain
5
+ your pipeline, re-export the .onnx, and this file is unchanged. The graph takes raw
6
+ counts (B,16) and trials (B,4) and returns parameter-space mean/std plus the trained
7
+ construct heads, so there is no featurisation, no link functions, and no sampling to
8
+ reproduce here.
9
+
10
+ from grin_onnx import GrinOnnx
11
+ grin = GrinOnnx("web/assets/models/cm/npe_model.onnx")
12
+ result, constructs = grin(counts_4x4) # trials default to row sums
13
+
14
+ `result` is compatible with grin_io.Criterion (.params/.std/.ci_low/.ci_high/.names).
15
+ `constructs` matches the keys grin_io's probability targets expect.
16
+ """
17
+ import hashlib
18
+ import json
19
+ import os
20
+ from importlib import resources
21
+
22
+ import numpy as np
23
+ import onnxruntime as ort
24
+
25
+ try:
26
+ from grt_model import PARAM_NAMES
27
+ except Exception:
28
+ try:
29
+ from src.grt_model import PARAM_NAMES
30
+ except Exception:
31
+ PARAM_NAMES = ([f"zx_{i}" for i in range(4)] + [f"zy_{i}" for i in range(4)]
32
+ + [f"rho_{i}" for i in range(4)])
33
+
34
+ # argmax(p_corr) index -> correlation-structure label
35
+ _CORR_LABEL = {0: "PI", 1: "RHO1", 2: "free"}
36
+
37
+
38
+ # Per-family posterior scale factors, fitted on held-out simulations by
39
+ # scripts/fit_recalibration.py in the research repository and validated on a further
40
+ # held-out set. Applied ONLY when the caller asks for it: see infer(calibrated=...).
41
+ _RECAL_CACHE = {}
42
+
43
+
44
+ def _recalibration():
45
+ """Load the shipped scale factors, or None if this build has none."""
46
+ if "spec" not in _RECAL_CACHE:
47
+ import json
48
+ try:
49
+ path = resources.files("grintools").joinpath("models", "recalibration.json")
50
+ _RECAL_CACHE["spec"] = json.loads(path.read_text())
51
+ except Exception:
52
+ _RECAL_CACHE["spec"] = None
53
+ return _RECAL_CACHE["spec"]
54
+
55
+
56
+ def _recal_scales(spec, n=12):
57
+ s = np.ones(n)
58
+ if spec:
59
+ s[0:8] = spec["global_scale"]["z"]
60
+ s[8:12] = spec["global_scale"]["rho"]
61
+ return s
62
+
63
+
64
+ class OnnxResult:
65
+ """InferenceResult-compatible posterior from the ONNX marginal-Gaussian head.
66
+
67
+ `calibrated=True` widens the intervals by the per-family factors described above.
68
+ Point estimates are never affected, so model selection and the fitted perceptual
69
+ space are identical either way -- only the stated uncertainty changes.
70
+ """
71
+ def __init__(self, mean, std, model_class, calibrated=False):
72
+ self.params = np.asarray(mean, float)
73
+ self.std_raw = np.asarray(std, float)
74
+ self.calibrated = bool(calibrated)
75
+ self.scale = _recal_scales(_recalibration() if calibrated else None)
76
+ self.std = self.std_raw * self.scale
77
+ self.ci_low = self.params - 1.645 * self.std # 90% marginal, Gaussian
78
+ self.ci_high = self.params + 1.645 * self.std
79
+ self.names = PARAM_NAMES
80
+ self.model_class = model_class
81
+ self.samples = None # ONNX head is analytic
82
+
83
+ def summary(self):
84
+ tag = " [calibrated]" if self.calibrated else ""
85
+ lines = [f"GRIN inference (onnx){tag}", "-" * 46]
86
+ for i, n in enumerate(self.names):
87
+ lines.append(f" {n:7s} = {self.params[i]:+.2f} +/- {self.std[i]:.2f}"
88
+ f" [90% {self.ci_low[i]:+.2f}, {self.ci_high[i]:+.2f}]")
89
+ lines.append("-" * 46)
90
+ lines.append(f" componentwise modal structure : {self.model_class}")
91
+ if not self.calibrated:
92
+ lines.append(" intervals are the network's own; pass calibrated=True for")
93
+ lines.append(" width-corrected intervals (see the package documentation)")
94
+ return "\n".join(lines)
95
+
96
+
97
+ def _class_label(p_corr, p_sep_a, p_sep_b):
98
+ corr = _CORR_LABEL[int(np.argmax(p_corr))]
99
+ parts = [corr]
100
+ parts.append("PS(A)" if p_sep_a >= 0.5 else "!PS(A)")
101
+ parts.append("PS(B)" if p_sep_b >= 0.5 else "!PS(B)")
102
+ return " + ".join(parts)
103
+
104
+
105
+ def _decision(probability, evidence_tol):
106
+ """Direction of evidence: 'for', 'against', or 'undecided'."""
107
+ lower = 0.5 - evidence_tol / 2.0
108
+ if probability < lower:
109
+ return "against"
110
+ if probability > 1.0 - lower:
111
+ return "for"
112
+ return "undecided"
113
+
114
+
115
+ def verify_bundled_model(path):
116
+ """Check a bundled model against the `model_provenance.json` written beside it.
117
+
118
+ Returns the sidecar dict, or None when there is no sidecar -- a user-supplied
119
+ `model_path` is not covered by one and is not our business to police.
120
+
121
+ This exists because of a real failure: between 2026-08-25 and 2026-09-29 the
122
+ packages shipped the PRE-release checkpoint while the web app served v1.0.0,
123
+ with the release-era recalibration factors applied on top. Nothing anywhere
124
+ compared the two, so the only symptom was a worked example in the paper whose
125
+ numbers no user could reproduce. A mismatch is now loud and immediate.
126
+ """
127
+ sidecar_path = os.path.join(os.path.dirname(os.path.abspath(path)),
128
+ "model_provenance.json")
129
+ if not os.path.isfile(sidecar_path):
130
+ return None
131
+ with open(sidecar_path, encoding="utf-8") as fh:
132
+ sidecar = json.load(fh)
133
+ if sidecar.get("model_file") != os.path.basename(path):
134
+ return None # sidecar describes a different file
135
+
136
+ h = hashlib.sha256()
137
+ with open(path, "rb") as fh:
138
+ for chunk in iter(lambda: fh.read(1 << 20), b""):
139
+ h.update(chunk)
140
+ actual = h.hexdigest()
141
+ if actual != sidecar.get("sha256"):
142
+ raise RuntimeError(
143
+ f"bundled GRIN model does not match its provenance record.\n"
144
+ f" file {path}\n"
145
+ f" expected {sidecar.get('sha256')} (version {sidecar.get('version')})\n"
146
+ f" actual {actual}\n"
147
+ "Reinstall grintools, or re-run scripts/export_onnx.py --install.")
148
+ return sidecar
149
+
150
+
151
+ class GrinOnnx:
152
+ def __init__(self, path, verify=True):
153
+ if verify:
154
+ self.provenance = verify_bundled_model(path)
155
+ else:
156
+ self.provenance = None
157
+ self.session = ort.InferenceSession(path, providers=["CPUExecutionProvider"])
158
+ self.inputs = [i.name for i in self.session.get_inputs()]
159
+ self.outputs = [o.name for o in self.session.get_outputs()]
160
+
161
+ def __call__(self, counts, trials=None, evidence_tol=0.5, calibrated=False):
162
+ """counts: (4,4) or length-16 canonical-order counts. Returns (OnnxResult, constructs)."""
163
+ counts = np.asarray(counts, dtype=np.float32).reshape(1, 16)
164
+ if trials is None:
165
+ trials = counts.reshape(1, 4, 4).sum(2)
166
+ trials = np.asarray(trials, dtype=np.float32).reshape(1, 4)
167
+ mean, std, p_corr, p_sep = self.session.run(
168
+ None, {"counts": counts, "trials": trials})
169
+ p_pi = float(p_corr[0, 0]); p_a = float(p_sep[0, 0]); p_b = float(p_sep[0, 1])
170
+ band = 0.5 - evidence_tol / 2.0 # matches model_posterior's flag
171
+ constructs = {
172
+ "p_PI": p_pi, "p_sep_A": p_a, "p_sep_B": p_b,
173
+ "p_corr": [float(x) for x in p_corr[0]], # [PI, RHO1, free]
174
+ "decision_PI": _decision(p_pi, evidence_tol),
175
+ "decision_sep_A": _decision(p_a, evidence_tol),
176
+ "decision_sep_B": _decision(p_b, evidence_tol),
177
+ # Back-compatible decisiveness flags. These do not encode direction;
178
+ # prefer decision_* in reporting code.
179
+ "evidence_PI": bool(abs(p_pi - 0.5) > band),
180
+ "evidence_sep_A": bool(abs(p_a - 0.5) > band),
181
+ "evidence_sep_B": bool(abs(p_b - 0.5) > band),
182
+ }
183
+ result = OnnxResult(mean[0], std[0], _class_label(p_corr[0], p_a, p_b),
184
+ calibrated=calibrated)
185
+ return result, constructs
186
+