Archer Hume commited on
Commit
105f9ef
·
1 Parent(s): 340f8e3

Solomon v1.1

Browse files

Adapter, trained readout heads, readout calibration and the serving layer for the
Solomon decision model. The base model is referenced by pinned revision and is not
redistributed; see NOTICE, MODIFICATIONS.md and MANIFEST.json.

.gitattributes CHANGED
@@ -1,35 +1,5 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
  *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
  *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
  *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
 
2
  *.bin filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
3
  *.npz filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
4
  *.pt filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
5
  *.tar filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Doccy Pty Ltd
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
MANIFEST.json ADDED
@@ -0,0 +1,766 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "adapter_sha256": "2addaf841ecc58829ad73081603b8d3e52743c53c6d558a17a1dd30e9bd2dbca",
3
+ "approved": true,
4
+ "base_weights_referenced_not_redistributed": [
5
+ {
6
+ "copyright": "2026 Alibaba Cloud",
7
+ "license": "Apache-2.0",
8
+ "purpose": "the operator downloads these themselves; this repository ships only an adapter",
9
+ "repo": "Qwen/Qwen3.8-27B",
10
+ "revision": "1d4bf0f2ff6012fd82039f2fa52739d0dd7c60c0"
11
+ }
12
+ ],
13
+ "blockers": [],
14
+ "calibration_file_sha256": "d6925a0168b2577d0e4d517cd25dd5ceb0b7cc8eee91b70aefd3a3aa9dcb64ce",
15
+ "calibration_payload_sha256": "6506e2394bda5f8e7c7b9742f70a5b8782efad53d5451d5d836ba3463cece24b",
16
+ "contract": "solomon-v1",
17
+ "descriptor": {
18
+ "path": "release/solomon-release.json",
19
+ "sha256": "c6d282c70959057f708664fadcb4e9964be5840ef56566803a140d98bff0bb1b"
20
+ },
21
+ "excluded_categories": [
22
+ "panels and document corpora (data/**, **/authoring/**, **/*.jsonl)",
23
+ "datasets and training inputs of every kind",
24
+ "caches, states, rendered images, score archives, annotation outputs and logs",
25
+ "test files, evaluation-panel builders and qualification machinery",
26
+ "acceptance fixture documents and any padded development document",
27
+ "base model weights (referenced by pinned revision, never redistributed)",
28
+ "GPU launch scripts, ops/ tooling, internal plans and internal cards"
29
+ ],
30
+ "files": [
31
+ {
32
+ "destination": ".gitattributes",
33
+ "generated_by": "huggingface-cli / already committed in the clone",
34
+ "kind": "git_lfs_config",
35
+ "note": "tracks *.safetensors, *.bin, *.npz, *.pt, *.tar through git-lfs; the adapter (.safetensors) and the heads (.npz) are both covered, so no new LFS pattern is needed",
36
+ "staged_bytes": 217,
37
+ "staged_sha256": "8baff4be52225e26dd13dffb05fed3d0db821911c36d7ffd6f6d00d02ca421c7"
38
+ },
39
+ {
40
+ "destination": "README.md",
41
+ "generated_by": "ops/solomon_package.py (authored for an external audience; every figure read from a measured artifact at generation time)",
42
+ "kind": "model_card",
43
+ "staged_bytes": 36680,
44
+ "staged_sha256": "6f6f80853f431781b8a8e232a90651220b06b41d8e21dd4d235fdd07ddf9e5c8"
45
+ },
46
+ {
47
+ "destination": "LICENSE",
48
+ "generated_by": "ops/solomon_package.py (Apache-2.0 body from the archived upstream text, our copyright in the appendix)",
49
+ "kind": "project_license",
50
+ "staged_bytes": 11344,
51
+ "staged_sha256": "a61385b8bc4e786195136404b4975fede3c0bca526877f526482e9af93d47457"
52
+ },
53
+ {
54
+ "destination": "NOTICE",
55
+ "generated_by": "ops/solomon_package.py",
56
+ "kind": "attribution_notice",
57
+ "staged_bytes": 4818,
58
+ "staged_sha256": "3439e4bf6508278868145d88aa8cf38deb461f3552243653bd72c43adada165e"
59
+ },
60
+ {
61
+ "destination": "MODIFICATIONS.md",
62
+ "generated_by": "ops/solomon_package.py",
63
+ "kind": "change_notice_apache_4b",
64
+ "staged_bytes": 6423,
65
+ "staged_sha256": "69cba71a966419bc7c53ac516ed894114535a5c0122e173d6e5cd0a293b85db5"
66
+ },
67
+ {
68
+ "destination": "requirements.lock",
69
+ "generated_by": "ops/solomon_package.py",
70
+ "kind": "dependency_pins",
71
+ "staged_bytes": 3943,
72
+ "staged_sha256": "56144aef9d15db53f7b33fd1c80e7a8d078b70800fa24d3ecc72d86e14cc2898"
73
+ },
74
+ {
75
+ "destination": "MANIFEST.json",
76
+ "generated_by": "ops/solomon_package.py",
77
+ "kind": "manifest"
78
+ },
79
+ {
80
+ "destination": "licenses/Qwen-Apache-2.0.txt",
81
+ "expected_bytes": 11544,
82
+ "expected_sha256": "bbedc3fda3305820b977265f01b8619d87570a6739de3a5582c3464840f1e57a",
83
+ "kind": "upstream_model_license",
84
+ "staged_bytes": 11544,
85
+ "staged_sha256": "bbedc3fda3305820b977265f01b8619d87570a6739de3a5582c3464840f1e57a"
86
+ },
87
+ {
88
+ "destination": "adapter/adapter.safetensors",
89
+ "expected_bytes": 870363376,
90
+ "expected_sha256": "2addaf841ecc58829ad73081603b8d3e52743c53c6d558a17a1dd30e9bd2dbca",
91
+ "git_lfs": true,
92
+ "kind": "lora_adapter",
93
+ "staged_bytes": 870363376,
94
+ "staged_sha256": "2addaf841ecc58829ad73081603b8d3e52743c53c6d558a17a1dd30e9bd2dbca"
95
+ },
96
+ {
97
+ "destination": "adapter/heads.npz",
98
+ "expected_bytes": 2053938,
99
+ "expected_sha256": "126a9b5487dca937a768a4f228f2d2e7d513900d8ad0e99c4137fbaa42a1aa6f",
100
+ "git_lfs": true,
101
+ "kind": "answer_heads",
102
+ "staged_bytes": 2053938,
103
+ "staged_sha256": "126a9b5487dca937a768a4f228f2d2e7d513900d8ad0e99c4137fbaa42a1aa6f"
104
+ },
105
+ {
106
+ "destination": "adapter/config.json",
107
+ "generated_by": "ops/solomon_package.py",
108
+ "kind": "adapter_config",
109
+ "staged_bytes": 2240,
110
+ "staged_sha256": "0d5e04740dafd6d276e470ef7f3f499cdfa320384e21088b8b399d39a4f10770"
111
+ },
112
+ {
113
+ "destination": "serving/serving-binding.json",
114
+ "kind": "serving_binding",
115
+ "staged_bytes": 5591,
116
+ "staged_sha256": "4162fb607e5f41841ba93668fcae4e097d7855b62988c1c163e779bbb9c24870"
117
+ },
118
+ {
119
+ "destination": "serving/readout-temperature-v2.json",
120
+ "expected_sha256": "d6925a0168b2577d0e4d517cd25dd5ceb0b7cc8eee91b70aefd3a3aa9dcb64ce",
121
+ "kind": "calibration_artifact",
122
+ "staged_bytes": 3414,
123
+ "staged_sha256": "d6925a0168b2577d0e4d517cd25dd5ceb0b7cc8eee91b70aefd3a3aa9dcb64ce"
124
+ },
125
+ {
126
+ "destination": "serving/selection.json",
127
+ "generated_by": "ops/solomon_package.py",
128
+ "kind": "readout_selection",
129
+ "staged_bytes": 551,
130
+ "staged_sha256": "5b2adb1dc61a4fcf5ce2993159899b46393648f0eda66b66f92b44a693004fe2"
131
+ },
132
+ {
133
+ "destination": "serving/service-export.json",
134
+ "generated_by": "ops/solomon_package.py",
135
+ "kind": "qualification_envelope",
136
+ "staged_bytes": 452,
137
+ "staged_sha256": "46055031eeef5d374382981c7c431450ead3640694a35611284a1c13ed33e364"
138
+ },
139
+ {
140
+ "destination": "src/solomon/__init__.py",
141
+ "kind": "serving_code",
142
+ "staged_bytes": 1157,
143
+ "staged_sha256": "1e9e7993cd182b5ccac3eab801277cb00c802c75281bee81571890c6fdaed2c6"
144
+ },
145
+ {
146
+ "destination": "src/solomon/api.py",
147
+ "kind": "serving_code",
148
+ "staged_bytes": 3929,
149
+ "staged_sha256": "52f53f39ed334277a721620b24bdb3a95cf9db08652a95bdd42f2771c2b2902c"
150
+ },
151
+ {
152
+ "destination": "src/solomon/binding.py",
153
+ "kind": "serving_code",
154
+ "staged_bytes": 13136,
155
+ "staged_sha256": "b19e5fead9435fa82b52e4c25139da9e03a0a30bc485d20a64c8d263a912e121"
156
+ },
157
+ {
158
+ "destination": "src/solomon/calibration.py",
159
+ "kind": "serving_code",
160
+ "staged_bytes": 10205,
161
+ "staged_sha256": "a891a91127abb44e2a9cde7342f7e980734049f79481c496a973b3fbc9de9a24"
162
+ },
163
+ {
164
+ "destination": "src/solomon/engine.py",
165
+ "kind": "serving_code",
166
+ "staged_bytes": 5682,
167
+ "staged_sha256": "23478f15c438f4b5201f4f3e817e2db95e92ad3353d796e18b6326d43916435b"
168
+ },
169
+ {
170
+ "destination": "src/solomon/engine_contract.py",
171
+ "kind": "serving_code",
172
+ "staged_bytes": 18263,
173
+ "staged_sha256": "3df6f2e515b765cbb07d5a281328989443795d7fdc920dc21756b4230ddf1fd5"
174
+ },
175
+ {
176
+ "destination": "src/solomon/engine_cuda.py",
177
+ "kind": "serving_code",
178
+ "staged_bytes": 7425,
179
+ "staged_sha256": "760ca8b1a506528bff0a2ea4ce9c5638110b31195a3ac3e6f5adaca707ec13ce"
180
+ },
181
+ {
182
+ "destination": "src/solomon/engine_numerics.py",
183
+ "kind": "serving_code",
184
+ "staged_bytes": 2979,
185
+ "staged_sha256": "898ea8cfce50fa19bd42bf2a115cc37d04d91fa0f9501220faec93a9821ca289"
186
+ },
187
+ {
188
+ "destination": "src/solomon/engine_reasoning.py",
189
+ "kind": "serving_code",
190
+ "staged_bytes": 9209,
191
+ "staged_sha256": "87f417015f45293283bd3a2738c5745e5a2aac7a805ae89403fdc1fb7b226bb4"
192
+ },
193
+ {
194
+ "destination": "src/solomon/engine_reference.py",
195
+ "kind": "serving_code",
196
+ "staged_bytes": 13037,
197
+ "staged_sha256": "5487a5b0536e481a8285ccd82dff7ff389340d4f59c36653d358088b6c4050c8"
198
+ },
199
+ {
200
+ "destination": "src/solomon/evidence.py",
201
+ "kind": "serving_code",
202
+ "staged_bytes": 7617,
203
+ "staged_sha256": "a0ece458b5c0546c1f80b48cea87ebc1c3732e83f2c0f8e58969645bc8bde2f7"
204
+ },
205
+ {
206
+ "destination": "src/solomon/evidence_packages.py",
207
+ "kind": "serving_code",
208
+ "staged_bytes": 24688,
209
+ "staged_sha256": "8e555f09c7fa96e1e135d5bb49d388b66ffbd4fc40fc1659b4cb7396ca3728c5"
210
+ },
211
+ {
212
+ "destination": "src/solomon/heads.py",
213
+ "kind": "serving_code",
214
+ "staged_bytes": 13978,
215
+ "staged_sha256": "1934d3c50c57622fa2159211b5c9da024ab888ad6ba49d8b7e82365539a785a4"
216
+ },
217
+ {
218
+ "destination": "src/solomon/prompts_two_letter.py",
219
+ "kind": "serving_code",
220
+ "staged_bytes": 4169,
221
+ "staged_sha256": "12e19c094e48be2881cbad79f5c1ea0ffefffdcb308013d1b45925d32b6aae6f"
222
+ },
223
+ {
224
+ "destination": "src/solomon/readout.py",
225
+ "kind": "serving_code",
226
+ "staged_bytes": 14094,
227
+ "staged_sha256": "59f7f941262eba4f912dbadf4c0140f7cbb5997736f9dc3c7bae5f856763fc77"
228
+ },
229
+ {
230
+ "destination": "src/solomon/reliability.py",
231
+ "kind": "serving_code",
232
+ "staged_bytes": 1523,
233
+ "staged_sha256": "08cc3b22371a314b06bc89a7807c7c0581063f8a70a86ad92b62eae442bad42a"
234
+ },
235
+ {
236
+ "destination": "src/solomon/retrieval.py",
237
+ "kind": "serving_code",
238
+ "staged_bytes": 9155,
239
+ "staged_sha256": "2b7bd6603cb6df3bfe63496dd475206ff17655d48916cf974860adf335e9b155"
240
+ },
241
+ {
242
+ "destination": "src/solomon/routing.py",
243
+ "kind": "serving_code",
244
+ "staged_bytes": 3038,
245
+ "staged_sha256": "9901da2c3d3a0e8dc453dae91f6c68c7a32b609418fb6e8fc41e95e3601b3f77"
246
+ },
247
+ {
248
+ "destination": "src/solomon/semantics.py",
249
+ "kind": "serving_code",
250
+ "staged_bytes": 2910,
251
+ "staged_sha256": "86e1833b7f693e914cc55744ed5565ae0d436424c262f8773bb944a9f5ac65da"
252
+ },
253
+ {
254
+ "destination": "src/solomon/service.py",
255
+ "kind": "serving_code",
256
+ "staged_bytes": 32343,
257
+ "staged_sha256": "ab8899c9c6f04662ab93e58dd8f23fe940dbedeaabc4c8a16c449a41d2c98641"
258
+ },
259
+ {
260
+ "destination": "src/solomon/service_answers.py",
261
+ "kind": "serving_code",
262
+ "staged_bytes": 20064,
263
+ "staged_sha256": "9075e9b9e7a713a9f843267dc5aebe8d6b9fc4dcaadbd9800c964d966e83fb06"
264
+ },
265
+ {
266
+ "destination": "src/solomon/service_checked.py",
267
+ "kind": "serving_code",
268
+ "staged_bytes": 7596,
269
+ "staged_sha256": "cff9d85ea8dcb3f431dd2497a636f4d02cdc2c5d2add6f12aab9889bb29e9082"
270
+ },
271
+ {
272
+ "destination": "src/solomon/service_evidence.py",
273
+ "kind": "serving_code",
274
+ "staged_bytes": 7758,
275
+ "staged_sha256": "a2021700c36d9844f607497b7ab0d098e1f51fd775c6eb2a77940fa590335603"
276
+ },
277
+ {
278
+ "destination": "src/solomon/service_heads.py",
279
+ "kind": "serving_code",
280
+ "staged_bytes": 9364,
281
+ "staged_sha256": "6dc2a0da037aea32c9bba0c3e5924c8f33779eed9b6f02c66465b3a9b960fb9c"
282
+ },
283
+ {
284
+ "destination": "src/solomon/service_packages.py",
285
+ "kind": "serving_code",
286
+ "staged_bytes": 13181,
287
+ "staged_sha256": "5f30eaaac5daa80f1fc8399828ddd1c7128a34e79fe88a3440656e76629ac8d8"
288
+ },
289
+ {
290
+ "destination": "src/solomon/service_states.py",
291
+ "kind": "serving_code",
292
+ "staged_bytes": 10657,
293
+ "staged_sha256": "329ecca03d06a53c3aa15568784b70cdde7c4ea63c3283e4aaec3f9018defdda"
294
+ },
295
+ {
296
+ "destination": "src/solomon/serving.py",
297
+ "kind": "serving_code",
298
+ "staged_bytes": 4009,
299
+ "staged_sha256": "978a6f1d1193dd535a5fc03fa393b6421a2cd7c85bb77b1dfa796b7fcfb92836"
300
+ },
301
+ {
302
+ "destination": "mlx/.gitignore",
303
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
304
+ "kind": "mlx_package",
305
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
306
+ "staged_bytes": 126,
307
+ "staged_sha256": "dde5ff0f5e7a2c741e6ec76777be6a2e1d3679815bdf8f44d8ca2cee2ce0e351"
308
+ },
309
+ {
310
+ "destination": "mlx/CONVERTER-SOURCE.json",
311
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
312
+ "kind": "mlx_package",
313
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
314
+ "staged_bytes": 1515,
315
+ "staged_sha256": "fd243d33ca76fe6a3e76a6b0dca6fc6ee2a8a062f7bc92d4364c49cf81a25e9f"
316
+ },
317
+ {
318
+ "destination": "mlx/LICENSE",
319
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
320
+ "kind": "mlx_package",
321
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
322
+ "staged_bytes": 11344,
323
+ "staged_sha256": "a61385b8bc4e786195136404b4975fede3c0bca526877f526482e9af93d47457"
324
+ },
325
+ {
326
+ "destination": "mlx/MODIFICATIONS.md",
327
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
328
+ "kind": "mlx_package",
329
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
330
+ "staged_bytes": 1616,
331
+ "staged_sha256": "219a4608561ff0d7629df974383a0e1857643f3b8a8ff6e910030e5b9d4911a0"
332
+ },
333
+ {
334
+ "destination": "mlx/NOTICE",
335
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
336
+ "kind": "mlx_package",
337
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
338
+ "staged_bytes": 3897,
339
+ "staged_sha256": "7c62f7b3fde4f2f80f869be0bf592facd5e4a4d38dec826c1f6953bede6255ca"
340
+ },
341
+ {
342
+ "destination": "mlx/README.md",
343
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
344
+ "kind": "mlx_package",
345
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
346
+ "staged_bytes": 7417,
347
+ "staged_sha256": "586f53fd31ea723be1cbf0a2b5f35ed196960a231e132d8fd27e5842cc2b46a8"
348
+ },
349
+ {
350
+ "destination": "mlx/bf16/LICENSE",
351
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
352
+ "kind": "mlx_package",
353
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
354
+ "staged_bytes": 11344,
355
+ "staged_sha256": "a61385b8bc4e786195136404b4975fede3c0bca526877f526482e9af93d47457"
356
+ },
357
+ {
358
+ "destination": "mlx/bf16/MODIFICATIONS.md",
359
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
360
+ "kind": "mlx_package",
361
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
362
+ "staged_bytes": 4195,
363
+ "staged_sha256": "eda88d63f04f03cb169579d527ceea4eb71bf44eae5c305bc688fc0e2a3fdc78"
364
+ },
365
+ {
366
+ "destination": "mlx/bf16/NOTICE",
367
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
368
+ "kind": "mlx_package",
369
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
370
+ "staged_bytes": 3897,
371
+ "staged_sha256": "7c62f7b3fde4f2f80f869be0bf592facd5e4a4d38dec826c1f6953bede6255ca"
372
+ },
373
+ {
374
+ "destination": "mlx/bf16/README.md",
375
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
376
+ "kind": "mlx_package",
377
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
378
+ "staged_bytes": 3063,
379
+ "staged_sha256": "1e3aa92ff4687d6e46520473bcc9c207b492d9239f1f882bff185c716ecee320"
380
+ },
381
+ {
382
+ "destination": "mlx/bf16/base-manifest.json",
383
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
384
+ "kind": "mlx_package",
385
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
386
+ "staged_bytes": 6434,
387
+ "staged_sha256": "e62a6942465b43f7f47616e36a16d6f32a1bd9daa5124dd26bf61b8eab0c3b6d"
388
+ },
389
+ {
390
+ "destination": "mlx/bf16/binding.json",
391
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
392
+ "kind": "mlx_package",
393
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
394
+ "staged_bytes": 12306,
395
+ "staged_sha256": "6d45715aa040fad98b061ff2cbafb35b047143ef2475646cee3df7a334f4d530"
396
+ },
397
+ {
398
+ "destination": "mlx/bf16/conversion.json",
399
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
400
+ "kind": "mlx_package",
401
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
402
+ "staged_bytes": 6934,
403
+ "staged_sha256": "fb3db797acdf96c9eca2b6dfef2d6d385705aeade387011d45ea16b91b510c66"
404
+ },
405
+ {
406
+ "destination": "mlx/docs/UPSTREAM-MODIFICATIONS.md",
407
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
408
+ "kind": "mlx_package",
409
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
410
+ "staged_bytes": 4195,
411
+ "staged_sha256": "eda88d63f04f03cb169579d527ceea4eb71bf44eae5c305bc688fc0e2a3fdc78"
412
+ },
413
+ {
414
+ "destination": "mlx/docs/VALIDATION-20260921.md",
415
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
416
+ "kind": "mlx_package",
417
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
418
+ "staged_bytes": 2928,
419
+ "staged_sha256": "86afe1be02ed55a75c2b2a1663898f20cc536371f5dcd2df0f701f7a30ae9a47"
420
+ },
421
+ {
422
+ "destination": "mlx/examples/decide.py",
423
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
424
+ "kind": "mlx_package",
425
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
426
+ "staged_bytes": 763,
427
+ "staged_sha256": "1a004e8a474f0458a4b84024098dfcb44ec5a24a795d742d266e7557ac9fd170"
428
+ },
429
+ {
430
+ "destination": "mlx/pyproject.toml",
431
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
432
+ "kind": "mlx_package",
433
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
434
+ "staged_bytes": 1115,
435
+ "staged_sha256": "e7822f6addbb909f4424084e3cca5eb11a7f5cb929b4b5742b1690a2bed756b5"
436
+ },
437
+ {
438
+ "destination": "mlx/requirements.cloud.lock",
439
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
440
+ "kind": "mlx_package",
441
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
442
+ "staged_bytes": 74492,
443
+ "staged_sha256": "4b60f433f1f67289db1db68630d011aea1565b50cf518c1e7461d7c2b0e2599b"
444
+ },
445
+ {
446
+ "destination": "mlx/requirements.lock",
447
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
448
+ "kind": "mlx_package",
449
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
450
+ "staged_bytes": 1338,
451
+ "staged_sha256": "cb2a81cc73252bc54570e035483d68e24253c98223e0e65373df5995bd99dc5a"
452
+ },
453
+ {
454
+ "destination": "mlx/scripts/benchmark.py",
455
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
456
+ "kind": "mlx_package",
457
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
458
+ "staged_bytes": 5074,
459
+ "staged_sha256": "7a9ee62cae81bf4d05d5ad17760bfa510886812a017eb0bc8d9cab68dcd1cab6"
460
+ },
461
+ {
462
+ "destination": "mlx/scripts/benchmark_chunks.py",
463
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
464
+ "kind": "mlx_package",
465
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
466
+ "staged_bytes": 1897,
467
+ "staged_sha256": "216e10981bdff42d04269082ae2317ab25a161c80504813aa74ee1a55b7ca167"
468
+ },
469
+ {
470
+ "destination": "mlx/scripts/check_cuda_parity.py",
471
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
472
+ "kind": "mlx_package",
473
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
474
+ "staged_bytes": 7614,
475
+ "staged_sha256": "082ae6c535f52d6b386d3348222515ef564b38efaf59fd8d6b262d00867b0a24"
476
+ },
477
+ {
478
+ "destination": "mlx/scripts/score_parity.py",
479
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
480
+ "kind": "mlx_package",
481
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
482
+ "staged_bytes": 542,
483
+ "staged_sha256": "ddc84f869bccd5d2c270f6abf2a0862c59ec7c0ebdc3497959ba35c16bb11b7a"
484
+ },
485
+ {
486
+ "destination": "mlx/scripts/validate_api.py",
487
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
488
+ "kind": "mlx_package",
489
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
490
+ "staged_bytes": 5852,
491
+ "staged_sha256": "f29c49ac600314491c36c43b780b92958dea56253377b4b64a2da7ecb4b57a28"
492
+ },
493
+ {
494
+ "destination": "mlx/src/solomon_mlx/__init__.py",
495
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
496
+ "kind": "mlx_package",
497
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
498
+ "staged_bytes": 132,
499
+ "staged_sha256": "714a5439b33780d250c404938cd062c0d6809f83f21b59f89997bd168469925a"
500
+ },
501
+ {
502
+ "destination": "mlx/src/solomon_mlx/_vendor/__init__.py",
503
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
504
+ "kind": "mlx_package",
505
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
506
+ "staged_bytes": 113,
507
+ "staged_sha256": "77defd15cc47661e0e9a31275e7fd59e979f3f9a6429671d8199f6002dca6c2c"
508
+ },
509
+ {
510
+ "destination": "mlx/src/solomon_mlx/_vendor/contract.py",
511
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
512
+ "kind": "mlx_package",
513
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
514
+ "staged_bytes": 6474,
515
+ "staged_sha256": "7c6607179a028f30b462349a86f9cf7d0ec2652e0a1c7c8c24649b6ce71df697"
516
+ },
517
+ {
518
+ "destination": "mlx/src/solomon_mlx/_vendor/evidence.py",
519
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
520
+ "kind": "mlx_package",
521
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
522
+ "staged_bytes": 7730,
523
+ "staged_sha256": "18a4978a27d6bbd3f7daaa34836d1820303c4ff581b0dfda877aab586392293b"
524
+ },
525
+ {
526
+ "destination": "mlx/src/solomon_mlx/_vendor/evidence_v3.py",
527
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
528
+ "kind": "mlx_package",
529
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
530
+ "staged_bytes": 24783,
531
+ "staged_sha256": "6ff3da1e920c082e9b3629ca0230007262f2ce69fd921b89dd4b3e67511b3a64"
532
+ },
533
+ {
534
+ "destination": "mlx/src/solomon_mlx/_vendor/prompts.py",
535
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
536
+ "kind": "mlx_package",
537
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
538
+ "staged_bytes": 4693,
539
+ "staged_sha256": "8bfb5a12d625664c8830f5cf243aac04d1e973bfe4f5ecfc8221021f09c318df"
540
+ },
541
+ {
542
+ "destination": "mlx/src/solomon_mlx/_vendor/retrieval.py",
543
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
544
+ "kind": "mlx_package",
545
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
546
+ "staged_bytes": 9261,
547
+ "staged_sha256": "11e7bbb1a84ba837eac3768d6e882f44a557be25d62729c8a39dd5cb870c0932"
548
+ },
549
+ {
550
+ "destination": "mlx/src/solomon_mlx/_vendor/semantics.py",
551
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
552
+ "kind": "mlx_package",
553
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
554
+ "staged_bytes": 3051,
555
+ "staged_sha256": "b580d3c114536a6faf58bcd92d2c61028f80891a19d78d6a17ed585948abfc15"
556
+ },
557
+ {
558
+ "destination": "mlx/src/solomon_mlx/api.py",
559
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
560
+ "kind": "mlx_package",
561
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
562
+ "staged_bytes": 13772,
563
+ "staged_sha256": "bae9fdd3ef6b395142ec5c099635cc9ba90f7f33c7423f99caf6009f51d4fd3c"
564
+ },
565
+ {
566
+ "destination": "mlx/src/solomon_mlx/artifacts.py",
567
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
568
+ "kind": "mlx_package",
569
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
570
+ "staged_bytes": 2614,
571
+ "staged_sha256": "d41d4d3f19aaf0dd54e4503d43807a29208d9528b8d4734b9f3d99cad18d9f93"
572
+ },
573
+ {
574
+ "destination": "mlx/src/solomon_mlx/budget.py",
575
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
576
+ "kind": "mlx_package",
577
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
578
+ "staged_bytes": 2875,
579
+ "staged_sha256": "f72614686c19e1d923e6bc23d4353e8b1ac150863565939ae4a3831bc4ecd211"
580
+ },
581
+ {
582
+ "destination": "mlx/src/solomon_mlx/cli.py",
583
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
584
+ "kind": "mlx_package",
585
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
586
+ "staged_bytes": 2990,
587
+ "staged_sha256": "0a6be4cd03621963ec5f73a8af71224cb8b40ae88232477d8370b7d3b9b75021"
588
+ },
589
+ {
590
+ "destination": "mlx/src/solomon_mlx/engine.py",
591
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
592
+ "kind": "mlx_package",
593
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
594
+ "staged_bytes": 15359,
595
+ "staged_sha256": "13c27c3fbca576ae0d70262c2a75c9382df3b4fcfd8a11996d125750883b648a"
596
+ },
597
+ {
598
+ "destination": "mlx/src/solomon_mlx/evaluation.py",
599
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
600
+ "kind": "mlx_package",
601
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
602
+ "staged_bytes": 13906,
603
+ "staged_sha256": "bb9f50d184527e21139b9ffb5e9d1613bc30822ccd7cf06b7b7f8b1cc8b50674"
604
+ },
605
+ {
606
+ "destination": "mlx/src/solomon_mlx/prepare.py",
607
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
608
+ "kind": "mlx_package",
609
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
610
+ "staged_bytes": 5513,
611
+ "staged_sha256": "dda9879a9ddc1c3f6dcf0df52b3a244b2ca7920946bbd29ddc8e1c0f9944b887"
612
+ },
613
+ {
614
+ "destination": "mlx/src/solomon_mlx_hub/__init__.py",
615
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
616
+ "kind": "mlx_package",
617
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
618
+ "staged_bytes": 248,
619
+ "staged_sha256": "9132679f7a5826d1f472cef6a42068ead04b9c4737d2c5fa667d8cb8437212e2"
620
+ },
621
+ {
622
+ "destination": "mlx/src/solomon_mlx_hub/__main__.py",
623
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
624
+ "kind": "mlx_package",
625
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
626
+ "staged_bytes": 1852,
627
+ "staged_sha256": "86cf93d7c2a2342e1f9babc4981f4dbd1255db08d79406ec0c3faaff91762f1c"
628
+ },
629
+ {
630
+ "destination": "mlx/src/solomon_mlx_hub/data/base-manifest.json",
631
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
632
+ "kind": "mlx_package",
633
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
634
+ "staged_bytes": 6434,
635
+ "staged_sha256": "e62a6942465b43f7f47616e36a16d6f32a1bd9daa5124dd26bf61b8eab0c3b6d"
636
+ },
637
+ {
638
+ "destination": "mlx/src/solomon_mlx_hub/data/release.json",
639
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
640
+ "kind": "mlx_package",
641
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
642
+ "staged_bytes": 8582,
643
+ "staged_sha256": "1bfa36191b003d46d85deeb51f40809c321feff1c0c6b8da27755b58e9c17b9e"
644
+ },
645
+ {
646
+ "destination": "mlx/src/solomon_mlx_hub/prepare.py",
647
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
648
+ "kind": "mlx_package",
649
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
650
+ "staged_bytes": 8707,
651
+ "staged_sha256": "9d433eb7b242aaa83e1f3c3f4a2b9f99cf410299f99c133732f6ff5559a9b202"
652
+ },
653
+ {
654
+ "destination": "mlx/tests/test_artifacts_and_evaluation.py",
655
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
656
+ "kind": "mlx_package",
657
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
658
+ "staged_bytes": 2745,
659
+ "staged_sha256": "10bbfb9b9e7d66c7dae6fd1e2ca2980572e4a81f93f847c3a0f49525d8053a23"
660
+ },
661
+ {
662
+ "destination": "mlx/tests/test_budget.py",
663
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
664
+ "kind": "mlx_package",
665
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
666
+ "staged_bytes": 780,
667
+ "staged_sha256": "4faef6c3ad8aa65df057babb86d4092943a4a262bb859445ee1dde1e29a826d5"
668
+ },
669
+ {
670
+ "destination": "mlx/tests/test_contract.py",
671
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
672
+ "kind": "mlx_package",
673
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
674
+ "staged_bytes": 3393,
675
+ "staged_sha256": "b4ac6dba4ac70f1f8c8c145fba62d276d3af9dc7ab833652c92f85a3048e5f26"
676
+ },
677
+ {
678
+ "destination": "mlx/tests/test_hub.py",
679
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
680
+ "kind": "mlx_package",
681
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
682
+ "staged_bytes": 7227,
683
+ "staged_sha256": "5926ceb8e970f1cc3c7a0b9fda2d35638f31eb12009d7232fabde4308247c633"
684
+ },
685
+ {
686
+ "destination": "mlx/tests/test_metal_primitives.py",
687
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
688
+ "kind": "mlx_package",
689
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
690
+ "staged_bytes": 1704,
691
+ "staged_sha256": "2d88596fba6cb6b16acb9af958add22e9b21d367dbd4fcc277878973a5e3c30a"
692
+ },
693
+ {
694
+ "destination": "mlx/tests/test_parity.py",
695
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
696
+ "kind": "mlx_package",
697
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
698
+ "staged_bytes": 763,
699
+ "staged_sha256": "77487c307fe272a99e1f17b9e26e30dc987127a7c47fc7c2c8a545bca174b881"
700
+ },
701
+ {
702
+ "destination": "mlx/tests/test_processor.py",
703
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
704
+ "kind": "mlx_package",
705
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
706
+ "staged_bytes": 853,
707
+ "staged_sha256": "521586bf405dced3dc8ebe890c2ad3f42dd99792c08fd84e9d0a4398642b3727"
708
+ },
709
+ {
710
+ "destination": "mlx/tests/test_tiny_decoder.py",
711
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
712
+ "kind": "mlx_package",
713
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
714
+ "staged_bytes": 2369,
715
+ "staged_sha256": "e2a7496551da6d6690ee55c2d299a4759122bcfa77d48f0424bac2892a555dcf"
716
+ },
717
+ {
718
+ "destination": "mlx/tests/test_tiny_library.py",
719
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
720
+ "kind": "mlx_package",
721
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
722
+ "staged_bytes": 6658,
723
+ "staged_sha256": "03a2887be6713671ce1307d24c1e41e5d5025423c24230c4d7e99743a9b50bc8"
724
+ },
725
+ {
726
+ "destination": "mlx/uv.lock",
727
+ "generated_by": "the MLX packaging step (separate owner); staged in place",
728
+ "kind": "mlx_package",
729
+ "note": "part of the optional Apple-silicon package under mlx/; not loaded by the serving layer under src/",
730
+ "staged_bytes": 285374,
731
+ "staged_sha256": "e413d49af059f183f7fd4a39fccae8cc2c3908a4e7562926ea8de248880ddbc7"
732
+ }
733
+ ],
734
+ "hash_or_size_mismatch": [],
735
+ "heads_sha256": "126a9b5487dca937a768a4f228f2d2e7d513900d8ad0e99c4137fbaa42a1aa6f",
736
+ "license": "apache-2.0",
737
+ "live_acceptance_passed_for_this_binding": true,
738
+ "missing_sources": [],
739
+ "model": "Solomon",
740
+ "not_shipped_though_statically_reachable": [
741
+ "a smoke test carrying an embedded synthetic document",
742
+ "the answer-head training loop",
743
+ "the benchmark-panel builder (panel authoring and validation, not a serving file)",
744
+ "the evaluation harness",
745
+ "the superseded training-side confidence layer",
746
+ "the training-side calibration fit",
747
+ "the training/evaluation data module"
748
+ ],
749
+ "not_staged": [],
750
+ "owner_release_decision_recorded": true,
751
+ "policy": "DEFAULT DENY. Only the destinations listed in `files` may exist in the repository. `ops/solomon_package.py --enforce` walks the working tree and fails on anything else.",
752
+ "publishing_performed": false,
753
+ "readout": "four_collapsed",
754
+ "repo_id": "DoccyHealth/Solomon",
755
+ "runtime_fingerprint": "c3d933e068e19879b45fb6dc6ce4af83a4d22f615c263b209e15f9c4fb2ae952",
756
+ "schema": "solomon.distribution-manifest.v1",
757
+ "serving_binding_sha256": "49904e27814e0ccfc483b0503237d84f8ca60a79713f393b23b0dbe57d87a6bf",
758
+ "staged_count": 96,
759
+ "staged_into": "release/Solomon",
760
+ "totals": {
761
+ "bytes_from_disk": 872709029,
762
+ "entries": 96,
763
+ "ready": 96
764
+ },
765
+ "version": "1.1.0"
766
+ }
MODIFICATIONS.md ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Statement of changes
2
+
3
+ Apache License 2.0, section 4(b): prominent notice that files carry modifications.
4
+
5
+ ## What is modified
6
+
7
+ **No upstream source file is modified.** No file from `Qwen/Qwen3.8-27B` is edited,
8
+ renamed, patched or redistributed in this repository, with one exception: the
9
+ upstream licence text is reproduced byte-for-byte at `licenses/Qwen-Apache-2.0.txt`
10
+ (sha256 `bbedc3fda3305820b977265f01b8619d87570a6739de3a5582c3464840f1e57a`) because section 4(a) requires it. That file is
11
+ unmodified and carries the upstream copyright.
12
+
13
+ The modification this work carries is not an edit to a source file. It is a set
14
+ of **trained parameters applied to the base model at inference time**, plus an
15
+ original serving layer that reads the model's logits. Concretely:
16
+
17
+ | Change | Artifact | sha256 |
18
+ |---|---|---|
19
+ | LoRA adapter, rank 64, question-side placement, float32 | `adapter/adapter.safetensors` | `2addaf841ecc58829ad73081603b8d3e52743c53c6d558a17a1dd30e9bd2dbca` |
20
+ | Trained linear answer heads | `adapter/heads.npz` | `126a9b5487dca937a768a4f228f2d2e7d513900d8ad0e99c4137fbaa42a1aa6f` |
21
+ | Readout calibration, one positive scalar per task | `serving/readout-temperature-v2.json` | file `d6925a0168b2577d0e4d517cd25dd5ceb0b7cc8eee91b70aefd3a3aa9dcb64ce` / payload `6506e2394bda5f8e7c7b9742f70a5b8782efad53d5451d5d836ba3463cece24b` |
22
+ | Runtime identity binding | `serving/serving-binding.json` | payload `49904e27814e0ccfc483b0503237d84f8ca60a79713f393b23b0dbe57d87a6bf` |
23
+ | Serving layer (original work, not derived from upstream code) | `src/` | see `MANIFEST.json` |
24
+
25
+ Base model, unmodified and not redistributed: `Qwen/Qwen3.8-27B` at revision
26
+ `1d4bf0f2ff6012fd82039f2fa52739d0dd7c60c0`, Copyright 2026 Alibaba Cloud, Apache-2.0.
27
+
28
+ Training took place between 16 and 20 September 2026. The shipped artifacts are
29
+ identified by the checksums in the table above and in `MANIFEST.json`.
30
+
31
+ ## Which files carry a change notice
32
+
33
+ | File | Why |
34
+ |---|---|
35
+ | `NOTICE` | Section 4(b) and 4(c) statement, carried with every copy |
36
+ | `MODIFICATIONS.md` | this file |
37
+ | `README.md` | names the base model, the pinned revision and the derivative relationship in the front matter and in the body |
38
+ | `adapter/config.json` | machine-readable record of the base repo, the pinned revision and both weight checksums |
39
+ | `serving/serving-binding.json` | pins the exact runtime the weights were measured on and refuses to load against a different one |
40
+
41
+ No file under `src/` carries an upstream change notice, because no file under
42
+ `src/` contains upstream code. Every file there is original work, written for
43
+ this project, and is covered by the repository's own Apache-2.0 `LICENSE` and by
44
+ the copyright line in `NOTICE`.
45
+
46
+ All of the changes described above — the adapter, the heads, the calibration, the
47
+ serving binding and the serving layer — are Copyright 2026
48
+ Doccy Pty Ltd and licensed under Apache-2.0.
49
+
50
+ ## Third-party text scan
51
+
52
+ Before release, **every file staged into this repository was scanned for text
53
+ originating in third-party source documents.** The scan compared normalised
54
+ 6-gram and 8-gram shingles of every staged text file against:
55
+
56
+ 1. the 42 third-party source records the training and evaluation panels were
57
+ built from (Apache-2.0, MIT, BSD-3-Clause, CC BY 4.0, CC BY-SA 4.0, CC0,
58
+ OGL v3.0 and US-government public-domain assertions); and
59
+ 2. every generated panel and document corpus on disk.
60
+
61
+ **Result: no third-party document text is present in any shipped file.** The
62
+ only matches were:
63
+
64
+ * the reproduced Apache-2.0 licence text at `licenses/Qwen-Apache-2.0.txt`, which
65
+ matches an Apache-2.0 licence document held in the evaluation corpus and is
66
+ required to be here verbatim; and
67
+ * the phrase *"A missing fact is not a negative fact"*, which is **our own
68
+ prompt-template wording** appearing in our own evaluation panels, not
69
+ third-party text entering our prompts.
70
+
71
+ Acceptance fixtures are excluded from this repository entirely. The fixture
72
+ documents used in live acceptance are original synthetic text authored for this
73
+ project and held in tooling that is not distributed.
74
+
75
+ Re-run the scan with `ops/solomon_package.py --scan` in the source project.
76
+
77
+ ## Maintainer notes
78
+
79
+ These warnings used to live in a `PUSH.md` that carried its own instruction to be
80
+ deleted before the repository was made public. The repository is public now, so
81
+ that file is gone — from the manifest and from the tree — and the parts of it that
82
+ are still true are kept here.
83
+
84
+ **Never mutate a published revision.** The serving binding pins by hash and
85
+ consumers pin by revision. If something is wrong with a published revision, push a
86
+ **new** revision and a **new** tag. Do not force-push over a revision that has
87
+ already been fetched: a consumer who pinned it would silently get different weights
88
+ under a hash they already trusted.
89
+
90
+ **Do not trust a fetch tool's exit code.** The remote-volume fetch used to retrieve the adapter PRINTS "No such file or directory" AND EXITS 0 on a wrong path: a failed download is indistinguishable from a successful one by return code. Never trust the exit status; check that the file exists and that its sha256 matches before treating a fetch as done.
91
+ The 870 MB adapter in this repository was fetched that way, and the only thing that
92
+ made the fetch trustworthy was re-hashing the file afterwards. Verify what you
93
+ downloaded from here the same way:
94
+
95
+ ```sh
96
+ shasum -a 256 adapter/adapter.safetensors # 2addaf841ecc58829ad73081603b8d3e52743c53c6d558a17a1dd30e9bd2dbca
97
+ shasum -a 256 adapter/heads.npz # 126a9b5487dca937a768a4f228f2d2e7d513900d8ad0e99c4137fbaa42a1aa6f
98
+ ```
99
+
100
+ `MANIFEST.json` carries the size and sha256 of every file here.
101
+
102
+ **Both weight files must go through git-lfs.** `.gitattributes` tracks
103
+ `*.safetensors` and `*.npz`; confirm with `git lfs ls-files` before committing. An
104
+ 870 MB blob committed outside LFS has to be undone by rewriting history.
105
+
106
+ **Every generated file here comes from `release/solomon-release.json`.** Editing a
107
+ generated file by hand breaks the manifest hash and is caught by
108
+ `ops/solomon_package.py --enforce` as `DRIFTED_SINCE_STAGING`. Change the descriptor
109
+ or the generator and re-stage.
110
+
111
+ **A calibration may not be carried onto a different adapter.** The temperatures were
112
+ fitted on this model's logits. Refit and register them for a new adapter, or ship no
113
+ calibration and serve at T = 1.0, which is always permitted.
NOTICE ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Solomon v1.1.0
2
+ Copyright 2026 Doccy Pty Ltd
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
5
+ this work except in compliance with the License. You may obtain a copy of the
6
+ License in the LICENSE file distributed with this work, or at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ --------------------------------------------------------------------------------
11
+ ATTRIBUTION FOR THE BASE MODEL (Apache License 2.0, section 4(c))
12
+ --------------------------------------------------------------------------------
13
+
14
+ This work is a DERIVATIVE WORK of:
15
+
16
+ Qwen/Qwen3.8-27B
17
+ Copyright 2026 Alibaba Cloud
18
+ Licensed under the Apache License, Version 2.0
19
+ Pinned revision: 1d4bf0f2ff6012fd82039f2fa52739d0dd7c60c0
20
+ Licence text: licenses/Qwen-Apache-2.0.txt (sha256 bbedc3fda3305820b977265f01b8619d87570a6739de3a5582c3464840f1e57a, 11544 bytes,
21
+ the exact bytes served at the pinned revision)
22
+
23
+ The base model weights are NOT redistributed in this repository. They are
24
+ referenced by the pinned revision above and downloaded by the operator directly
25
+ from the upstream repository under the upstream licence.
26
+
27
+ Upstream NOTICE file: NONE. A NOTICE file is absent from Qwen/Qwen3.8-27B at the
28
+ pinned revision (HTTP 404, retrieved 2026-09-18T03:49Z without credentials).
29
+ Apache-2.0 section 4(d) therefore imposes no carry-forward obligation here. No
30
+ upstream attribution text has been invented or paraphrased.
31
+
32
+ "Qwen" and "Alibaba Cloud" are used nominatively, to identify the base model
33
+ this adapter was trained against. Apache-2.0 section 6 grants no trademark
34
+ rights and none are claimed or implied. Nothing here states or implies any
35
+ endorsement, sponsorship or affiliation.
36
+
37
+ --------------------------------------------------------------------------------
38
+ STATEMENT OF CHANGES (Apache License 2.0, section 4(b))
39
+ --------------------------------------------------------------------------------
40
+
41
+ No upstream source file is modified, and no upstream file is redistributed
42
+ except the unmodified licence text at licenses/Qwen-Apache-2.0.txt.
43
+
44
+ The modification this work carries is a trained LoRA adapter and a set of
45
+ trained linear answer heads, applied to the base model at inference time:
46
+
47
+ * LoRA adapter, rank 64, question-side placement, float32
48
+ adapter/adapter.safetensors
49
+ sha256 2addaf841ecc58829ad73081603b8d3e52743c53c6d558a17a1dd30e9bd2dbca
50
+ 870363376 bytes
51
+ * Trained linear answer heads
52
+ adapter/heads.npz
53
+ sha256 126a9b5487dca937a768a4f228f2d2e7d513900d8ad0e99c4137fbaa42a1aa6f
54
+ 2053938 bytes
55
+ * Readout calibration (one positive scalar per task)
56
+ serving/readout-temperature-v2.json
57
+ file sha256 d6925a0168b2577d0e4d517cd25dd5ceb0b7cc8eee91b70aefd3a3aa9dcb64ce
58
+ payload sha256 6506e2394bda5f8e7c7b9742f70a5b8782efad53d5451d5d836ba3463cece24b
59
+
60
+ Training took place between 16 and 20 September 2026. The adapter and the heads
61
+ are identified by the checksums above. Full change detail is in MODIFICATIONS.md.
62
+
63
+ --------------------------------------------------------------------------------
64
+ THIRD-PARTY CONTENT IN THIS REPOSITORY
65
+ --------------------------------------------------------------------------------
66
+
67
+ The only third-party content distributed here is the unmodified Apache License
68
+ 2.0 text at licenses/Qwen-Apache-2.0.txt, reproduced to satisfy section 4(a).
69
+
70
+ No training document, evaluation panel, dataset, corpus, rendered page, cached
71
+ state, score archive or acceptance fixture is distributed. Every file in this
72
+ repository was scanned for text originating in third-party source documents
73
+ before release; see MODIFICATIONS.md, "Third-party text scan".
74
+
75
+ Everything else in this repository -- the serving code under src/, the adapter
76
+ and head weights, the calibration artifact, the serving binding and the
77
+ documentation -- is original work of Doccy Pty Ltd, licensed under
78
+ Apache-2.0.
79
+
80
+ --------------------------------------------------------------------------------
81
+ TRAINING-DATA PROVENANCE
82
+ --------------------------------------------------------------------------------
83
+
84
+ The adapter was trained on synthetic documents, some of which were produced by
85
+ editing third-party natural texts. None of those texts, and no document, panel or
86
+ dataset built from them, is distributed here. The training-panel sources are
87
+ listed with their titles, URLs and recorded licences in README.md, "Training-data
88
+ provenance", including the three recorded as CC BY-SA 4.0.
89
+
90
+ That listing is provenance disclosure and attribution as good practice. It is not
91
+ a statement that the trained weights are a derivative work or an adaptation of
92
+ those texts. Whether share-alike terms reach model weights is unsettled; this
93
+ package takes no position on it and the owner accepted the residual risk on
94
+ 21 September 2026 rather than resolving it.
README.md ADDED
@@ -0,0 +1,511 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ base_model: Qwen/Qwen3.8-27B
4
+ base_model_relation: adapter
5
+ library_name: peft
6
+ pipeline_tag: text-classification
7
+ tags:
8
+ - lora
9
+ - document-question-answering
10
+ - structured-decisions
11
+ - calibration
12
+ - synthetic-evaluation
13
+ ---
14
+
15
+ <!-- Generated by the release packager from release/solomon-release.json and the measured artifacts.
16
+ Do not edit this file by hand: it is hashed in MANIFEST.json and an edit trips enforcement. -->
17
+
18
+ # Solomon
19
+
20
+ A LoRA adapter and trained answer heads for **Qwen/Qwen3.8-27B** that turn a document plus a set of
21
+ structured questions into one probability per decision, with the evidence spans each answer was read
22
+ from. It does not generate text.
23
+
24
+ > ### Read this before you trust a number on this page
25
+ >
26
+ > **Every document accuracy and calibration figure here was measured on documents this project
27
+ > generated synthetically.** The only evaluation against real documents scored **0.8131
28
+ > whole-question agreement**, not the ≈99% the synthetic figures show, and the loss is concentrated in
29
+ > two of the five answer types: **entity 0.4359** and
30
+ > **multi-label 0.7000**.
31
+ >
32
+ > **The probability calibration does not transfer out of domain.** On general-knowledge benchmarks this
33
+ > model is *more* overconfident than the base model it is built on.
34
+ >
35
+ > Both are set out in full under **Limitations**, below. Nothing on this page is a certified error rate
36
+ > and nothing is guaranteed.
37
+
38
+ ## What it is, and what it is for
39
+
40
+ Give it a document once and ask structured questions against it. Each answer comes back as a
41
+ probability with the evidence it was read from. There is no chat, no reasoning trace and no sampling:
42
+ every answer is read from letter logits at a fixed position through trained linear heads, so the same
43
+ document and the same question return the same numbers every time.
44
+
45
+ Five answer types:
46
+
47
+ | Type | Question shape | What comes back |
48
+ |---|---|---|
49
+ | Yes / no | does the document establish X? | one probability |
50
+ | Single choice | which of these does it state? | one probability over the listed options |
51
+ | Ordered choice | which threshold does it state? | one probability over the ordered options |
52
+ | Entity | which of these parties is the X? | **one probability per candidate** |
53
+ | Multi-label | which of these apply? | **one probability per candidate** |
54
+
55
+ **It is for** turning documents into structured, machine-readable answers where you need a number
56
+ attached to each one, and where determinism and a refusal to drift matter more than fluency.
57
+
58
+ **It is not for** general knowledge question-answering, chat, generation, or summarisation. It is not
59
+ for any setting where the cost of a confident wrong "No" on something the document never mentions is
60
+ high — that is this model's worst measured failure and it is documented below.
61
+
62
+ ## How it works
63
+
64
+ | | |
65
+ |---|---|
66
+ | Base model | `Qwen/Qwen3.8-27B`, Apache-2.0, pinned revision `1d4bf0f2ff6012fd82039f2fa52739d0dd7c60c0`. **Not redistributed here** |
67
+ | Adaptation | LoRA, rank 64, **question-side** placement, float32 |
68
+ | Answer projection | trained linear heads (`adapter/heads.npz`), not the language-model head |
69
+ | Readout | structured letter logits; yes/no-shaped units collapse to a binary log-odds before temperature |
70
+ | Calibration | one positive scalar per answer type, applied to the logits before the softmax |
71
+ | Runtime identity | a 15-key binding that refuses to load if the engine is not the one measured |
72
+
73
+ **The document is prefilled once; the questions branch off it.** The document goes through the model a
74
+ single time and becomes a reusable state (`POST /states`). Every question is then answered as an
75
+ isolated branch off that prefix. Two consequences are worth stating because they are tested on real
76
+ hardware and not merely intended: asking the same questions in a different order returns the same
77
+ answers, and answering from the cached document state matches a full forward pass to within 1e-3.
78
+
79
+ **The adapter is off while the document is read, and on from the question onward.** That is what
80
+ question-side placement means. Applying it across the whole sequence gives a different model to
81
+ the one that was measured, and the identity binding exists partly to stop that happening by accident.
82
+
83
+ **The readout is structured, not generated.** Rather than sampling an answer and parsing it, the model
84
+ is asked to commit at a fixed position and the letter logits at that position are read through trained
85
+ heads (readout mode `four_collapsed`). Yes/no-shaped units — a yes/no question, and each individual candidate
86
+ inside an entity or multi-label answer — are collapsed to a single binary log-odds,
87
+ `p = sigmoid(z / T)` with `z = log P(yes)/P(no)`, before the temperature is applied. Choice questions
88
+ apply the temperature to the listed slice, `softmax(logits[:n] / T)`. The ruled temperatures are
89
+ boolean 1.9476 · single 1.0 · ordered 1.5063 · multilabel 1.6895 · entity 2.1834. Single choice ships at 1.0 deliberately: at its accuracy there is essentially nothing to
90
+ calibrate and a fitted value there would be noise.
91
+
92
+ A branch whose `head_key` is not in the calibration artifact's map is **refused, not served at an
93
+ assumed 1.0**.
94
+
95
+ **The temperatures live inside the runtime binding**, covered by its checksum. A calibration fitted on
96
+ one model may not be served on another: the loader refuses by name rather than serving scalars that
97
+ mean nothing. Serving at temperature 1.0 everywhere is always permitted, on any model.
98
+
99
+ ### What the returned score means
100
+
101
+ `ordering_score` means two different things depending on the question, and the difference matters.
102
+
103
+ - **Single-unit** — a yes/no question, a single or ordered choice, and **every per-candidate value**
104
+ inside an entity or multi-label answer. Here the score *is* the tempered readout probability, and the
105
+ held-out synthetic panel below validates it as a calibrated magnitude.
106
+ - **Multi-unit** — the rolled-up question-level score for an entity or multi-label question with more
107
+ than one candidate. It is the **product** of the per-candidate probabilities, which assumes those
108
+ candidates are independent. **That assumption has never been validated as a joint probability.** It
109
+ orders such questions well; it is a heuristic ordering, not a calibrated joint. If you need a
110
+ magnitude for one of these, read the per-candidate numbers.
111
+
112
+ The field is not called `probability` because that would be accurate for the first case and an
113
+ overclaim for the second.
114
+
115
+ There is **no abstention**. Every question is answered. The service will not emit a field named
116
+ `abstain`, `confidence`, `threshold` or `certified_error_rate`; it raises rather than return one. If
117
+ you want to decline low-confidence answers, that is your policy, made on your population, and this
118
+ release makes no claim about where to put the line.
119
+
120
+ ## How to run it
121
+
122
+ The package is a library, not a daemon: you build the engine, wrap it in the serving layer and start the
123
+ HTTP surface in four lines. It needs one CUDA device with enough memory for the base model in float32.
124
+
125
+ ```sh
126
+ pip install -r requirements.lock
127
+
128
+ huggingface-cli download DoccyHealth/Solomon --local-dir ./solomon
129
+ huggingface-cli download Qwen/Qwen3.8-27B --revision 1d4bf0f2ff6012fd82039f2fa52739d0dd7c60c0 --local-dir ./solomon/base
130
+
131
+ cd solomon
132
+ export PYTHONPATH=$PWD/src
133
+ ```
134
+
135
+ Run from inside that directory: the engine looks for the base model in `base/`, and the serving layer
136
+ reads `serving/selection.json` and the binding it names, both relative to the package root.
137
+
138
+ ```python
139
+ from solomon import api, service
140
+ from solomon.serving import ServiceEngine
141
+
142
+ engine = ServiceEngine('adapter/adapter.safetensors', 'adapter/heads.npz')
143
+ layer = service.service('./store', engine) # './store' holds cached document states
144
+ server = api.serve(layer) # GET /health, POST /states, POST /v1/decide
145
+ print('http://127.0.0.1:%d' % server.server_port)
146
+ server.serve_forever() # or skip the server and call layer.decide(...) directly
147
+ ```
148
+
149
+ `ServiceEngine` also takes `expected_adapter=` and `expected_heads=`, the two sha256 values printed
150
+ below; pass them and the engine refuses to start on a file that is not the one this card describes.
151
+
152
+ `GET /health` reports the contract, the readout mode and the runtime identity. If the engine you built
153
+ differs from the one the numbers were measured on — a different torch build, a different adapter, a
154
+ different arithmetic mode — **the binding refuses to load rather than quietly serving different
155
+ numbers**. That is intended behaviour; do not work around it.
156
+
157
+ ### What is in this repository
158
+
159
+ ```
160
+ README.md this file
161
+ LICENSE Apache-2.0
162
+ NOTICE attribution and the Apache-2.0 4(b)/4(c) notices
163
+ MODIFICATIONS.md statement of changes, third-party text scan, maintainer notes
164
+ MANIFEST.json every file, its size and its sha256
165
+ requirements.lock the pins of the image this was qualified on, and dependency licences
166
+ licenses/Qwen-Apache-2.0.txt the upstream licence, verbatim
167
+ adapter/adapter.safetensors the LoRA adapter
168
+ adapter/heads.npz the trained answer heads
169
+ adapter/config.json base repo, pinned revision, checksums, placement
170
+ serving/serving-binding.json runtime identity binding and the frozen temperatures
171
+ serving/readout-temperature-v2.json the calibration artifact, standalone
172
+ serving/selection.json readout mode and model identity
173
+ serving/service-export.json qualification envelope hashes
174
+ src/solomon/__init__.py solomon: a document plus structured questions in, one probability per decision out
175
+ src/solomon/api.py HTTP surface for the Solomon layer (solomon/service.py)
176
+ src/solomon/binding.py serving identity: which readout is served, and proof that it is the one that was measured
177
+ src/solomon/calibration.py the readout calibration: one positive scalar per answer type, and nothing else
178
+ src/solomon/engine.py question-only CUDA runtime for immutable semantic-head checkpoints
179
+ src/solomon/engine_contract.py the answer contract engine: contract v3 on the reference engine's float32 cached path
180
+ src/solomon/engine_cuda.py CUDA contract-v3 engine
181
+ src/solomon/engine_numerics.py versioned CUDA repair: bounded FP32 attention, FP64 recurrent accumulation
182
+ src/solomon/engine_reasoning.py the confidence layer text reasoning on immutable answer-contract base-prefix states
183
+ src/solomon/engine_reference.py the reference engine: task-agnostic document prefix, float32 arithmetic, chunked prefill
184
+ src/solomon/evidence.py deterministic source references and explicit evidence interventions
185
+ src/solomon/evidence_packages.py evidence packages (v3): selected spans plus source-derived governing context, per question unit
186
+ src/solomon/heads.py final normalized feature extraction, preserving the qualified CUDA engine
187
+ src/solomon/prompts_two_letter.py two-letter (Noul) prompts and block conversions
188
+ src/solomon/readout.py contract v3 readouts: branch jobs for every answer type, predictions from letter logits, and metrics
189
+ src/solomon/reliability.py what the readout says about its own answer, with nothing fitted behind it
190
+ src/solomon/retrieval.py inference-only source candidates and explicitly labelled retrieval baselines
191
+ src/solomon/routing.py real callback-driven escalation
192
+ src/solomon/semantics.py answer semantics (design note, not distributed)
193
+ src/solomon/service.py decision layer: the Solomon serving contract over the pinned readout chain
194
+ src/solomon/service_answers.py confidence-aware five-task service, reusing immutable answer-contract input persistence
195
+ src/solomon/service_checked.py backend-neutral contract-v3 service; restart replays immutable inputs, not tensors
196
+ src/solomon/service_evidence.py optional source-grounded evidence around the existing confidence service
197
+ src/solomon/service_heads.py trained-head fast/views service; unchanged decoder and separate stage confidence
198
+ src/solomon/service_packages.py evidence packages (v3) in the answer service: per-unit, source-grounded, page-referenced
199
+ src/solomon/service_states.py local contract-v3 prototype: task-neutral text/image states and five answer types
200
+ src/solomon/serving.py preserve five-task trained-head confidence/routing with optional evidence
201
+ mlx/ the optional Apple-silicon package: its own library, tests and notices
202
+ ```
203
+
204
+ **What is deliberately not here:** no training data, no evaluation panels, no document corpora, no
205
+ datasets, no cached states, no rendered images, no score archives, no test fixtures, no logs and no
206
+ base model weights. The package is default-deny: a manifest names every permitted file and the build
207
+ fails if anything else is present.
208
+
209
+ The files under `serving/` carry identity only: hashes, the readout mode, the served design and the
210
+ five temperatures. The loader verifies the binding's checksum and every runtime key it carries. The
211
+ measured provenance behind those hashes (which panels, which fit, which qualification run) is held in
212
+ the maintainer's records and is not distributed.
213
+
214
+ ## What it scores
215
+
216
+ ### On documents, held out, and synthetic
217
+
218
+ 1,500 generated documents, none of them seen by the temperature fit. The calibration
219
+ this repository ships is applied.
220
+
221
+ | Answer type | Units scored | Accuracy | ECE | Errors stated ≥0.99 | Share of mass ≥0.99 |
222
+ |---|---|---|---|---|---|
223
+ | Yes / no | 1,500 questions | 98.600% | 0.0079 | 14.3% | 73.6% |
224
+ | Single choice | 1,500 questions | 99.867% | 0.0004 | 0.0% | 99.1% |
225
+ | Ordered choice | 1,500 questions | 98.600% | 0.0012 | 4.8% | 85.2% |
226
+ | Multi-label (per candidate) | 7,634 candidates | 99.528% | 0.0026 | 13.9% | 95.8% |
227
+ | Entity (per candidate) | 12,000 candidates | 99.217% | 0.0073 | 3.2% | 67.9% |
228
+
229
+ Ordered choice is the best-calibrated cell here. **Yes/no is the weakest and stays weak**: it still
230
+ states 14.3% of its errors
231
+ above 0.99, so a yes/no answer above 0.99 is worth less than an entity candidate above 0.99 and the two
232
+ should not be treated as interchangeable.
233
+
234
+ **These documents are synthetic.** They were produced by this project's generators. That is the single
235
+ most important qualifier on this table and the next section is about what happens without it.
236
+
237
+ ### On public benchmarks, with no document at all
238
+
239
+ These are out-of-domain by construction: Solomon reads documents, and every item here is a bare
240
+ multiple-choice question. They are included because they are the only comparison a reader can check
241
+ against a model they already know — the unmodified base model, item for item, on the same prompts.
242
+
243
+ - **Solomon** — the shipped adapter and heads, structured letter readout over the answer options (`head_key` `single/choiceS`), production cached path, fp32.
244
+ - **Base model, standard prompt** — Qwen3.8-27B with no adapter, a standard zero-shot multiple-choice chat prompt, letter logits from the unmodified `lm_head`.
245
+ - **Base model, same readout** — Qwen3.8-27B with no adapter, read through the same structured prompt shape as Solomon, letter logits from the unmodified `lm_head`. This is the like-for-like control.
246
+
247
+ **Accuracy, with a 95% bootstrap interval**
248
+
249
+ | Panel | Solomon | Base model, standard prompt | Base model, same readout |
250
+ |---|---|---|---|
251
+ | ARC-Challenge (n = 600) | 97.2% [95.8%–98.3%] | 97.0% [95.5%–98.3%] | 97.2% [95.7%–98.5%] |
252
+ | MMLU (n = 2,400) | 82.4% [80.9%–83.9%] | 82.5% [81.0%–84.0%] | 81.7% [80.3%–83.3%] |
253
+ | MMLU-Pro (n = 800) | 60.5% [57.1%–63.7%] | 62.3% [59.0%–65.5%] | 61.8% [58.4%–65.0%] |
254
+ | Fresh math (n = 190) | 55.8% [48.9%–63.2%] | 52.1% [45.3%–58.9%] | 43.7% [36.3%–50.5%] |
255
+ | Fresh math, multi-step only (n = 170) | 51.2% [43.5%–58.2%] | 46.5% [38.8%–54.1%] | 37.1% [30.0%–44.1%] |
256
+
257
+ **Expected calibration error — lower is better**
258
+
259
+ | Panel | Solomon | Base model, standard prompt | Base model, same readout |
260
+ |---|---|---|---|
261
+ | ARC-Challenge (n = 600) | 0.022 | 0.007 | 0.028 |
262
+ | MMLU (n = 2,400) | 0.117 | 0.057 | 0.027 |
263
+ | MMLU-Pro (n = 800) | 0.190 | 0.063 | 0.059 |
264
+ | Fresh math (n = 190) | 0.063 | 0.063 | 0.050 |
265
+ | Fresh math, multi-step only (n = 170) | 0.076 | 0.070 | 0.056 |
266
+
267
+ **Errors stated at 0.99 or above — count, and share of that arm's errors**
268
+
269
+ | Panel | Solomon | Base model, standard prompt | Base model, same readout |
270
+ |---|---|---|---|
271
+ | ARC-Challenge (n = 600) | 4 (23.5% of 17) | 1 (5.6% of 18) | 1 (5.9% of 17) |
272
+ | MMLU (n = 2,400) | 76 (18.0% of 423) | 30 (7.1% of 421) | 10 (2.3% of 439) |
273
+ | MMLU-Pro (n = 800) | 21 (6.6% of 316) | 9 (3.0% of 302) | 4 (1.3% of 306) |
274
+ | Fresh math (n = 190) | 0 (0.0% of 84) | 0 (0.0% of 91) | 0 (0.0% of 107) |
275
+ | Fresh math, multi-step only (n = 170) | 0 (0.0% of 83) | 0 (0.0% of 91) | 0 (0.0% of 107) |
276
+
277
+ **AUROC — how well the stated probability separates right answers from wrong ones**
278
+
279
+ | Panel | Solomon | Base model, standard prompt | Base model, same readout |
280
+ |---|---|---|---|
281
+ | ARC-Challenge (n = 600) | 0.946 | 0.966 | 0.887 |
282
+ | MMLU (n = 2,400) | 0.854 | 0.872 | 0.853 |
283
+ | MMLU-Pro (n = 800) | 0.847 | 0.850 | 0.844 |
284
+ | Fresh math (n = 190) | 0.845 | 0.764 | 0.782 |
285
+ | Fresh math, multi-step only (n = 170) | 0.818 | 0.704 | 0.716 |
286
+
287
+ On ARC-Challenge and MMLU, **accuracy is essentially the base model's**: every interval above overlaps. On the two fresh-math panels — items generated for this comparison and present in no public corpus — Solomon is **clearly ahead** of the base model read the same way (55.8% against 43.7%, and 51.2% against 37.1%), and ahead of it under a standard prompt as well.
288
+
289
+ **The calibration does not survive the trip.** On MMLU, Solomon's expected calibration error is **0.117** against **0.027** for the same base model read the same way, and 0.057 for the base model under a standard prompt. Solomon states 76 of its 423 errors at 0.99 or above; the base model on the same readout states 10 of 439. **MMLU-Pro is worse again** — 0.190 against 0.059, on lower accuracy (60.5% against 61.8%).
290
+
291
+ Read plainly: **this adapter makes the model more confident, and out of its own domain that confidence is not earned.** Solomon is MORE overconfident on general-knowledge questions than the model it is built on. The per-answer-type temperatures were fitted on structured document question-answering and they do not transfer; nothing here entitles a reader to carry the in-domain calibration results over to a general-knowledge population.
292
+
293
+ The ranking signal degrades more gently than the magnitude does: AUROC stays close to the base model's on every panel, and beats it on both fresh-math panels. An out-of-domain score is worth more as an ordering than as a probability — and in domain the same caution applies to the multi-candidate roll-up, below.
294
+
295
+ **How to read these numbers**
296
+
297
+ - NO TEMPERATURE IS APPLIED in these numbers: the scoring harness takes a plain softmax over the raw letter logits. The shipped serving path would not serve these items calibrated either -- the readout used here is `head_key` `single/choiceS`, which is not in the calibration artifact's map, and the loader REFUSES an unmapped `head_key` rather than assuming 1.0.
298
+ - These panels have no document. Solomon is a document question-answering model and every one of these items is a bare multiple-choice question, so this is out-of-domain by construction.
299
+ - The fresh-math panels use 10-option items, an option count outside the range the readout was developed on.
300
+ - The fresh-math items were generated for this comparison and are in no public corpus. Only top probability and correctness were retained for some arms there, so no Brier score is computed on those panels.
301
+ - 95% CIs are 2,000-resample item bootstraps.
302
+
303
+ ## Limitations
304
+
305
+ ### The synthetic-to-real gap
306
+
307
+ Everything above about documents is measured on generated documents. **One evaluation has ever been run
308
+ against real documents**, on a panel of 40 real documents and
309
+ 198 questions.
310
+
311
+ | | Whole-question agreement | Yes/no | Single | Ordered | Multi-label | Entity |
312
+ |---|---|---|---|---|---|---|
313
+ | **This model** | **0.8131** | 0.9750 | 1.0000 | 0.9500 | 0.7000 | 0.4359 |
314
+ | A previous training round, same panel | 0.8232 | 0.9750 | 1.0000 | 0.9750 | 0.7000 | 0.4615 |
315
+ | Questions | 198 | 40 | 39 | 40 | 40 | 39 |
316
+
317
+ Set that against ≈99% on the synthetic panel. **The gap is real, it is large, and it is concentrated in
318
+ entity and multi-label.** Slot accuracy on the earlier round was 0.8529; the
319
+ earlier round's whole-question agreement carries a 95% interval of
320
+ 0.7789–0.8629.
321
+
322
+ **The shipped model was measured on this panel and did not improve on it.** The difference against the
323
+ previous round is -1.0 points, 95% interval
324
+ [-3.0, +1.0], McNemar
325
+ p = 0.62 on 4
326
+ discordant questions. The two rounds are indistinguishable here. A round of training aimed specifically
327
+ at this failure did not move it.
328
+
329
+ **The dominant error.** The model answers **"No" where the adjudicated reference is "not
330
+ established"**, for candidates the document never mentions. Of the
331
+ 110 entity slots whose reference is "not
332
+ established", this model answers "No" on 57; the earlier
333
+ round answered "No" on 56 of the same
334
+ 110. The earlier round's analysis recorded it this way —
335
+ *B* is the "No" letter and *C* the "not established" letter:
336
+
337
+ > answers B (No) where adjudicated gold is C (not established) for entities/labels absent from the document: 60 of 94 wrong entity/multilabel slots; 25 of 33 wrong entity/multilabel questions are only this confusion
338
+
339
+ These are not marginal errors. The project's analysis of this panel records that the model stays
340
+ confident on exactly these slots, and that a round of training aimed at the failure left both the count
341
+ and the confidence essentially unchanged. If your questions ask about things that may simply be absent from the
342
+ document, this is the behaviour that will hurt you, and no released version of this model handles it
343
+ well.
344
+
345
+ Analysis of why the synthetic population does not transfer, recorded before the shipped model was
346
+ trained: synthetic documents state their own reading conventions and real ones do not; the synthetic
347
+ entity questions are about permissions while the real ones are about exclusive roles; and the
348
+ conventions for "mentioned in another role" differ between the two label sets.
349
+
350
+ ### What the real-document panel is, and is not
351
+
352
+ - The reference labels are **adjudicated agent labels** — two blind passes plus an adjudicator — not
353
+ human ground truth. The artifact records `reviewer: "agent"` and `human_verified: false`.
354
+ **No human has verified this panel.**
355
+ - The two blind passes did not agree with each other on the convention either. The artifact records:
356
+
357
+ > the two blind labelling passes disagreed on the same convention (entity agreement 0.786, multilabel 0.833 question-level)
358
+
359
+ So part of the measured gap may be a labelling-convention disagreement rather than a model error:
360
+
361
+ > 24 of the 60 slots are in document-referential questions ("named in the letter as ...") where No is defensible; 36 are substantive questions where the model contradicts its own prompt rule "A missing fact is not a negative fact"
362
+
363
+ - The shipped model's scores on this panel were produced by the project's paired evaluation harness on
364
+ the frozen design, not through the serving API in this repository. Temperature is a monotone
365
+ rescaling and cannot change which answer is on top, so accuracy carries; calibration on real
366
+ documents has not been measured at all.
367
+ - 40 documents and 198 questions is a small panel. Treat the per-type numbers as
368
+ indicative, not precise.
369
+
370
+ ### The rest
371
+
372
+ - **Out of domain, the probability magnitude is not trustworthy.** See the benchmark section: on
373
+ general knowledge this model is more overconfident than the base model it is built on.
374
+ - **The multi-candidate roll-up is an ordering, not a joint probability.** Read per-candidate values if
375
+ you need a magnitude.
376
+ - **Nothing here is a certified error rate.** No certification was run for this release and no
377
+ threshold is enforced anywhere on the serving path.
378
+ - **A confirmation run on the held-out synthetic panel did not happen** — its compute went to training.
379
+ The synthetic claim rests on the held-out panel above plus repeated paired panels.
380
+ - **No image modality claim.** Text only.
381
+ - **Yes/no above 0.99 is the least trustworthy high-confidence signal in the model.**
382
+
383
+ ## Training-data provenance
384
+
385
+ **No training document, panel, corpus or source text is distributed in this repository.**
386
+ The adapter was trained on synthetic documents, and some of those documents were produced by **editing
387
+ third-party natural texts**. Those texts are listed here so that their provenance is on the record, and
388
+ so that a reviewer doing lawful-sourcing diligence can see what was used without having to ask.
389
+
390
+ The model card discloses the provenance of the third-party texts the training panel was edited from, and attributes them. This is provenance disclosure and attribution as good practice, and it supports documented-lawful-sourcing procurement review. It is NOT a concession that the trained weights are a derivative work or an adaptation of those texts; that question is open and nothing in this package answers it.
391
+
392
+ 13 of the 42 reviewed sources were used in the training panel:
393
+
394
+ | | Source | URL | Licence, as recorded |
395
+ |---|---|---|---|
396
+ | | Django's security policies | [https://docs.djangoproject.com/en/dev/internals/security/](https://docs.djangoproject.com/en/dev/internals/security/) | BSD 3-Clause (Django project LICENSE, which covers the documentation in the django/django repository) |
397
+ | **CC BY-SA** | Wikipedia:Arbitration/Policy (English Wikipedia arbitration policy) | [https://en.wikipedia.org/wiki/Wikipedia:Arbitration/Policy](https://en.wikipedia.org/wiki/Wikipedia:Arbitration/Policy) | CC BY-SA 4.0 (Wikipedia text; attribution: English Wikipedia contributors, 'Wikipedia:Arbitration/Policy') |
398
+ | | Common Paper Mutual Non-Disclosure Agreement, Version 1.0 – Standard Terms | [https://commonpaper.com/standards/mutual-nda/1.0/](https://commonpaper.com/standards/mutual-nda/1.0/) | CC BY 4.0 (stated in the agreement footer and in the CommonPaper/Mutual-NDA repository README: 'free to use and modify under CC BY 4.0') |
399
+ | | 36 CFR Part 2 (National Park Service) - Resource Protection, Public Use and Recreation: sections 2.10, 2.13, 2.14, 2.15, 2.16, 2.21 and 2.22 | [https://www.ecfr.gov/current/title-36/chapter-I/part-2](https://www.ecfr.gov/current/title-36/chapter-I/part-2) | US Government work (public domain): Code of Federal Regulations text, not subject to copyright (17 U.S.C. 105) |
400
+ | | NSF Proposal & Award Policies & Procedures Guide (PAPPG, NSF 24-1), Chapter IV: Non-Award Decisions and Transactions | [https://www.nsf.gov/policies/pappg/24-1/ch-4-non-award-decisions-transactions](https://www.nsf.gov/policies/pappg/24-1/ch-4-non-award-decisions-transactions) | US Government work (public domain): U.S. National Science Foundation policy guide, not subject to copyright (17 U.S.C. 105) |
401
+ | | GOV.UK: Make a court claim for money | [https://www.gov.uk/api/content/make-court-claim-for-money](https://www.gov.uk/api/content/make-court-claim-for-money) | Open Government Licence v3.0 |
402
+ | | 42 CFR 68: NIH Loan Repayment Programs (2025 edition) | [https://www.govinfo.gov/content/pkg/CFR-2025-title42-vol1/xml/CFR-2025-title42-vol1-part68.xml](https://www.govinfo.gov/content/pkg/CFR-2025-title42-vol1/xml/CFR-2025-title42-vol1-part68.xml) | US Government work (public domain) |
403
+ | **CC BY-SA** | WordPress.com (Automattic) Terms of Service, last updated April 10, 2026 | [https://github.com/Automattic/legalmattic/blob/master/Terms%20of%20Service/WordPress.com/EN-Terms-of-Service.md](https://github.com/Automattic/legalmattic/blob/master/Terms%20of%20Service/WordPress.com/EN-Terms-of-Service.md) | CC BY-SA 4.0 (Automattic/legalmattic LICENSE.txt and README; the Terms themselves state they are available under a Creative Commons Sharealike license) |
404
+ | **CC BY-SA** | GitLab Handbook: Global Travel and Expense Policy (sections 1 to 3) | [https://handbook.gitlab.com/handbook/finance/expenses/](https://handbook.gitlab.com/handbook/finance/expenses/) | CC BY-SA 4.0 (GitLab handbook content; licence badge in the footer of handbook.gitlab.com pages) |
405
+ | | Sourcegraph Handbook: Spending company money | [https://github.com/sourcegraph/handbook/blob/main/content/benefits-pay-perks/benefits-perks/spending-company-money.md](https://github.com/sourcegraph/handbook/blob/main/content/benefits-pay-perks/benefits-perks/spending-company-money.md) | Apache License 2.0 (LICENSE of the public sourcegraph/handbook repository) |
406
+ | | Project Jupyter Governance: Executive Council | [https://raw.githubusercontent.com/jupyter/governance/main/docs/executive_council.md](https://raw.githubusercontent.com/jupyter/governance/main/docs/executive_council.md) | CC0 1.0 Universal (jupyter/governance repository LICENSE.md) |
407
+ | | 29 CFR 1904.30–1904.34: establishment records and annual summaries (2025 edition) | [https://www.govinfo.gov/content/pkg/CFR-2025-title29-vol5/xml/CFR-2025-title29-vol5-part1904.xml](https://www.govinfo.gov/content/pkg/CFR-2025-title29-vol5/xml/CFR-2025-title29-vol5-part1904.xml) | US Government work (public domain) |
408
+ | | 31 CFR 1.2, 1.4 and 1.6: Treasury FOIA requests and appeals (2025 edition) | [https://www.govinfo.gov/content/pkg/CFR-2025-title31-vol1/xml/CFR-2025-title31-vol1-part1.xml](https://www.govinfo.gov/content/pkg/CFR-2025-title31-vol1/xml/CFR-2025-title31-vol1-part1.xml) | US Government work (public domain) |
409
+
410
+ **3 of these are recorded as CC BY-SA 4.0** — *Wikipedia:Arbitration/Policy (English Wikipedia arbitration policy)*, *WordPress.com (Automattic) Terms of Service, last updated April 10, 2026*, *GitLab Handbook: Global Travel and Expense Policy (sections 1 to 3)*. Share-alike is the one term
411
+ attribution cannot cure. Whether a share-alike obligation can propagate through training into model
412
+ weights **is legally unsettled**; there is no authority settling it in either direction, and the
413
+ project's own licence review explicitly declines to infer one. The owner of this release
414
+ **accepted that residual risk on 2026-09-21 rather than resolving
415
+ it**, and kept this package under Apache-2.0. A reader should treat the question as open, not answered.
416
+
417
+ **On the strength of this evidence.** The licences above are **as recorded by the person who collected
418
+ each source**, from the source's own stated terms at the time of collection. The review records
419
+ `evidence_level: "authoring metadata assertion, not archived governing licence text"` and
420
+ `upstream_terms_independently_verified: false` for every row. No governing licence text was archived
421
+ alongside most of these sources, and this listing should not be read as a licence audit.
422
+
423
+ Listing these sources is **provenance disclosure and attribution as good practice**. It is not a
424
+ statement that the trained weights are a derivative work, an adaptation, or a copy of any of these
425
+ texts.
426
+
427
+
428
+ ## Third-party dependency licences
429
+
430
+ `requirements.lock` names the packages the serving layer needs. **None of them is redistributed in
431
+ this repository** — you install them yourself from their own publishers — so Apache-2.0 section 4(a)
432
+ imposes no bundled-notice obligation here and no dependency licence text is packaged. This summary
433
+ exists because a reviewer will ask for one.
434
+
435
+ Each licence in the table is the one declared in that distribution's OWN package metadata -- the `METADATA` file of an installed wheel -- read from a copy on the maintainer's machine. Where no copy existed, the row says NOT VERIFIED instead of guessing.
436
+
437
+ | Package | Pinned as | Licence, as declared by the distribution itself |
438
+ |---|---|---|
439
+ | `torch` | 2.13.0 | BSD-3-Clause — read from version 2.8.0 |
440
+ | `torchvision` | 0.28.0 | NOT VERIFIED |
441
+ | `transformers` | 5.17.0 | Apache 2.0 License |
442
+ | `flash-linear-attention` | 0.5.2 | NOT VERIFIED |
443
+ | `safetensors` | unpinned in the qualified image | Apache Software License — read from version 0.8.0 |
444
+ | `accelerate` | unpinned in the qualified image | Apache (Apache Software License) — read from version 1.15.0 |
445
+ | `numpy` | unpinned in the qualified image | BSD-3-Clause AND 0BSD AND MIT AND Zlib AND CC0-1.0 — read from version 2.5.3 |
446
+ | `scipy` | unpinned in the qualified image | BSD License (classifier); the METADATA `License` field carries the Enthought / SciPy Developers copyright line rather than an SPDX identifier — read from version 1.18.1 |
447
+ | `pillow` | unpinned in the qualified image | MIT-CMU — read from version 12.3.0 |
448
+
449
+ **Two rows say NOT VERIFIED and mean it.** A licence read from one installed version is evidence about that version only. Where the table names a version different from the pin, that is the version whose metadata was actually read, and the pinned version's own metadata could differ. Treat this table as a starting point for
450
+ your own review, not as a legal opinion, and re-check the distributions you actually install.
451
+
452
+ Full evidence paths for each row are in the release descriptor
453
+ (`release/solomon-release.json` → `dependency_licences`), which is not distributed; the same
454
+ information is repeated in the comments of `requirements.lock`.
455
+
456
+
457
+ ## Licence and attribution
458
+
459
+ Copyright 2026 Doccy Pty Ltd.
460
+
461
+ This repository is licensed **Apache-2.0** — the adapter and head weights, the calibration artifact,
462
+ the serving code and the documentation alike. See `LICENSE` and `NOTICE`.
463
+
464
+ It is a **derivative work** of `Qwen/Qwen3.8-27B`, Copyright 2026 Alibaba Cloud, licensed under Apache-2.0.
465
+ The upstream licence text is reproduced verbatim at `licenses/Qwen-Apache-2.0.txt` (sha256
466
+ `bbedc3fda3305820b977265f01b8619d87570a6739de3a5582c3464840f1e57a`). `NOTICE` carries the attribution required by section 4(c) and
467
+ `MODIFICATIONS.md` the statement of changes required by section 4(b).
468
+
469
+ No `NOTICE` file exists in the upstream repository at the pinned revision (HTTP 404, checked
470
+ 2026-09-18), so section 4(d) carries nothing forward and no upstream attribution text has been
471
+ invented.
472
+
473
+ "Qwen" and "Alibaba Cloud" are used nominatively to identify the base model. Apache-2.0 section 6
474
+ grants no trademark rights and none are claimed. No endorsement or affiliation is implied.
475
+
476
+ ## Verify what you downloaded
477
+
478
+ ```sh
479
+ shasum -a 256 adapter/adapter.safetensors # 2addaf841ecc58829ad73081603b8d3e52743c53c6d558a17a1dd30e9bd2dbca
480
+ shasum -a 256 adapter/heads.npz # 126a9b5487dca937a768a4f228f2d2e7d513900d8ad0e99c4137fbaa42a1aa6f
481
+ shasum -a 256 serving/readout-temperature-v2.json
482
+ # -> d6925a0168b2577d0e4d517cd25dd5ceb0b7cc8eee91b70aefd3a3aa9dcb64ce
483
+ ```
484
+
485
+ `MANIFEST.json` carries the size and sha256 of every file in this repository.
486
+
487
+ The calibration artifact has **two legitimate and different hashes**, and confusing them makes a sound
488
+ provenance chain look tampered with. `d6925a01…` is the *file* hash, what `shasum`
489
+ returns. `6506e239…` is the artifact's own internal `sha256` field, computed over its
490
+ contents with that field removed — a self-referential field cannot hash the file containing it. The
491
+ loader verifies the payload hash; use the file hash to check the file you were given. Both are recorded
492
+ in the serving binding's `provenance`, under those names.
493
+
494
+ ## Release record
495
+
496
+ Machine-readable identity for citation and pinning. The model identity, the calibration and the runtime
497
+ binding move together; pin by revision.
498
+
499
+ | | |
500
+ |---|---|
501
+ | Repository | `DoccyHealth/Solomon` |
502
+ | Release | `1.1.0`, 2026-09-21 |
503
+ | Serving contract | `solomon-v1` |
504
+ | Adapter sha256 | `2addaf841ecc58829ad73081603b8d3e52743c53c6d558a17a1dd30e9bd2dbca` |
505
+ | Heads sha256 | `126a9b5487dca937a768a4f228f2d2e7d513900d8ad0e99c4137fbaa42a1aa6f` |
506
+ | Base model | `Qwen/Qwen3.8-27B` at `1d4bf0f2ff6012fd82039f2fa52739d0dd7c60c0` |
507
+ | Runtime binding sha256 (payload) | `49904e27814e0ccfc483b0503237d84f8ca60a79713f393b23b0dbe57d87a6bf` |
508
+ | Calibration sha256 (file / payload) | `d6925a0168b2577d0e4d517cd25dd5ceb0b7cc8eee91b70aefd3a3aa9dcb64ce` / `6506e2394bda5f8e7c7b9742f70a5b8782efad53d5451d5d836ba3463cece24b` |
509
+ | Runtime fingerprint | `c3d933e068e19879b45fb6dc6ce4af83a4d22f615c263b209e15f9c4fb2ae952` |
510
+ | Readout | `four_collapsed` |
511
+ | Ruled temperatures | boolean 1.9476 · single 1.0 · ordered 1.5063 · multilabel 1.6895 · entity 2.1834 |
adapter/adapter.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2addaf841ecc58829ad73081603b8d3e52743c53c6d558a17a1dd30e9bd2dbca
3
+ size 870363376
adapter/config.json ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "adapter_bytes": 870363376,
3
+ "adapter_file": "adapter/adapter.safetensors",
4
+ "adapter_sha256": "2addaf841ecc58829ad73081603b8d3e52743c53c6d558a17a1dd30e9bd2dbca",
5
+ "answer_projection": "trained-semantic-head-float32",
6
+ "base_model_copyright": "2026 Alibaba Cloud",
7
+ "base_model_license": "Apache-2.0",
8
+ "base_model_name_or_path": "Qwen/Qwen3.8-27B",
9
+ "base_model_redistributed": false,
10
+ "base_model_revision": "1d4bf0f2ff6012fd82039f2fa52739d0dd7c60c0",
11
+ "calibration_artifact": "serving/readout-temperature-v2.json",
12
+ "calibration_file_sha256": "d6925a0168b2577d0e4d517cd25dd5ceb0b7cc8eee91b70aefd3a3aa9dcb64ce",
13
+ "calibration_fitted_on": {
14
+ "adapter_sha256": "2addaf841ecc58829ad73081603b8d3e52743c53c6d558a17a1dd30e9bd2dbca",
15
+ "trained_heads_sha256": "126a9b5487dca937a768a4f228f2d2e7d513900d8ad0e99c4137fbaa42a1aa6f"
16
+ },
17
+ "calibration_note": "a temperature is fitted on ONE model's logits. The loader refuses to serve these scalars on any adapter other than the one named in calibration_fitted_on. Serving at T = 1.0 everywhere is always permitted on any model.",
18
+ "calibration_payload_sha256": "6506e2394bda5f8e7c7b9742f70a5b8782efad53d5451d5d836ba3463cece24b",
19
+ "contract": "solomon-v1",
20
+ "copyright": "2026 Doccy Pty Ltd",
21
+ "design": {
22
+ "ordered": "S",
23
+ "single_choice": "R"
24
+ },
25
+ "dtype": "float32",
26
+ "heads_bytes": 2053938,
27
+ "heads_file": "adapter/heads.npz",
28
+ "heads_sha256": "126a9b5487dca937a768a4f228f2d2e7d513900d8ad0e99c4137fbaa42a1aa6f",
29
+ "license": "apache-2.0",
30
+ "lora_alpha": 64,
31
+ "measured_arithmetic": "fp32",
32
+ "measured_backend": "cuda",
33
+ "model_name": "Solomon",
34
+ "peft_type": "LORA",
35
+ "placement": "question",
36
+ "placement_note": "question-side: the adapter is OFF while the document prefix is prefilled and ON from the question branch onward. Applying it to the whole sequence gives a different model to the one that was measured.",
37
+ "r": 64,
38
+ "readout": "four_collapsed",
39
+ "runtime_fingerprint": "c3d933e068e19879b45fb6dc6ce4af83a4d22f615c263b209e15f9c4fb2ae952",
40
+ "schema": "solomon-adapter-config-v1",
41
+ "serving_binding": "serving/serving-binding.json",
42
+ "serving_binding_sha256": "49904e27814e0ccfc483b0503237d84f8ca60a79713f393b23b0dbe57d87a6bf",
43
+ "task_type": "FEATURE_EXTRACTION",
44
+ "version": "1.1.0"
45
+ }
adapter/heads.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:126a9b5487dca937a768a4f228f2d2e7d513900d8ad0e99c4137fbaa42a1aa6f
3
+ size 2053938
licenses/Qwen-Apache-2.0.txt ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Alibaba Cloud
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
requirements.lock ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Solomon -- runtime pins.
2
+ #
3
+ # These are the EXACT pins of the image the shipped weights were qualified and live-accepted on
4
+ # (one B200, CUDA, fp32 arithmetic). They are the image definition, not a resolved lock file:
5
+ # four packages were installed unpinned in the qualified image and their resolved versions were
6
+ # not captured at run time. They are listed below as unpinned, honestly, rather than guessed.
7
+ #
8
+ # Pinned in the qualified image:
9
+ torch==2.13.0 # observed at run time as 2.13.0+cu130; bound in the serving binding
10
+ torchvision==0.28.0
11
+ transformers==5.17.0
12
+ flash-linear-attention==0.5.2
13
+
14
+ # Installed UNPINNED in the qualified image; resolved versions were not recorded.
15
+ # Pin them yourself before relying on numerical reproducibility.
16
+ safetensors
17
+ accelerate
18
+ numpy
19
+ scipy
20
+ pillow
21
+
22
+ # Python 3.12.
23
+ #
24
+ # The serving binding (serving/serving-binding.json) records `torch: 2.13.0+cu130` among 15 runtime
25
+ # identity keys and REFUSES TO LOAD if the live engine differs on any of them. A different torch build
26
+ # will not silently serve different numbers; it will refuse.
27
+ #
28
+ # Not required for serving: the MLX path is not qualified and is not shipped.
29
+
30
+ # ---------------------------------------------------------------------------
31
+ # DEPENDENCY LICENCES
32
+ #
33
+ # None of these packages is redistributed in this repository. You install them from their own
34
+ # publishers, so Apache-2.0 4(a) imposes no bundled-notice obligation here and no dependency licence
35
+ # text is packaged. The summary below is provided because a reviewer will ask.
36
+ #
37
+ # Each licence is the one declared in that distribution's OWN package metadata, read from a copy on
38
+ # the maintainer's machine. Where no copy existed, the row says NOT VERIFIED rather than guessing.
39
+ # A licence read from one version is evidence about that version only.
40
+ #
41
+ # torch BSD-3-Clause — read from version 2.8.0
42
+ # evidence: .venv-probes/lib/python3.12/site-packages/torch-2.8.0.dist-info/METADATA, field `License: BSD-3-Clause`
43
+ # torchvision NOT VERIFIED
44
+ # evidence: NOT VERIFIED: no copy of torchvision exists anywhere in this project, so no licence statement is made here. Check the distribution you install.
45
+ # transformers Apache 2.0 License
46
+ # evidence: .venv/lib/python3.12/site-packages/transformers-5.17.0.dist-info/METADATA, field `License: Apache 2.0 License`
47
+ # flash-linear-attention NOT VERIFIED
48
+ # evidence: NOT VERIFIED: no copy of flash-linear-attention exists anywhere in this project, so no licence statement is made here. Check the distribution you install.
49
+ # safetensors Apache Software License — read from version 0.8.0
50
+ # evidence: .venv-reference/lib/python3.12/site-packages/safetensors-0.8.0.dist-info/METADATA, classifier `License :: OSI Approved :: Apache Software License`
51
+ # accelerate Apache (Apache Software License) — read from version 1.15.0
52
+ # evidence: .venv-reference/lib/python3.12/site-packages/accelerate-1.15.0.dist-info/METADATA, field `License: Apache`, classifier `License :: OSI Approved :: Apache Software License`
53
+ # numpy BSD-3-Clause AND 0BSD AND MIT AND Zlib AND CC0-1.0 — read from version 2.5.3
54
+ # evidence: .venv-reference/lib/python3.12/site-packages/numpy-2.5.3.dist-info/METADATA, field `License-Expression`
55
+ # scipy BSD License (classifier); the METADATA `License` field carries the Enthought / SciPy Developers copyright line rather than an SPDX identifier — read from version 1.18.1
56
+ # evidence: .venv/lib/python3.12/site-packages/scipy-1.18.1.dist-info/METADATA, classifier `License :: OSI Approved :: BSD License`
57
+ # pillow MIT-CMU — read from version 12.3.0
58
+ # evidence: .venv/lib/python3.12/site-packages/pillow-12.3.0.dist-info/METADATA, field `License-Expression: MIT-CMU`
59
+ #
60
+ # See README.md, "Third-party dependency licences".
serving/readout-temperature-v2.json ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "application": {
3
+ "by_head_key": {
4
+ "boolean/state4": "boolean",
5
+ "entity/state4": "entity",
6
+ "multilabel/state4": "multilabel",
7
+ "ordered/choiceS": "ordered",
8
+ "single/choiceR": "single"
9
+ },
10
+ "choice": {
11
+ "branches": "|R, |S (head_key single/choiceR, ordered/choiceS)",
12
+ "confidence": "the listed top-1 probability",
13
+ "expression": "probabilities = softmax(x[:n] / T)",
14
+ "note": "slice to the n listed options first, then divide by T. Reserved slots are never scored.",
15
+ "rule": "SLICE THEN TEMPER"
16
+ },
17
+ "granularity": "per task, which in this readout is EQUIVALENT to per head_key: every scored branch carries a head_key that already names its task, one to one. Index by head_key in the serving path. The paraphrase branch |bp reports boolean/state4 and takes the boolean temperature.",
18
+ "idempotence": "apply exactly once; the returned probability, the confidence and the listed top-1 all derive from the same tempered read.",
19
+ "note": "Nouls and choices are tempered DIFFERENTLY. The two forms agree at T = 1 and diverge above it; at the shipped boolean and entity temperatures the two readings differ by up to 0.123 in returned probability. Implement exactly as written.",
20
+ "noul": {
21
+ "branches": "|b, |bp, |E|j, |L|j (head_key boolean/state4, entity/state4, multilabel/state4)",
22
+ "confidence": "max(P(yes), 1 - P(yes))",
23
+ "expression": "z = x[0] - logsumexp(x[1:]); P(yes) = sigmoid(z / T)",
24
+ "note": "x is the full four-letter logit vector. Do NOT compute softmax(x / T)[0]: that is a four-way temper which decays toward 0.25, while the collapsed binary form decays toward 0.5. The collapsed binary form is what was fitted and what was validated.",
25
+ "rule": "COLLAPSE THEN TEMPER"
26
+ }
27
+ },
28
+ "derived_from_payload_sha256": "682d611ec53c3322905c7e265bf9b9b35a1cd581f6d8b7ea924df864a3d74278",
29
+ "fitted_on_model": {
30
+ "adapter_sha256": "2addaf841ecc58829ad73081603b8d3e52743c53c6d558a17a1dd30e9bd2dbca",
31
+ "trained_heads_sha256": "126a9b5487dca937a768a4f228f2d2e7d513900d8ad0e99c4137fbaa42a1aa6f"
32
+ },
33
+ "frozen": true,
34
+ "models": {
35
+ "boolean": {
36
+ "applied": true,
37
+ "fit_units": 2000,
38
+ "fitted_temperature": 1.947566230660407,
39
+ "head_key": "boolean/state4",
40
+ "kind": "noul",
41
+ "task": "boolean",
42
+ "temperature": 1.947566230660407,
43
+ "unit": "question"
44
+ },
45
+ "entity": {
46
+ "applied": true,
47
+ "fit_units": 16000,
48
+ "fitted_temperature": 2.1833931278263035,
49
+ "head_key": "entity/state4",
50
+ "kind": "noul",
51
+ "task": "entity",
52
+ "temperature": 2.1833931278263035,
53
+ "unit": "candidate noul"
54
+ },
55
+ "multilabel": {
56
+ "applied": true,
57
+ "fit_units": 9903,
58
+ "fitted_temperature": 1.689503561722502,
59
+ "head_key": "multilabel/state4",
60
+ "kind": "noul",
61
+ "task": "multilabel",
62
+ "temperature": 1.689503561722502,
63
+ "unit": "candidate noul"
64
+ },
65
+ "ordered": {
66
+ "applied": true,
67
+ "fit_units": 2000,
68
+ "fitted_temperature": 1.5063267793786488,
69
+ "head_key": "ordered/choiceS",
70
+ "kind": "choice",
71
+ "task": "ordered",
72
+ "temperature": 1.5063267793786488,
73
+ "unit": "question"
74
+ },
75
+ "single": {
76
+ "applied": false,
77
+ "fit_units": 2000,
78
+ "fitted_temperature": 1.4118967122943824,
79
+ "head_key": "single/choiceR",
80
+ "kind": "choice",
81
+ "task": "single",
82
+ "temperature": 1.0,
83
+ "unit": "question"
84
+ }
85
+ },
86
+ "schema": "solomon-readout-temperature-v2",
87
+ "sha256": "6506e2394bda5f8e7c7b9742f70a5b8782efad53d5451d5d836ba3463cece24b"
88
+ }
serving/selection.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "adapter_sha256": "2addaf841ecc58829ad73081603b8d3e52743c53c6d558a17a1dd30e9bd2dbca",
3
+ "binding": "serving-binding.json",
4
+ "contract": "solomon-v1",
5
+ "design": {
6
+ "ordered": "S",
7
+ "single_choice": "R"
8
+ },
9
+ "frozen": true,
10
+ "heads_sha256": "126a9b5487dca937a768a4f228f2d2e7d513900d8ad0e99c4137fbaa42a1aa6f",
11
+ "note": "readout mode, served design and the serving binding, named relative to this file. The binding pins the full runtime identity.",
12
+ "readout": "four_collapsed",
13
+ "readout_mode": "four_collapsed",
14
+ "schema": "solomon-selection-v1"
15
+ }
serving/service-export.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "contract": "solomon-v1",
3
+ "envelope": {
4
+ "confirmation_sha256": "8d0720109a1548e75a76f90509dc4669941ddee26694c0f4ba673f0ddef444f1",
5
+ "policy_sha256": "cbe6cc8af522ccd3bc5141d10c6dc2a8c95b061d67b4ebe50ababbf4c50e3819"
6
+ },
7
+ "note": "qualification envelope hashes. The serving binding carries the same `envelope` and the two are checked against each other at acceptance.",
8
+ "readout_mode": "four_collapsed",
9
+ "schema": "solomon-service-export-v1"
10
+ }
serving/serving-binding.json ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "answer_policy": "always_answers",
3
+ "contract": "solomon-v1",
4
+ "design": {
5
+ "ordered": "S",
6
+ "single_choice": "R"
7
+ },
8
+ "envelope": {
9
+ "confirmation_sha256": "8d0720109a1548e75a76f90509dc4669941ddee26694c0f4ba673f0ddef444f1",
10
+ "policy_sha256": "cbe6cc8af522ccd3bc5141d10c6dc2a8c95b061d67b4ebe50ababbf4c50e3819"
11
+ },
12
+ "prompts_sha256": null,
13
+ "provenance": {
14
+ "calibration_file_sha256": "d6925a0168b2577d0e4d517cd25dd5ceb0b7cc8eee91b70aefd3a3aa9dcb64ce",
15
+ "calibration_fitted_on": {
16
+ "adapter_sha256": "2addaf841ecc58829ad73081603b8d3e52743c53c6d558a17a1dd30e9bd2dbca",
17
+ "trained_heads_sha256": "126a9b5487dca937a768a4f228f2d2e7d513900d8ad0e99c4137fbaa42a1aa6f"
18
+ },
19
+ "calibration_payload_sha256": "6506e2394bda5f8e7c7b9742f70a5b8782efad53d5451d5d836ba3463cece24b",
20
+ "temperature_ruled_values": {
21
+ "boolean": 1.9476,
22
+ "entity": 2.1834,
23
+ "multilabel": 1.6895,
24
+ "ordered": 1.5063,
25
+ "single": 1.0
26
+ }
27
+ },
28
+ "readout": "four_collapsed",
29
+ "runtime": {
30
+ "adapter_sha256": "2addaf841ecc58829ad73081603b8d3e52743c53c6d558a17a1dd30e9bd2dbca",
31
+ "answer_engine_sha256": "23478f15c438f4b5201f4f3e817e2db95e92ad3353d796e18b6326d43916435b",
32
+ "answer_projection": "trained-semantic-head-float32",
33
+ "arithmetic": "fp32",
34
+ "backend": "cuda",
35
+ "base_engine_sha256": "760ca8b1a506528bff0a2ea4ce9c5638110b31195a3ac3e6f5adaca707ec13ce",
36
+ "base_fingerprint": "96d9bb24444a26769cc9fa626c73d29dc5396a1150bd0f1f751199e54cc2ff71",
37
+ "code_sha256": "898ea8cfce50fa19bd42bf2a115cc37d04d91fa0f9501220faec93a9821ca289",
38
+ "execution": "cached",
39
+ "model_sha256": "77042094076611b69791a610065f28b7013b8c621795fa86ddccc8bac7d1b9df",
40
+ "numerics": "fp32-attention-qblock128-fp64-recurrence-reference-v2",
41
+ "placement": "question",
42
+ "torch": "2.13.0+cu130",
43
+ "trained_heads_report_sha256": "0b3f4f92b63b7d91df21a012550869de865f8a303b342ee3001d9a5eddc75db4",
44
+ "trained_heads_sha256": "126a9b5487dca937a768a4f228f2d2e7d513900d8ad0e99c4137fbaa42a1aa6f"
45
+ },
46
+ "schema": "solomon-serving-binding-v1",
47
+ "sha256": "49904e27814e0ccfc483b0503237d84f8ca60a79713f393b23b0dbe57d87a6bf",
48
+ "temperatures": {
49
+ "application": {
50
+ "by_head_key": {
51
+ "boolean/state4": "boolean",
52
+ "entity/state4": "entity",
53
+ "multilabel/state4": "multilabel",
54
+ "ordered/choiceS": "ordered",
55
+ "single/choiceR": "single"
56
+ },
57
+ "choice": {
58
+ "branches": "|R, |S (head_key single/choiceR, ordered/choiceS)",
59
+ "confidence": "the listed top-1 probability",
60
+ "expression": "probabilities = softmax(x[:n] / T)",
61
+ "note": "slice to the n listed options first, then divide by T. Reserved slots are never scored.",
62
+ "rule": "SLICE THEN TEMPER"
63
+ },
64
+ "granularity": "per task, which in this readout is EQUIVALENT to per head_key: every scored branch carries a head_key that already names its task, one to one. Index by head_key in the serving path. The paraphrase branch |bp reports boolean/state4 and takes the boolean temperature.",
65
+ "idempotence": "apply exactly once; the returned probability, the confidence and the listed top-1 all derive from the same tempered read.",
66
+ "note": "Nouls and choices are tempered DIFFERENTLY. The two forms agree at T = 1 and diverge above it; at the shipped boolean and entity temperatures the two readings differ by up to 0.123 in returned probability. Implement exactly as written.",
67
+ "noul": {
68
+ "branches": "|b, |bp, |E|j, |L|j (head_key boolean/state4, entity/state4, multilabel/state4)",
69
+ "confidence": "max(P(yes), 1 - P(yes))",
70
+ "expression": "z = x[0] - logsumexp(x[1:]); P(yes) = sigmoid(z / T)",
71
+ "note": "x is the full four-letter logit vector. Do NOT compute softmax(x / T)[0]: that is a four-way temper which decays toward 0.25, while the collapsed binary form decays toward 0.5. The collapsed binary form is what was fitted and what was validated.",
72
+ "rule": "COLLAPSE THEN TEMPER"
73
+ }
74
+ },
75
+ "derived_from_payload_sha256": "682d611ec53c3322905c7e265bf9b9b35a1cd581f6d8b7ea924df864a3d74278",
76
+ "fitted_on_model": {
77
+ "adapter_sha256": "2addaf841ecc58829ad73081603b8d3e52743c53c6d558a17a1dd30e9bd2dbca",
78
+ "trained_heads_sha256": "126a9b5487dca937a768a4f228f2d2e7d513900d8ad0e99c4137fbaa42a1aa6f"
79
+ },
80
+ "frozen": true,
81
+ "models": {
82
+ "boolean": {
83
+ "applied": true,
84
+ "fit_units": 2000,
85
+ "fitted_temperature": 1.947566230660407,
86
+ "head_key": "boolean/state4",
87
+ "kind": "noul",
88
+ "task": "boolean",
89
+ "temperature": 1.947566230660407,
90
+ "unit": "question"
91
+ },
92
+ "entity": {
93
+ "applied": true,
94
+ "fit_units": 16000,
95
+ "fitted_temperature": 2.1833931278263035,
96
+ "head_key": "entity/state4",
97
+ "kind": "noul",
98
+ "task": "entity",
99
+ "temperature": 2.1833931278263035,
100
+ "unit": "candidate noul"
101
+ },
102
+ "multilabel": {
103
+ "applied": true,
104
+ "fit_units": 9903,
105
+ "fitted_temperature": 1.689503561722502,
106
+ "head_key": "multilabel/state4",
107
+ "kind": "noul",
108
+ "task": "multilabel",
109
+ "temperature": 1.689503561722502,
110
+ "unit": "candidate noul"
111
+ },
112
+ "ordered": {
113
+ "applied": true,
114
+ "fit_units": 2000,
115
+ "fitted_temperature": 1.5063267793786488,
116
+ "head_key": "ordered/choiceS",
117
+ "kind": "choice",
118
+ "task": "ordered",
119
+ "temperature": 1.5063267793786488,
120
+ "unit": "question"
121
+ },
122
+ "single": {
123
+ "applied": false,
124
+ "fit_units": 2000,
125
+ "fitted_temperature": 1.4118967122943824,
126
+ "head_key": "single/choiceR",
127
+ "kind": "choice",
128
+ "task": "single",
129
+ "temperature": 1.0,
130
+ "unit": "question"
131
+ }
132
+ },
133
+ "schema": "solomon-readout-temperature-v2",
134
+ "sha256": "6506e2394bda5f8e7c7b9742f70a5b8782efad53d5451d5d836ba3463cece24b"
135
+ }
136
+ }
src/solomon/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Solomon: a document plus structured questions in, one probability per decision out.
2
+
3
+ from solomon import service, api
4
+ layer = service.service(store, engine, selection='serving/selection.json')
5
+ server = api.serve(layer)
6
+
7
+ Reading order. `service` is the serving contract and the layer that reads the model's own letter logits.
8
+ `binding` is the identity check that refuses to serve a stack that is not the one that was measured, and
9
+ `calibration` the one positive scalar per answer type it carries. `semantics` and `reliability` are what a
10
+ probability means here; `readout` turns letter logits into one. `engine` is the served engine, built on
11
+ `engine_numerics` over `engine_cuda`; `heads` are the trained answer heads it reads through.
12
+ `engine_contract` and `engine_reference` hold the prompt blocks every answer type is asked with. The
13
+ `service_*` modules are the pinned chain the layer wraps, innermost first: `service_states`,
14
+ `service_checked`, `service_answers`, `service_heads`, `service_evidence`, `service_packages`, `serving`.
15
+
16
+ Every answer type is answered. There is no abstention on this path; see `service.ORDERING_DISCLOSURE`.
17
+ """
src/solomon/api.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Solomon HTTP surface for the Solomon layer (solomon/service.py). Named api.py, not http.py, so that running a
2
+ script from inside Solomon/ can never shadow the standard-library http package.
3
+
4
+ GET /health contract, readout mode, serving binding, runtime identity
5
+ POST /states {"state": text | object | parts} -> {"state_id", ...}
6
+ POST /v1/decide {"state" | "state_id", "questions", ...} -> {"answers", "usage", ...}
7
+ POST /states/<state_id>/decide {"questions", ...} -> same, reusing the saved state
8
+
9
+ v1.1: every question is answered. A decide response carries probabilities (one per candidate for entity and
10
+ multi-label questions) and an `ordering_score`; it never carries `abstain`, `confidence`, a threshold or anything
11
+ that reads as a certified error rate -- `solomon.service.decide` refuses to emit such a field. `ordering_score` is
12
+ uncalibrated and rank-only; `ordering_score_semantics` says so in every response and on /health.
13
+ """
14
+ import json
15
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
16
+
17
+ DECIDE_KEYS = {'state', 'state_id', 'questions', 'population', 'evidence', 'evidence_max_calls', 'evidence_detail', 'budget', 'model'}
18
+
19
+
20
+ def handler(service):
21
+ class Handler(BaseHTTPRequestHandler):
22
+ def log_message(self, *args):
23
+ pass
24
+
25
+ def reply(self, status, data):
26
+ raw = json.dumps(data).encode()
27
+ self.send_response(status)
28
+ self.send_header('Content-Type', 'application/json')
29
+ self.send_header('Content-Length', str(len(raw)))
30
+ self.end_headers()
31
+ self.wfile.write(raw)
32
+
33
+ def do_GET(self):
34
+ if self.path != '/health':
35
+ return self.reply(404, {'error': 'not found'})
36
+ return self.reply(200, service.health())
37
+
38
+ def do_POST(self):
39
+ try:
40
+ if self.headers.get('Origin'):
41
+ return self.reply(403, {'error': 'cross-origin requests unsupported'})
42
+ length = int(self.headers.get('Content-Length', '0'))
43
+ if not 0 < length <= 8_000_000:
44
+ raise ValueError('request body must be 1 to 8000000 bytes')
45
+ body = json.loads(self.rfile.read(length))
46
+ if not isinstance(body, dict):
47
+ raise ValueError('request body must be a JSON object')
48
+ path = self.path.strip('/').split('/')
49
+ if path == ['states']:
50
+ return self.reply(201, service.create(body.get('state', body.get('document'))))
51
+ if path == ['v1', 'decide'] or (len(path) == 3 and path[0] == 'states' and path[2] == 'decide'):
52
+ unknown = set(body) - DECIDE_KEYS
53
+ if unknown:
54
+ raise ValueError('unknown request fields: ' + ', '.join(sorted(unknown)))
55
+ body.pop('model', None) # some clients send a model name; one model is served here, so it is accepted and ignored
56
+ if len(path) == 3:
57
+ if 'state' in body or 'state_id' in body:
58
+ raise ValueError('state is given by the URL')
59
+ body['state_id'] = path[1]
60
+ return self.reply(200, service.decide(**body))
61
+ return self.reply(404, {'error': 'not found'})
62
+ except (ValueError, KeyError, TypeError) as exc:
63
+ return self.reply(400, {'error': str(exc)})
64
+ except FileNotFoundError:
65
+ return self.reply(404, {'error': 'state or input file not found'})
66
+ return Handler
67
+
68
+
69
+ def serve(service, host='127.0.0.1', port=0):
70
+ """Start a ThreadingHTTPServer (caller runs serve_forever / shutdown)."""
71
+ server = ThreadingHTTPServer((host, port), handler(service))
72
+ server.service = service
73
+ return server
src/solomon/binding.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Serving identity: which readout is served, and proof that it is the one that was measured.
2
+
3
+ Split out of `solomon/service.py` unchanged. Three things live here:
4
+
5
+ * the frozen selection file (readout mode, served design, where the binding is),
6
+ * the two-letter prompt identity, and
7
+ * `RuntimeBinding` -- the one safety property this release keeps. A binding carries the runtime identity
8
+ of the model that was scored, and every key of it must equal the live engine's or the service refuses
9
+ to load. The binding also carries the calibration, so a temperature cannot drift from the stack it was
10
+ fitted against, and it refuses a calibration fitted on a different model.
11
+ """
12
+ import copy
13
+ import hashlib
14
+ import importlib
15
+ import json
16
+ from pathlib import Path
17
+
18
+ from solomon.calibration import NoTemperature, ROOT, digest, load_temperature
19
+ from solomon.engine_contract import BOOLEAN_TASK, LABEL
20
+
21
+ SELECTION = ROOT / 'serving/selection.json'
22
+ DEFAULT_BINDING = ROOT / 'serving/serving-binding.json'
23
+ DESIGN_FREEZE = ROOT / 'serving/design-freeze.json'
24
+ CONTRACT = 'solomon-v1'
25
+ MODES = ('four_collapsed', 'two_letter')
26
+ BINDING_SCHEMA = 'solomon-serving-binding-v1'
27
+ # ------------------------------------------------------------------ selection and prompts
28
+ def load_selection(path=SELECTION):
29
+ """The frozen selection file -> {'mode', 'design', 'prompts', 'binding', 'sha256'}.
30
+
31
+ Accepted keys: 'readout', 'readout_mode' or 'mode' (four_collapsed | two_letter).
32
+ Optional: 'design' {single_choice, ordered} override, 'two_letter_prompts' (inline headers dict or
33
+ 'module:ATTRIBUTE'), 'binding' (path to the Solomon serving-binding.json: absolute, or relative to the
34
+ selection file's own directory, else to the project root).
35
+ """
36
+ path = Path(path)
37
+ if not path.exists():
38
+ raise ValueError(f'Solomon selection not found: {path} (pass mode= explicitly for development use)')
39
+ raw = json.loads(path.read_text())
40
+ mode = raw.get('readout') or raw.get('readout_mode') or raw.get('mode')
41
+ if mode not in MODES:
42
+ raise ValueError('selection.json names no readout mode (readout / readout_mode / mode)')
43
+ return {'mode': mode, 'design': raw.get('design'), 'prompts': raw.get('two_letter_prompts'), 'binding': raw.get('binding'),
44
+ 'sha256': hashlib.sha256(path.read_bytes()).hexdigest(), 'path': str(path), 'dir': str(path.resolve().parent)}
45
+
46
+
47
+ def default_design(mode):
48
+ """four_collapsed serves the frozen design (single R, ordered S); two_letter was trained on S rows only."""
49
+ if mode == 'two_letter':
50
+ return {'single_choice': 'S', 'ordered': 'S'}
51
+ frozen = json.loads(DESIGN_FREEZE.read_text()) if DESIGN_FREEZE.exists() else {'single_choice': 'R', 'ordered': 'S'}
52
+ return {'single_choice': frozen['single_choice'], 'ordered': frozen['ordered']}
53
+
54
+
55
+ class TwoLetterPrompts:
56
+ """Header swap four-state -> two-letter. headers: {'boolean': str, 'label': str, optional 'entity': str}.
57
+
58
+ The four-state block is HEADER + rest (question / label / answer cue); only HEADER changes, so a two-letter block
59
+ is byte-identical to what training used iff the training builder does the same swap (checked by `check_parity`).
60
+ """
61
+ FOUR = {'boolean': BOOLEAN_TASK, 'label': LABEL}
62
+
63
+ def __init__(self, headers):
64
+ if not isinstance(headers, dict) or not {'boolean', 'label'} <= set(headers) or set(headers) - {'boolean', 'label', 'entity'}:
65
+ raise ValueError('two-letter prompts need headers for boolean and label (optional entity)')
66
+ if any(not isinstance(v, str) or not v.strip() for v in headers.values()):
67
+ raise ValueError('two-letter headers must be nonempty strings')
68
+ if any(v.startswith(four) or four.startswith(v) for v in headers.values() for four in self.FOUR.values()):
69
+ raise ValueError('two-letter header must differ from the four-state headers')
70
+ self.headers = dict(headers)
71
+ self.sha256 = digest(self.headers)
72
+
73
+ def header(self, task, kind):
74
+ return self.headers.get('entity', self.headers['boolean']) if (kind == 'boolean' and task == 'entity') else self.headers[kind]
75
+
76
+ def rewrite(self, task, block):
77
+ """Four-state block -> (two-letter block, 2), or None when the block is not a four-state Noul block."""
78
+ for kind, four in self.FOUR.items():
79
+ if block.startswith(four) and (kind == 'label') == (task == 'multilabel') and task in ('boolean', 'entity', 'multilabel'):
80
+ return self.header(task, kind) + block[len(four):], 2
81
+ return None
82
+
83
+ def check_parity(self, rows):
84
+ """rows: two-letter training/eval rows {'task', 'block'} (Noul tasks). Returns mismatching row indices."""
85
+ bad = []
86
+ for i, row in enumerate(rows):
87
+ task, block = row['task'], row['block']
88
+ kind = 'label' if task == 'multilabel' else 'boolean'
89
+ head = self.header(task, kind)
90
+ if not block.startswith(head) or self.rewrite(task, self.FOUR[kind] + block[len(head):]) != (block, 2):
91
+ bad.append(i)
92
+ return bad
93
+
94
+
95
+ def load_prompts(spec):
96
+ """spec: None (solomon/prompts_two_letter.py, the headers the two-letter readout was trained on), inline headers dict, or 'module:ATTRIBUTE'."""
97
+ if spec is None:
98
+ from solomon import prompts_two_letter as p9
99
+ loaded = TwoLetterPrompts({'boolean': p9.BOOLEAN_TASK2, 'label': p9.LABEL2})
100
+ loaded.sha256 = hashlib.sha256(Path(p9.__file__).read_bytes()).hexdigest() # = the prompts_sha256 a two_letter binding pins
101
+ return loaded
102
+ if isinstance(spec, str):
103
+ module, _, attr = spec.partition(':')
104
+ spec = getattr(importlib.import_module(module), attr or 'TWO_LETTER_HEADERS')
105
+ return spec if isinstance(spec, TwoLetterPrompts) else TwoLetterPrompts(spec)
106
+
107
+
108
+ class UnboundServing:
109
+ """Development / no-binding-file path. Still answers everything; it simply claims no bound identity."""
110
+ status = 'unbound'
111
+ schema = None
112
+ sha256 = None
113
+
114
+ def __init__(self, reason='unbound: no Solomon serving binding is loaded'):
115
+ self.reason = reason
116
+ self.bound_keys = []
117
+ self.calibration = NoTemperature()
118
+
119
+ def describe(self):
120
+ return {'status': self.status, 'schema': None, 'sha256': None, 'bound_runtime_keys': [],
121
+ 'reason': self.reason, 'calibration': self.calibration.describe()}
122
+
123
+
124
+ class RuntimeBinding:
125
+ """The one safety property Solomon v1.1 keeps: the stack being served is the stack that was measured.
126
+
127
+ A `solomon-serving-binding-v1` artifact carries the runtime identity of the scored model (15 keys for this
128
+ release: every ServiceEngine identity key except the recomputed `fingerprint`). Every one of them must equal the
129
+ live engine identity or construction raises, so the service refuses to load on drift. It carries NO thresholds,
130
+ NO per-task status, NO temperatures and NO fitted correctness head: there is nothing here that could gate an
131
+ answer, because nothing gates an answer.
132
+ """
133
+ status = 'bound'
134
+ schema = BINDING_SCHEMA
135
+ # Without these two the binding would not pin the model at all; a binding that omits them is refused.
136
+ REQUIRED = ('adapter_sha256', 'trained_heads_sha256')
137
+ # Keys that must never appear in a serving binding: they are the machinery of the abstention path (v1.1).
138
+ # `temperatures` is deliberately NOT here -- a per-task scalar is a calibration parameter, not a decision, and
139
+ # carrying it inside the binding is what stops it drifting from the stack it was fitted against.
140
+ REFUSED = ('tasks', 'thresholds', 'confidence', 'correctness', 'abstention', 'policy', 'status')
141
+ # A temperature is fitted on ONE model's logits and is meaningless on another, even though the numbers would
142
+ # look identical. So a non-trivial calibration must record the model it was fitted on, and that model must be
143
+ # the one this binding serves.
144
+ CALIBRATION_BOUND_KEYS = ('adapter_sha256', 'trained_heads_sha256')
145
+
146
+ def __init__(self, binding, *, mode, runtime, design, prompts_sha256=None):
147
+ if not isinstance(binding, dict) or binding.get('schema') != BINDING_SCHEMA:
148
+ raise ValueError('Solomon serving binding schema required')
149
+ if binding.get('sha256') != digest({k: v for k, v in binding.items() if k != 'sha256'}):
150
+ raise ValueError('Solomon serving binding checksum mismatch')
151
+ present = [k for k in self.REFUSED if k in binding]
152
+ if present:
153
+ raise ValueError('serving binding carries removed abstention machinery: ' + ', '.join(present))
154
+ if binding.get('contract') not in (None, CONTRACT):
155
+ raise ValueError('Solomon serving binding was issued for a different serving contract: ' + str(binding.get('contract')))
156
+ if binding.get('readout') != mode:
157
+ raise ValueError('Solomon serving binding was built for a different readout mode')
158
+ bound = binding.get('runtime') or {}
159
+ if not isinstance(bound, dict) or any(k not in bound for k in self.REQUIRED):
160
+ raise ValueError('serving binding must bind at least ' + ', '.join(self.REQUIRED))
161
+ drift = sorted(k for k, v in bound.items() if runtime.get(k) != v)
162
+ if drift:
163
+ raise ValueError('Solomon serving binding runtime identity mismatch: ' + ', '.join(drift))
164
+ if binding.get('design') is not None and binding['design'] != design:
165
+ raise ValueError('Solomon serving binding design mismatch')
166
+ if mode == 'two_letter' and binding.get('prompts_sha256') != prompts_sha256:
167
+ raise ValueError('Solomon serving binding prompt identity mismatch')
168
+ self.binding = copy.deepcopy(binding)
169
+ self.sha256 = binding['sha256']
170
+ self.bound_keys = sorted(bound)
171
+ # Covered by this binding's checksum and by the identity check above, so the temperatures cannot drift
172
+ # from the runtime they were measured on.
173
+ self.calibration = load_temperature(binding.get('temperatures'))
174
+ provenance = binding.get('provenance') or {}
175
+ if self.calibration.file_sha256 is None: # embedded copy: take the file hash from the provenance
176
+ self.calibration.file_sha256 = provenance.get('calibration_file_sha256')
177
+ self._check_calibration_model(bound, provenance)
178
+
179
+ def _check_calibration_model(self, bound, provenance):
180
+ """Refuse a calibration inherited from a different model.
181
+
182
+ The 15-key identity check already proves the SERVING stack is the scored one. It cannot see this: a
183
+ temperature fitted on model A and copied onto a binding for model B has the same numbers and passes every
184
+ value check there is. The only thing that distinguishes them is which model's logits the scalars were
185
+ fitted against, so that has to be recorded and matched.
186
+ """
187
+ if self.calibration.is_identity():
188
+ return # T = 1.0 everywhere is a no-op; safe on any model
189
+ fitted = provenance.get('calibration_fitted_on') or {}
190
+ missing = [k for k in self.CALIBRATION_BOUND_KEYS if not fitted.get(k)]
191
+ if missing:
192
+ raise ValueError(
193
+ 'serving binding carries temperatures but no record of the model they were fitted on (missing '
194
+ + ', '.join('provenance.calibration_fitted_on.' + k for k in missing) + '). A temperature fitted '
195
+ 'on one model is meaningless on another, so an unattributed calibration is refused. Refit on this '
196
+ 'model, or serve at T = 1.0.')
197
+ for key in self.CALIBRATION_BOUND_KEYS:
198
+ if bound.get(key) != fitted[key]:
199
+ raise ValueError(
200
+ f'calibration was fitted on {key} {fitted[key]}, binding carries {key} {bound.get(key)}. '
201
+ 'Temperatures fitted on one model do not transfer to another even when the numbers match; '
202
+ 'refit on this model against the error-rich fit panel, or serve it at T = 1.0.')
203
+
204
+ def describe(self):
205
+ return {'status': self.status, 'schema': self.schema, 'sha256': self.sha256,
206
+ 'bound_runtime_keys': list(self.bound_keys), 'calibration': self.calibration.describe()}
207
+
208
+
209
+ def load_binding(path, *, mode, runtime, design, prompts_sha256=None):
210
+ """None / missing file -> UnboundServing; a present but invalid or drifted file fails closed (raises)."""
211
+ if isinstance(path, (UnboundServing, RuntimeBinding)) or hasattr(path, 'describe'):
212
+ return path
213
+ if isinstance(path, dict):
214
+ return RuntimeBinding(path, mode=mode, runtime=runtime, design=design, prompts_sha256=prompts_sha256)
215
+ path = Path(path) if path is not None else DEFAULT_BINDING
216
+ if not path.is_absolute():
217
+ path = ROOT / path
218
+ if not path.exists():
219
+ return UnboundServing(f'unbound: no Solomon serving binding at {path.relative_to(ROOT) if path.is_relative_to(ROOT) else path}')
220
+ return RuntimeBinding(json.loads(path.read_text()), mode=mode, runtime=runtime, design=design, prompts_sha256=prompts_sha256)
221
+
222
+
src/solomon/calibration.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The readout calibration: one positive scalar per answer type, and nothing else.
2
+
3
+ Split out of `solomon/service.py` unchanged. A temperature rescales a probability; it cannot reorder one,
4
+ so nothing here can decline an answer. `ReadoutTemperature` refuses an artifact that carries anything with
5
+ structure beyond the five scalars and the head_key map, which is what a smuggled decision rule would look
6
+ like.
7
+ """
8
+ import copy
9
+ import hashlib
10
+ import json
11
+ import math
12
+ from pathlib import Path
13
+
14
+ ROOT = Path(__file__).resolve().parents[2]
15
+
16
+ # Per-task readout temperature. Not a gate and not a decision: one positive scalar per task, applied to the logits
17
+ # before the softmax, which is the only parameter that fixes the MAGNITUDE of the returned probability. It cannot
18
+ # change any ranking (a positive temperature is monotone), so it cannot reintroduce abstention by another name.
19
+ TEMPERATURE_SCHEMA = 'solomon-readout-temperature-v2'
20
+ # v1 is accepted structurally so an older artifact still LOADS rather than crashing; which fit may actually SHIP
21
+ # is decided by the release tooling:RULED_TEMPERATURES, on values rather than on a version string.
22
+ TEMPERATURE_SCHEMAS = ('solomon-readout-temperature-v2', 'solomon-readout-temperature-v1')
23
+ TEMPERATURE = 1.0 # served when no calibration artifact is bound
24
+ TEMPERATURE_TASKS = ('boolean', 'entity', 'multilabel', 'single', 'ordered')
25
+ def digest(value):
26
+ return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(',', ':'), allow_nan=False).encode()).hexdigest()
27
+
28
+
29
+ class ReadoutTemperature:
30
+ """A frozen `solomon-readout-temperature-v1`: one positive scalar per task, nothing else.
31
+
32
+ This is a fitted artifact, and that is deliberate. The object removed from this path today was a
33
+ 5,125-parameter logistic regression over the full hidden state fitted on ~1 effective negative, whose
34
+ regularisation was chosen on a panel containing zero errors; it separated perfectly and did not replicate.
35
+ This is five scalars fitted on thousands of units, stable across the two disjoint fit panels, and it decides
36
+ nothing -- it rescales a number. The risk classes are not comparable. It is still bound by the runtime
37
+ identity like everything else, so it cannot drift from the stack it was measured on.
38
+
39
+ Application (must match abstention_refit/readout.py, which is what the scalars were fitted on):
40
+ Noul -> p_yes(t) = sigmoid(z/t) on the COLLAPSED binary logit z (solomon.semantics.p_yes)
41
+ Choice -> softmax(logits[:n]/t) over the listed options only (solomon.semantics.listed_probs)
42
+ """
43
+ # Nothing that could gate, rank-order differently, or make a certified claim may ride along with the scalars.
44
+ # Prose is fine: the artifact documents itself, and `application.noul.confidence` is a sentence describing
45
+ # what a caller reads off the tempered probability, not a fitted object. So a refused name is only refused
46
+ # when it carries STRUCTURE (numbers, arrays, objects) -- that is what a smuggled head would look like.
47
+ REFUSED = ('thresholds', 'threshold', 'weights', 'mean', 'scale', 'confidence', 'correctness',
48
+ 'feature_recipe', 'abstention', 'coverage', 'error_upper')
49
+ REFUSED_ANYWHERE = ('weights', 'thresholds', 'correctness', 'abstention')
50
+
51
+ def __init__(self, artifact, file_sha256=None):
52
+ if not isinstance(artifact, dict) or artifact.get('schema') not in TEMPERATURE_SCHEMAS:
53
+ raise ValueError('one of ' + ', '.join(TEMPERATURE_SCHEMAS) + ' required')
54
+ if artifact.get('frozen') is not True:
55
+ raise ValueError('readout temperature artifact must be frozen')
56
+ stated = artifact.get('sha256')
57
+ if stated != hashlib.sha256(json.dumps({k: v for k, v in artifact.items() if k != 'sha256'},
58
+ sort_keys=True, separators=(',', ':')).encode()).hexdigest():
59
+ raise ValueError('readout temperature checksum mismatch')
60
+ bad = sorted(_structural_keys(artifact) & set(self.REFUSED))
61
+ if bad:
62
+ raise ValueError('readout temperature artifact carries non-temperature machinery: ' + ', '.join(bad))
63
+ anywhere = sorted(_all_keys(artifact) & set(self.REFUSED_ANYWHERE))
64
+ if anywhere:
65
+ raise ValueError('readout temperature artifact names forbidden machinery: ' + ', '.join(anywhere))
66
+ if set(artifact) & set(self.REFUSED):
67
+ raise ValueError('readout temperature artifact carries a refused top-level field')
68
+ models = artifact.get('models') or {}
69
+ if set(models) != set(TEMPERATURE_TASKS):
70
+ raise ValueError('readout temperature needs exactly one model per task: ' + ', '.join(sorted(TEMPERATURE_TASKS)))
71
+ values = {}
72
+ for task, model in models.items():
73
+ t = model.get('temperature')
74
+ if isinstance(t, bool) or not isinstance(t, (int, float)) or not math.isfinite(t) or not 0 < t <= 20:
75
+ raise ValueError(f'{task}: temperature must be a finite scalar in (0, 20]')
76
+ values[task] = float(t)
77
+ self.artifact = copy.deepcopy(artifact)
78
+ self.values = values
79
+ # TWO DIFFERENT HASHES, and confusing them makes a sound provenance chain look tampered with:
80
+ # payload_sha256 -- the artifact's own `sha256` field, over its contents with that field removed. A
81
+ # self-referential field cannot hash the file containing it, so this is what it covers,
82
+ # and it is what this class verifies (above) and what survives being embedded in the
83
+ # serving binding, where there is no file at all.
84
+ # file_sha256 -- sha256 of the .json file on disk. This is what `shasum -a 256 <file>` returns and
85
+ # what a reader verifying the standalone artifact will compute. Known only when we
86
+ # loaded from a path; recorded in the binding's provenance either way.
87
+ self.payload_sha256 = stated
88
+ self.file_sha256 = file_sha256
89
+ # The artifact indexes by head_key, which is the field the runtime carries on every branch. The mapping to
90
+ # the five tasks is one-to-one, so a served branch whose head_key is not in the map is a readout the
91
+ # scalars were never fitted against (e.g. a different choice design) -- that must fail, not silently use 1.0.
92
+ self.by_head_key = dict((artifact.get('application') or {}).get('by_head_key') or {})
93
+ for key, task in self.by_head_key.items():
94
+ if task not in values:
95
+ raise ValueError(f'readout temperature by_head_key maps {key} to unknown task {task}')
96
+
97
+ def is_identity(self):
98
+ """All temperatures exactly 1.0: a no-op, and therefore safe on any model."""
99
+ return all(v == 1.0 for v in self.values.values())
100
+
101
+ def temperature(self, task, head_keys=()):
102
+ if task not in self.values:
103
+ raise ValueError(f'readout temperature has no scalar for task {task}')
104
+ for key in {k for k in head_keys if k}:
105
+ if self.by_head_key and key not in self.by_head_key:
106
+ raise ValueError(f'readout temperature was not fitted for head_key {key!r} (fitted: '
107
+ + ', '.join(sorted(self.by_head_key)) + '); refusing to serve it uncalibrated')
108
+ if self.by_head_key and self.by_head_key[key] != task:
109
+ raise ValueError(f'head_key {key!r} is calibrated for task {self.by_head_key[key]}, served as {task}')
110
+ return self.values[task]
111
+
112
+ def describe(self):
113
+ return {'schema': self.artifact['schema'], 'payload_sha256': self.payload_sha256,
114
+ 'file_sha256': self.file_sha256, 'per_task': dict(self.values),
115
+ 'by_head_key': dict(self.by_head_key),
116
+ 'applied': 'logits are divided by the task temperature before the softmax; Noul temperature '
117
+ 'applies to the collapsed binary logit (p_yes = sigmoid(z/T)), choice temperature to '
118
+ 'the listed options (softmax(logits[:n]/T)); applied exactly once per read'}
119
+
120
+
121
+ class NoTemperature:
122
+ """No calibration artifact bound: the readout is served raw at T = 1."""
123
+ payload_sha256 = None
124
+ file_sha256 = None
125
+
126
+ def is_identity(self):
127
+ return True
128
+
129
+ def temperature(self, task, head_keys=()):
130
+ return TEMPERATURE
131
+
132
+ def describe(self):
133
+ return {'schema': None, 'payload_sha256': None, 'file_sha256': None, 'per_task': {}, 'by_head_key': {},
134
+ 'applied': 'none: raw readout at T = 1'}
135
+
136
+
137
+ def load_temperature(source):
138
+ """None -> NoTemperature; a dict or a path -> ReadoutTemperature (invalid fails closed).
139
+
140
+ Loading from a path also records the file hash, which is what `shasum` returns; loading from a dict (the
141
+ embedded copy inside a serving binding) cannot know it, and the binding's provenance carries it instead.
142
+ """
143
+ if source is None:
144
+ return NoTemperature()
145
+ if hasattr(source, 'temperature'):
146
+ return source
147
+ if isinstance(source, dict):
148
+ return ReadoutTemperature(source)
149
+ path = Path(source)
150
+ if not path.is_absolute():
151
+ path = ROOT / path
152
+ if not path.exists():
153
+ raise ValueError(f'readout temperature artifact not found: {path}')
154
+ raw = path.read_bytes()
155
+ return ReadoutTemperature(json.loads(raw), file_sha256=hashlib.sha256(raw).hexdigest())
156
+
157
+
158
+ def _structural_keys(value):
159
+ """Keys anywhere in `value` whose own value is not a descriptive string (i.e. carries structure)."""
160
+ out = set()
161
+ if isinstance(value, dict):
162
+ for k, v in value.items():
163
+ if not isinstance(v, str):
164
+ out.add(k)
165
+ out |= _structural_keys(v)
166
+ elif isinstance(value, list):
167
+ for v in value:
168
+ out |= _structural_keys(v)
169
+ return out
170
+
171
+
172
+ def _all_keys(value):
173
+ if isinstance(value, dict):
174
+ return set(value) | (set().union(*(_all_keys(v) for v in value.values())) if value else set())
175
+ if isinstance(value, list):
176
+ return set().union(*(_all_keys(v) for v in value)) if value else set()
177
+ return set()
178
+
179
+
src/solomon/engine.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Question-only CUDA runtime for immutable semantic-head checkpoints."""
2
+ import copy
3
+ from contextlib import contextmanager
4
+ import hashlib
5
+ import json
6
+ from pathlib import Path
7
+ import threading
8
+ import numpy as np
9
+ from solomon.engine_numerics import CudaEngine
10
+ from solomon.heads import semantic_head_key
11
+
12
+ def sha(path):return hashlib.sha256(Path(path).read_bytes()).hexdigest()
13
+
14
+ class SolomonEngine(CudaEngine):
15
+ def __init__(self, adapter, heads_path, *, expected_adapter=None, expected_heads=None, correctness=None):
16
+ if expected_adapter and sha(adapter)!=expected_adapter:raise ValueError('adapter hash mismatch')
17
+ if expected_heads and sha(heads_path)!=expected_heads:raise ValueError('heads hash mismatch')
18
+ super().__init__(adapter=adapter,placement='question',mode='fp32')
19
+ self.base_identity=dict(self.identity)
20
+ with np.load(heads_path,allow_pickle=False) as arrays:
21
+ self.answer_heads={k[:-7]:{'weight':arrays[k].copy(),'bias':arrays[k[:-7]+'/bias'].copy()}
22
+ for k in arrays.files if k.endswith('/weight')}
23
+ if len(self.answer_heads)!=10:raise ValueError('all ten semantic heads required')
24
+ for head in self.answer_heads.values():
25
+ if head['weight'].shape!=(10,5120) or head['bias'].shape!=(10,) or not all(np.isfinite(v).all() for v in head.values()):
26
+ raise ValueError('invalid semantic head')
27
+ self.correctness_models=correctness or {}
28
+ self._task=None;self._lock=threading.RLock()
29
+ self.identity.update(trained_heads_sha256=sha(heads_path),answer_engine_sha256=sha(__file__),
30
+ answer_projection='trained-semantic-head-float32',base_fingerprint=self.base_identity['fingerprint'])
31
+ self.identity.pop('fingerprint',None)
32
+ self.identity['fingerprint']=hashlib.sha256(json.dumps(self.identity,sort_keys=True).encode()).hexdigest()
33
+
34
+ @contextmanager
35
+ def task_context(self,task):
36
+ with self._lock:
37
+ previous=self._task;self._task=task
38
+ try:yield self
39
+ finally:self._task=previous
40
+
41
+ def ask(self,state,block,n_letters,execution='cached',head_key=None,tap_layers=()):
42
+ with self._lock:
43
+ key=head_key or semantic_head_key(self._task,block)
44
+ if key not in self.answer_heads or not 2<=n_letters<=10:raise ValueError('unknown semantic head or width')
45
+ if execution not in ('cached','full'):raise ValueError('invalid execution')
46
+ torch=self.torch;p=state['prefix_tokens'];previous=self.ctx['start'];handles=[];taps={}
47
+ def hook(index):
48
+ def capture(module,args,output):
49
+ h=output[0] if isinstance(output,tuple) else output
50
+ # Intermediate states are normalized using the frozen final norm.
51
+ taps[str(index)]=self.lm.norm(h[:,-1:])[0,-1].detach().float().cpu().numpy().copy()
52
+ return capture
53
+ try:
54
+ for index in tap_layers:
55
+ if type(index)is not int or not 0<=index<len(self.lm.layers):raise ValueError('invalid layer tap')
56
+ handles.append(self.lm.layers[index].register_forward_hook(hook(index)))
57
+ with torch.inference_mode():
58
+ text=self._render(state['parts'],block);ids,embeds,pos,_=self._encode(state['parts'],text,state['features'])
59
+ if not torch.equal(ids[:,:p],state['prefix_ids']):raise ValueError('question prefix mismatch')
60
+ self.ctx['start']=0 if execution=='cached' else p
61
+ if execution=='cached':hidden=self.lm(inputs_embeds=embeds[:,p:],position_ids=pos[...,p:],past_key_values=copy.deepcopy(state['cache']),use_cache=True).last_hidden_state
62
+ else:hidden=self.lm(inputs_embeds=embeds,position_ids=pos,use_cache=False).last_hidden_state
63
+ head=self.answer_heads[key]
64
+ logits=torch.nn.functional.linear(hidden[:,-1].float(),torch.as_tensor(head['weight'],device=hidden.device),torch.as_tensor(head['bias'],device=hidden.device))[0,:n_letters]
65
+ probabilities=logits.softmax(-1).cpu().numpy()
66
+ feature=hidden[0,-1].float().cpu().numpy().copy()
67
+ return {'letter_logits':logits.cpu().numpy(),'probabilities':probabilities,'prediction':int(probabilities.argmax()),
68
+ 'hidden':feature,'taps':taps,'head_key':key,'mass':None,'top_is_letter':None,'mass_available':False,
69
+ 'execution':execution,'fallback':'','prompt_tokens':int(ids.shape[1]),'branch_tokens':int(ids.shape[1])-p,
70
+ 'input_tokens':int(ids.shape[1])-p,'reused_prefix_tokens':p if execution=='cached' else 0,'generation_tokens':0,
71
+ 'fingerprint':self.identity['fingerprint']}
72
+ finally:
73
+ self.ctx['start']=previous
74
+ for handle in handles:handle.remove()
75
+
76
+ def predict_correctness(self,task,branches):
77
+ from solomon.head_training import predict_correctness
78
+ if task not in self.correctness_models:return {'reliability':None}
79
+ hidden=[np.asarray(r['hidden'],float) for r in branches]
80
+ probs=[np.asarray(r['probabilities'],float) for r in branches]
81
+ feature=np.r_[np.mean(hidden,axis=0),min(float(p.max()) for p in probs),min(float(np.sort(p)[-1]-np.sort(p)[-2]) for p in probs),max(float(-np.sum(p*np.log(np.maximum(p,1e-300)))/np.log(len(p))) for p in probs),float(len(branches)),float(sum(len(p) for p in probs))]
82
+ return {'reliability':predict_correctness(self.correctness_models[task],feature)}
src/solomon/engine_contract.py ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The answer contract engine: contract v3 on the reference engine's float32 cached path.
2
+
3
+ Adds to solomon/engine_reference.py (which is not modified):
4
+ * a switchable LoRA layer, so an adapter can act on every token ('full', as the reference engine) or only on the
5
+ question branch ('question'): off while the document is prefilled, on for the branch, and in full
6
+ execution applied from the prefix boundary onward;
7
+ * documents made of parts: text and page images, in any order. The vision tower runs once per document,
8
+ the library's positions are used for the prefix, and the state carries the rope delta;
9
+ * task blocks for every answer type, and ten answer letters;
10
+ * state format v3.
11
+ """
12
+ import copy
13
+ import hashlib
14
+ import json
15
+ from pathlib import Path
16
+
17
+ import numpy as np
18
+
19
+ from solomon.engine_reference import (BOOLEAN_TASK, CHOICE_TASK, CHUNK, SYSTEM, TOKEN_CAP, Engine, Ledger, boolean_block, # noqa: F401
20
+ choice_block, dump, read_rows, sha, softmax)
21
+
22
+ ROOT = Path(__file__).resolve().parents[1]
23
+ MODEL = ROOT / 'runtime/qwen38-8bit'
24
+ ART = ROOT / 'artifacts/contract'
25
+ CONTRACT = 'solomon-answer-contract-v3'
26
+ STATE_FORMAT = 'solomon-answer-state-v3'
27
+ LETTERS = 'ABCDEFGHIJ'
28
+ PAGE = '<|vision_start|><|image_pad|><|vision_end|>'
29
+ IMAGE_PAD, VISION_END = '<|image_pad|>', '<|vision_end|>'
30
+ RESERVED = ['The document does not state this', 'The document gives conflicting answers']
31
+ NOT_STATED, CONFLICTING = 'not_stated', 'conflicting'
32
+
33
+ SINGLE_R = ('Task: choose the single option that the document establishes as the answer. If the document does not establish any of '
34
+ 'the other listed answers, choose the option that says it does not state this. If the document establishes two different '
35
+ 'listed answers and does not say which prevails, choose the option that says it gives conflicting answers. A replaced or '
36
+ 'withdrawn statement establishes nothing. Respond with exactly one letter. Do not explain.')
37
+ ORDERED_R = ('Task: the options form an ordered scale, lowest first, followed by two special options. Choose the single level that the '
38
+ 'document establishes. If the document does not establish any level, choose the option that says it does not state this. If '
39
+ 'it establishes two different levels and does not say which prevails, choose the option that says it gives conflicting '
40
+ 'answers. A replaced or withdrawn statement establishes nothing. Respond with exactly one letter. Do not explain.')
41
+ SINGLE_S = CHOICE_TASK
42
+ ORDERED_S = ('Task: the options form an ordered scale, lowest first. Choose the single level that the document best supports. '
43
+ 'Respond with exactly one letter. Do not explain.')
44
+ SUFFICIENCY = ('Task: classify what the document establishes about the answer to the question, using only the document. '
45
+ 'A = it establishes exactly one of the listed answers. B = it does not establish any of the listed answers. '
46
+ 'C = it establishes two or more different listed answers and does not say which prevails. '
47
+ 'A missing fact is not a negative fact. A replaced or withdrawn statement establishes nothing. '
48
+ 'Respond with exactly one letter: A, B, or C. Do not explain.')
49
+ LABEL = ('Task: decide whether the label applies, using only the document. A = the document establishes that it applies, and nothing in '
50
+ 'it establishes that it does not. B = the document establishes that it does not apply, and nothing in it establishes that it '
51
+ 'does. C = the document establishes neither. D = the document establishes both. A missing fact is not a negative fact. '
52
+ 'Evidence about another person or subject does not count. A replaced or withdrawn statement establishes nothing. '
53
+ 'Respond with exactly one letter: A, B, C, or D. Do not explain.')
54
+ OPTION = ('Task: decide whether the proposed answer is correct, using only the document. A = the document establishes this answer, and '
55
+ 'nothing in it establishes a different one. B = the document establishes a different answer, or establishes that this one is '
56
+ 'wrong, and nothing in it establishes this one. C = the document establishes neither. D = the document establishes both this '
57
+ 'answer and a different one. A missing fact is not a negative fact. A replaced or withdrawn statement establishes nothing. '
58
+ 'Respond with exactly one letter: A, B, C, or D. Do not explain.')
59
+
60
+
61
+ def _lettered(options):
62
+ return '\n'.join(f'{LETTERS[i]}. {text}' for i, text in enumerate(options))
63
+
64
+
65
+ def listwise_block(question, options, ordered=False, reserved=True):
66
+ """Caller options in caller order; with `reserved` the service appends the two reserved outcomes."""
67
+ if not 2 <= len(options) <= 8 or len(set(options)) != len(options):
68
+ raise ValueError('needs 2 to 8 distinct options')
69
+ shown = list(options) + (RESERVED if reserved else [])
70
+ task = (ORDERED_R if ordered else SINGLE_R) if reserved else (ORDERED_S if ordered else SINGLE_S)
71
+ return task + '\nQuestion: ' + question + '\nOptions:\n' + _lettered(shown) + '\nAnswer (one letter):', len(shown)
72
+
73
+
74
+ def sufficiency_block(question, options):
75
+ return SUFFICIENCY + '\nQuestion: ' + question + '\nListed answers:\n' + '\n'.join('- ' + o for o in options) + '\nAnswer (one letter):', 3
76
+
77
+
78
+ def label_block(question, label):
79
+ return LABEL + '\nQuestion: ' + question + '\nLabel: ' + label + '\nAnswer (one letter):', 4
80
+
81
+
82
+ def option_block(question, option):
83
+ return OPTION + '\nQuestion: ' + question + '\nProposed answer: ' + option + '\nAnswer (one letter):', 4
84
+
85
+
86
+ def four_state_block(question):
87
+ return boolean_block(question), 4
88
+
89
+
90
+ CTL = {'start': None} # None: adapter off. int s: adapter applied to positions >= s of the current call.
91
+
92
+
93
+ def _switch_lora_class():
94
+ import mlx.core as mx
95
+ import mlx.nn as nn
96
+
97
+ class SwitchLoRA(nn.Module):
98
+ def __init__(self, linear, lora_a, lora_b, scale):
99
+ super().__init__()
100
+ self.linear = linear
101
+ self.lora_a = lora_a
102
+ self.lora_b = lora_b
103
+ self.scale = scale
104
+
105
+ def __call__(self, x):
106
+ y = self.linear(x)
107
+ s = CTL['start']
108
+ if s is None or s >= x.shape[1]:
109
+ return y
110
+ xs = x if s <= 0 else x[:, s:]
111
+ z = (self.scale * ((xs @ self.lora_a) @ self.lora_b)).astype(y.dtype)
112
+ if s <= 0:
113
+ return y + z
114
+ return mx.concatenate([y[:, :s], y[:, s:] + z], axis=1)
115
+
116
+ return SwitchLoRA
117
+
118
+
119
+ def attach_adapter(lm, path, scale=2.0):
120
+ """Wrap the projections named in the adapter file. Returns (wrapped count, rank)."""
121
+ import mlx.core as mx
122
+ weights = mx.load(str(path))
123
+ cls = _switch_lora_class()
124
+ names = sorted({k.rsplit('.', 1)[0] for k in weights})
125
+ rank = None
126
+ for name in names:
127
+ parts = name.split('.') # model.layers.N.owner.key
128
+ owner = lm.model.layers[int(parts[2])]
129
+ for p in parts[3:-1]:
130
+ owner = getattr(owner, p)
131
+ a, b = weights[name + '.lora_a'].astype(mx.float32), weights[name + '.lora_b'].astype(mx.float32)
132
+ rank = a.shape[1]
133
+ setattr(owner, parts[-1], cls(getattr(owner, parts[-1]), a, b, scale))
134
+ lm.freeze()
135
+ mx.eval(lm.parameters())
136
+ return len(names), rank
137
+
138
+
139
+ def as_parts(document):
140
+ """A document is a string (text) or a list of parts {'text': str} / {'image': path}."""
141
+ if isinstance(document, str):
142
+ return [{'text': document}]
143
+ if not document or any(set(p) not in ({'text'}, {'image'}) for p in document):
144
+ raise ValueError('parts must be {"text": ...} or {"image": ...}')
145
+ return document
146
+
147
+
148
+ def document_key(document):
149
+ h = hashlib.sha256()
150
+ for p in as_parts(document):
151
+ h.update(b'T' + p['text'].encode() if 'text' in p else b'I' + bytes.fromhex(sha(p['image'])))
152
+ return h.hexdigest()
153
+
154
+
155
+ class ContractEngine(Engine):
156
+ def __init__(self, arithmetic='float32', ledger=None, adapter=None, placement='question'):
157
+ if placement not in ('question', 'full'):
158
+ raise ValueError('placement must be question or full')
159
+ super().__init__(arithmetic, ledger, adapter=None)
160
+ self.placement = placement
161
+ self.adapter = None
162
+ self.rank = None
163
+ if adapter is not None:
164
+ self.wrapped, self.rank = attach_adapter(self.lm, adapter)
165
+ self.adapter = str(adapter)
166
+ self._pad = self.t.convert_tokens_to_ids(IMAGE_PAD)
167
+
168
+ # ---- rendering -------------------------------------------------------------------
169
+ def _content(self, parts):
170
+ out = ''
171
+ for i, p in enumerate(parts):
172
+ if 'text' in p:
173
+ out += ('\n' if i and 'image' in parts[i - 1] else '') + p['text']
174
+ else:
175
+ out += ('\n' if i and 'text' in parts[i - 1] else '') + PAGE
176
+ return out
177
+
178
+ def _text(self, parts, block):
179
+ msgs = [{'role': 'system', 'content': SYSTEM}, {'role': 'user', 'content': 'Document:\n' + self._content(parts) + '\n\n' + block}]
180
+ return self.t.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True, enable_thinking=False)
181
+
182
+ def _expand(self, ids, counts):
183
+ out, k = [], 0
184
+ for tok in ids:
185
+ if tok == self._pad:
186
+ out += [tok] * counts[k]
187
+ k += 1
188
+ else:
189
+ out.append(tok)
190
+ if k != len(counts):
191
+ raise ValueError('image placeholder count differs from the number of images')
192
+ return out
193
+
194
+ def _pixels(self, parts):
195
+ from PIL import Image
196
+ images = [Image.open(p['image']).convert('RGB') for p in parts if 'image' in p]
197
+ if not images:
198
+ return None, None, []
199
+ out = self.processor.image_processor(images=images)
200
+ grid = np.array(out['image_grid_thw'])
201
+ merge = self.model.config.vision_config.spatial_merge_size ** 2
202
+ counts = [int(g[0] * g[1] * g[2]) // merge for g in grid]
203
+ return self.mx.array(np.array(out['pixel_values'])), self.mx.array(grid), counts
204
+
205
+ def _vision(self, pixels, grid):
206
+ """Vision tower one image at a time (memory stays flat for long scans)."""
207
+ mx = self.mx
208
+ dtype = self.model.vision_tower.patch_embed.proj.weight.dtype
209
+ feats, offset = [], 0
210
+ for i in range(grid.shape[0]):
211
+ n = int(np.prod(np.array(grid[i])))
212
+ h, _ = self.model.vision_tower(pixels[offset:offset + n].astype(dtype), grid[i:i + 1])
213
+ mx.eval(h)
214
+ feats.append(h)
215
+ offset += n
216
+ return mx.concatenate(feats, axis=0)
217
+
218
+ # ---- execution -------------------------------------------------------------------
219
+ def _forward(self, ids, pos, cache, embeds=None, chunk=CHUNK, adapter_from=None):
220
+ """Run ids through the language model; logits for the final position. adapter_from indexes into ids."""
221
+ mx = self.mx
222
+ n = len(ids)
223
+ if self.ledger is not None:
224
+ self.ledger.add(forwards=1, input_tokens=n)
225
+ step = n if chunk is None else chunk
226
+ if cache is None and step < n:
227
+ raise ValueError('Chunked execution needs a cache')
228
+ logits = None
229
+ for a in range(0, n, step):
230
+ b = min(a + step, n)
231
+ CTL['start'] = None if adapter_from is None else max(0, adapter_from - a)
232
+ kwargs = dict(cache=cache, position_ids=pos[:, :, a:b], skip_logits=True)
233
+ if embeds is not None:
234
+ kwargs['inputs_embeds'] = embeds[:, a:b]
235
+ if b == n:
236
+ out = self.lm(mx.array([ids[a:b]]), return_hidden=True, **kwargs)
237
+ lg = self.lm.lm_head(out.hidden_states[-1][:, -1:, :])[0, -1].astype(mx.float32)
238
+ mx.eval(lg)
239
+ logits = np.array(lg)
240
+ del out
241
+ else:
242
+ self.lm(mx.array([ids[a:b]]), **kwargs)
243
+ mx.eval([c.state for c in cache])
244
+ CTL['start'] = None
245
+ if not np.isfinite(logits).all():
246
+ raise ValueError('Non-finite model output')
247
+ if mx.get_peak_memory() > 100 * 2**30:
248
+ raise MemoryError('100 GiB MLX allocation cap exceeded')
249
+ return logits
250
+
251
+ def _positions(self, start, n):
252
+ mx = self.mx
253
+ return mx.broadcast_to(mx.arange(start, start + n)[None, None, :], (3, 1, n))
254
+
255
+ def prefill(self, document, chunk=CHUNK):
256
+ """Encode the task-neutral document prefix once. Returns state format v3."""
257
+ mx = self.mx
258
+ parts = as_parts(document)
259
+ text = self._text(parts, 'X')
260
+ end = text.rfind('\n\nX')
261
+ if end < 0:
262
+ raise ValueError('Document boundary missing')
263
+ raw = self.t.encode(text[:end], add_special_tokens=False)
264
+ if 'text' in parts[-1]:
265
+ raw = raw[:-1] # leave the boundary token uncached: its tokenisation can depend on what follows
266
+ pixels, grid, counts = self._pixels(parts)
267
+ ids = self._expand(raw, counts)
268
+ if not ids or len(ids) > TOKEN_CAP:
269
+ raise ValueError(f'prefix of {len(ids)} tokens is empty or exceeds the {TOKEN_CAP}-token cap')
270
+ embeds, delta, feats = None, 0, None
271
+ if counts:
272
+ feats = self._vision(pixels, grid)
273
+ f = self.model.get_input_embeddings(mx.array([ids]), pixels, image_grid_thw=grid, cached_image_features=feats)
274
+ embeds, pos = f.inputs_embeds, f.position_ids
275
+ delta = int(np.array(f.rope_deltas).reshape(-1)[0])
276
+ if delta != int(np.array(pos).max()) + 1 - len(ids):
277
+ raise ValueError('rope delta disagrees with the prefix positions')
278
+ else:
279
+ pos = self._positions(0, len(ids))
280
+ cache = self.lm.make_cache()
281
+ self._forward(ids, pos, cache, embeds, chunk, adapter_from=0 if (self.adapter and self.placement == 'full') else None)
282
+ mx.clear_cache()
283
+ return {'format': STATE_FORMAT, 'prefix_ids': ids, 'cache': cache, 'rope_delta': delta, 'parts': parts,
284
+ 'image_tokens': int(sum(counts)), 'image_sha256': [sha(p['image']) for p in parts if 'image' in p],
285
+ 'layout': ''.join('T' if 'text' in p else 'I' for p in parts),
286
+ 'prefix_sha256': hashlib.sha256(json.dumps(ids).encode()).hexdigest(),
287
+ '_pixels': pixels, '_grid': grid, '_counts': counts, '_feats': feats}
288
+
289
+ def letters_for(self, text, n):
290
+ ids = self.t.encode(text, add_special_tokens=False)
291
+ out = []
292
+ for letter in LETTERS[:n]:
293
+ if letter not in self._letters:
294
+ ext = self.t.encode(text + letter, add_special_tokens=False)
295
+ if len(ext) != len(ids) + 1 or ext[:-1] != ids:
296
+ raise ValueError('Unstable answer-letter continuation')
297
+ self._letters[letter] = ext[-1]
298
+ out.append(self._letters[letter])
299
+ return out, ids
300
+
301
+ def ask(self, state, block, n_letters, execution='cached', full_chunk=None):
302
+ """Answer-letter distribution for one task block against a prefilled state."""
303
+ mx = self.mx
304
+ text = self._text(state['parts'], block)
305
+ letters, raw = self.letters_for(text, n_letters)
306
+ ids = self._expand(raw, state['_counts'])
307
+ prefix = state['prefix_ids']
308
+ P = len(prefix)
309
+ fallback = None
310
+ if ids[:P] != prefix:
311
+ execution, fallback = 'full', 'prefix token mismatch'
312
+ on = self.adapter is not None
313
+ if execution == 'cached':
314
+ branch = copy.deepcopy(state['cache'])
315
+ logits = self._forward(ids[P:], self._positions(P + state['rope_delta'], len(ids) - P), branch, chunk=None,
316
+ adapter_from=0 if on else None)
317
+ del branch
318
+ reused = P
319
+ else:
320
+ embeds = None
321
+ if state['_counts']:
322
+ f = self.model.get_input_embeddings(mx.array([ids]), state['_pixels'], image_grid_thw=state['_grid'],
323
+ cached_image_features=None if len(state['_counts']) <= 6 else state['_feats'])
324
+ embeds, pos = f.inputs_embeds, f.position_ids
325
+ else:
326
+ pos = self._positions(0, len(ids))
327
+ start = None if not on else (0 if self.placement == 'full' else P)
328
+ logits = self._forward(ids, pos, self.lm.make_cache() if full_chunk else None, embeds, full_chunk, adapter_from=start)
329
+ reused = 0
330
+ full = softmax(logits)
331
+ mx.clear_cache()
332
+ return {'letter_logits': logits[letters].astype(np.float64), 'probabilities': softmax(logits[letters]),
333
+ 'mass': float(full[letters].sum()), 'top_is_letter': int(logits.argmax()) in letters, 'execution': execution,
334
+ 'fallback': fallback, 'prompt_tokens': len(ids), 'reused_prefix_tokens': reused, 'branch_tokens': len(ids) - reused}
335
+
336
+
337
+ def identity(engine):
338
+ """Runtime fingerprint for state format v3. With question placement the adapter is not part of the state."""
339
+ from importlib.metadata import version
340
+ ip = engine.processor.image_processor
341
+ payload = {'contract': CONTRACT, 'state_format': STATE_FORMAT, 'system_sha256': hashlib.sha256(SYSTEM.encode()).hexdigest(),
342
+ 'arithmetic': engine.arithmetic, 'engine_sha256': sha(Path(__file__)), 'base_engine_sha256': sha(ROOT / 'solomon/engine_reference.py'),
343
+ 'model_config_sha256': sha(MODEL / 'config.json'),
344
+ 'image_processor': {'class': type(ip).__name__, 'config_sha256': sha(MODEL / 'preprocessor_config.json')
345
+ if (MODEL / 'preprocessor_config.json').exists() else None},
346
+ 'state_adapter': (engine.adapter and sha(engine.adapter)) if engine.placement == 'full' else None,
347
+ 'versions': {p: version(p) for p in ('mlx', 'mlx-vlm', 'transformers')}}
348
+ payload['fingerprint'] = hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()
349
+ payload['branch_adapter'] = engine.adapter and {'sha256': sha(engine.adapter), 'placement': engine.placement, 'rank': engine.rank}
350
+ return payload
src/solomon/engine_cuda.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CUDA contract-v3 engine. Separate identity; never presents itself as MLX.
2
+ Model dependencies import lazily. Mutable cache branches are always deep-copied.
3
+ """
4
+ import copy,hashlib,json
5
+ from pathlib import Path
6
+
7
+ class CudaEngine:
8
+ def __init__(self,model_dir='base',adapter='adapter/adapter.safetensors',mode='fp32',placement='question'):
9
+ import torch
10
+ from torch import nn
11
+ from transformers import AutoModelForImageTextToText,AutoProcessor
12
+ from transformers.cache_utils import LinearAttentionLayer
13
+ from safetensors.torch import load_file
14
+ self.torch=torch;self.mode=mode;self.ctx={'start':None};self.adapter=adapter;self.placement=placement
15
+ torch.backends.cuda.matmul.allow_tf32=False
16
+ self.model=AutoModelForImageTextToText.from_pretrained(model_dir,dtype=torch.float32 if mode=='fp32' else torch.bfloat16,device_map='cuda',attn_implementation='sdpa').eval()
17
+ self.processor=AutoProcessor.from_pretrained(model_dir);self.t=self.processor.tokenizer;self.lm=self.model.model.language_model
18
+ def update(cache,recurrent_states,state_idx=0,**kwargs):
19
+ if not cache.is_recurrent_states_initialized[state_idx]:cache.lazy_initialization(recurrent_states=recurrent_states,state_idx=state_idx)
20
+ cache.recurrent_states[state_idx]=recurrent_states;return recurrent_states
21
+ LinearAttentionLayer.update_recurrent_state=update
22
+ if mode=='bf16-fp32-recurrence':
23
+ from transformers.models.qwen3_5 import modeling_qwen3_5 as modeling
24
+ for name in ('torch_chunk_gated_delta_rule','torch_recurrent_gated_delta_rule'):
25
+ original=getattr(modeling,name)
26
+ def promoted(q,k,v,*args,_original=original,**kwargs):
27
+ old=q.dtype
28
+ for key in ('g','beta','initial_state'):
29
+ if isinstance(kwargs.get(key),torch.Tensor):kwargs[key]=kwargs[key].float()
30
+ out,state=_original(q.float(),k.float(),v.float(),*args,**kwargs)
31
+ return out.to(old),state
32
+ setattr(modeling,name,promoted)
33
+ if adapter:
34
+ ctx=self.ctx;w=load_file(adapter)
35
+ class LoRA(nn.Module):
36
+ def __init__(self,linear,a,b):super().__init__();self.linear=linear;self.a=a.cuda().float();self.b=b.cuda().float()
37
+ def forward(self,x):
38
+ y=self.linear(x);s=ctx['start']
39
+ if s is None or s>=x.shape[1]:return y
40
+ z=(2*((x[:,s:].float()@self.a)@self.b)).to(y.dtype)
41
+ return y+z if s==0 else torch.cat((y[:,:s],y[:,s:]+z),dim=1)
42
+ for name in sorted({k.rsplit('.',1)[0] for k in w}):
43
+ parts=name.split('.');owner=self.lm.layers[int(parts[2])]
44
+ for p in parts[3:-1]:owner=getattr(owner,p)
45
+ setattr(owner,parts[-1],LoRA(getattr(owner,parts[-1]),w[name+'.lora_a'],w[name+'.lora_b']))
46
+ sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest()
47
+ self.identity={'backend':'cuda','execution':'cached','arithmetic':mode,'placement':placement,'model_sha256':sha(Path(model_dir)/'model.safetensors.index.json'),'adapter_sha256':sha(adapter) if adapter else None,'code_sha256':sha(__file__),'torch':torch.__version__}
48
+ self.identity['fingerprint']=hashlib.sha256(json.dumps(self.identity,sort_keys=True).encode()).hexdigest()
49
+
50
+ def _render(self,parts,block):
51
+ from solomon.engine_contract import SYSTEM,PAGE
52
+ content=''
53
+ for i,p in enumerate(parts):
54
+ if 'text' in p:content+= ('\n' if i and 'image' in parts[i-1] else '')+p['text']
55
+ else:content+= ('\n' if i and 'text' in parts[i-1] else '')+PAGE
56
+ return self.t.apply_chat_template([{'role':'system','content':SYSTEM},{'role':'user','content':'Document:\n'+content+'\n\n'+block}],tokenize=False,add_generation_prompt=True,enable_thinking=False)
57
+
58
+ def _encode(self,parts,text,features=None):
59
+ from PIL import Image
60
+ torch=self.torch
61
+ images=[Image.open(p['image']).convert('RGB') for p in parts if 'image' in p]
62
+ enc=self.processor(text=[text],images=images or None,return_tensors='pt',add_special_tokens=False).to('cuda')
63
+ ids=enc['input_ids'];embeds=self.model.get_input_embeddings()(ids)
64
+ if images:
65
+ if features is None:features=torch.cat(self.model.model.get_image_features(enc['pixel_values'],enc['image_grid_thw'],return_dict=True).pooler_output,dim=0)
66
+ features=features.to(embeds);mask,_=self.model.model.get_placeholder_mask(ids,inputs_embeds=embeds,image_features=features)
67
+ embeds=embeds.masked_scatter(mask,features)
68
+ pos,_=self.model.model.get_rope_index(ids,enc.get('mm_token_type_ids',torch.zeros_like(ids)),image_grid_thw=enc.get('image_grid_thw'),attention_mask=enc.get('attention_mask'))
69
+ return ids,embeds,pos,features
70
+
71
+ def prefill(self,document):
72
+ from solomon.engine_contract import as_parts
73
+ from transformers import DynamicCache
74
+ parts=as_parts(document);text=self._render(parts,'X');end=text.rfind('\n\nX')
75
+ raw=self.t.encode(text[:end],add_special_tokens=False)
76
+ if 'text' in parts[-1]:raw=raw[:-1]
77
+ with self.torch.inference_mode():
78
+ ids,embeds,pos,features=self._encode(parts,text)
79
+ p=len(raw)+ids.shape[1]-len(self.t.encode(text,add_special_tokens=False))
80
+ cache=DynamicCache(config=self.lm.config);self.ctx['start']=0 if self.adapter and self.placement=='full' else None
81
+ self.lm(inputs_embeds=embeds[:,:p],position_ids=pos[...,:p],past_key_values=cache,use_cache=True)
82
+ return {'parts':parts,'prefix_ids':ids[:,:p].clone(),'cache':cache,'features':features,'prefix_tokens':p}
83
+
84
+ def ask(self,state,block,n_letters,execution='cached'):
85
+ if execution not in ('cached','full'):raise ValueError('invalid execution')
86
+ torch=self.torch;text=self._render(state['parts'],block);raw=self.t.encode(text,add_special_tokens=False)
87
+ letters=[]
88
+ for c in 'ABCDEFGHIJ'[:n_letters]:
89
+ ext=self.t.encode(text+c,add_special_tokens=False)
90
+ if ext[:-1]!=raw or len(ext)!=len(raw)+1:raise ValueError('unstable answer continuation')
91
+ letters.append(ext[-1])
92
+ with torch.inference_mode():
93
+ ids,embeds,pos,_=self._encode(state['parts'],text,state['features']);p=state['prefix_tokens']
94
+ if not torch.equal(ids[:,:p],state['prefix_ids']):raise ValueError('prefix mismatch')
95
+ self.ctx['start']=(0 if execution=='cached' or self.placement=='full' else p) if self.adapter else None
96
+ if execution=='cached':hidden=self.lm(inputs_embeds=embeds[:,p:],position_ids=pos[...,p:],past_key_values=copy.deepcopy(state['cache']),use_cache=True).last_hidden_state
97
+ else:hidden=self.lm(inputs_embeds=embeds,position_ids=pos,use_cache=False).last_hidden_state
98
+ logits=self.model.lm_head(hidden[:,-1]).float()[0];choice=logits[letters];probs=choice.softmax(-1)
99
+ return {'letter_logits':choice.cpu().numpy(),'probabilities':probs.cpu().numpy(),'mass':float(logits.softmax(-1)[letters].sum()),'top_is_letter':int(logits.argmax()) in letters,'execution':execution,'fallback':'','prompt_tokens':int(ids.shape[1]),'branch_tokens':int(ids.shape[1])-p,'reused_prefix_tokens':p if execution=='cached' else 0}
src/solomon/engine_numerics.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Versioned CUDA repair: bounded FP32 attention, FP64 recurrent accumulation.
2
+ No changes to the deployed v1 engine or existing evidence.
3
+ """
4
+ import hashlib,inspect,json,textwrap
5
+ from pathlib import Path
6
+ from solomon.engine_cuda import CudaEngine as V1
7
+
8
+ def install_numerics():
9
+ import torch
10
+ from transformers.models.qwen3_5 import modeling_qwen3_5 as m
11
+ # Use the pinned readable reference implementation rather than FLA's FP32
12
+ # chunk solve. Output retains input dtype; only recurrence arithmetic is FP64.
13
+ for name in ('torch_chunk_gated_delta_rule','torch_recurrent_gated_delta_rule'):
14
+ original=inspect.unwrap(getattr(m,name))
15
+ source=textwrap.dedent(inspect.getsource(original))
16
+ source=source[source.index('def '):].replace('torch.float32','torch.float64')
17
+ namespace=dict(vars(m));exec(compile(source,'<qwen-fp64-reference>','exec'),namespace)
18
+ setattr(m,name,namespace[name])
19
+ def bounded(module,query,key,value,attention_mask,dropout=0.,scaling=None,**kwargs):
20
+ groups=query.shape[1]//key.shape[1]
21
+ key=m.repeat_kv(key,groups);value=m.repeat_kv(value,groups)
22
+ length=query.shape[-2];total=key.shape[-2];outputs=[]
23
+ for start in range(0,length,128):
24
+ end=min(length,start+128)
25
+ scores=query[...,start:end,:]@key.transpose(-2,-1)
26
+ scores=scores*(scaling if scaling is not None else query.shape[-1]**-.5)
27
+ if attention_mask is not None:
28
+ mask=attention_mask[...,start:end,:total] if attention_mask.shape[-2]!=1 else attention_mask[...,:total]
29
+ if mask.dtype==torch.bool:scores=scores.masked_fill(~mask,float('-inf'))
30
+ else:scores=scores+mask
31
+ elif getattr(module,'is_causal',False):
32
+ qpos=torch.arange(start,end,device=query.device)+total-length
33
+ kpos=torch.arange(total,device=query.device)
34
+ scores=scores.masked_fill(kpos[None,:]>qpos[:,None],float('-inf'))
35
+ probs=scores.softmax(-1)
36
+ outputs.append(probs@value)
37
+ return torch.cat(outputs,dim=-2).transpose(1,2).contiguous(),None
38
+ # Replace the decoder's existing SDPA interface. Vision retains its installed
39
+ # module interface only insofar as it also dispatches here; causal flag false
40
+ # gives ordinary dense vision attention without a causal mask.
41
+ m.ALL_ATTENTION_FUNCTIONS.register('sdpa',bounded)
42
+
43
+ class CudaEngine(V1):
44
+ def __init__(self,*args,**kwargs):
45
+ super().__init__(*args,**kwargs)
46
+ install_numerics()
47
+ self.identity['base_engine_sha256']=self.identity['code_sha256']
48
+ self.identity['code_sha256']=hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
49
+ self.identity['numerics']='fp32-attention-qblock128-fp64-recurrence-reference-v2'
50
+ self.identity.pop('fingerprint',None)
51
+ self.identity['fingerprint']=hashlib.sha256(json.dumps(self.identity,sort_keys=True).encode()).hexdigest()
src/solomon/engine_reasoning.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The confidence layer text reasoning on immutable answer-contract base-prefix states."""
2
+ import copy,hashlib,json
3
+ from pathlib import Path
4
+ from solomon.engine_numerics import CudaEngine
5
+
6
+ FORCE='\n</think>\n\nGive only the answer letter: '
7
+
8
+ def validate_request(state,n_letters,max_tokens):
9
+ if not isinstance(max_tokens,int) or isinstance(max_tokens,bool) or not 1<=max_tokens<=3072:raise ValueError('reasoning cap must be 1..3072')
10
+ if not isinstance(n_letters,int) or isinstance(n_letters,bool) or not 2<=n_letters<=10:raise ValueError('invalid letter count')
11
+ if any('image' in p for p in state['parts']):raise ValueError('the confidence layer reasoning confidence supports text only')
12
+
13
+ class ReasoningEngine(CudaEngine):
14
+ def reasoning_identity(self):
15
+ return {'base_runtime':self.identity,'reasoning_code_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),'adapter':'disabled','forced_suffix':FORCE}
16
+
17
+ def estimate(self,state,block,n,stage='fast',max_new_tokens=512):
18
+ if stage not in ('fast','reasoning'):raise ValueError('unknown stage')
19
+ if any('image' in p for p in state['parts']):raise ValueError('the confidence layer text-only budget estimator')
20
+ text=self._render(state['parts'],block)
21
+ if stage=='reasoning':
22
+ validate_request(state,n,max_new_tokens)
23
+ marker='<|im_start|>assistant\n'
24
+ if marker not in text:raise ValueError('unknown assistant template')
25
+ text=text[:text.rfind(marker)]+marker+'<think>\n'
26
+ ids=self.t.encode(text,add_special_tokens=False)
27
+ prefix=state['prefix_ids'][0].tolist()
28
+ if ids[:len(prefix)]!=prefix:raise ValueError('budget prefix mismatch')
29
+ extra=len(self.t.encode(FORCE,add_special_tokens=False)) if stage=='reasoning' else 0
30
+ return {'input_tokens':len(ids)-len(prefix)+extra,'generated_tokens':max_new_tokens if stage=='reasoning' else 0,'branches':1,'full_prompt_tokens':len(ids),'reused_prefix_tokens':len(prefix)}
31
+
32
+ def _reason_inputs(self,state,block):
33
+ text=self._render(state['parts'],block)
34
+ marker='<|im_start|>assistant\n'
35
+ if marker not in text:raise ValueError('unknown assistant template')
36
+ text=text[:text.rfind(marker)]+marker+'<think>\n'
37
+ ids,embeds,pos,_=self._encode(state['parts'],text,state['features'])
38
+ if not self.torch.equal(ids[:,:state['prefix_tokens']],state['prefix_ids']):raise ValueError('reasoning prefix mismatch')
39
+ return text,ids,embeds,pos
40
+
41
+ def reason(self,state,block,n_letters,max_tokens=512,execution='cached',replay_tokens=None,cap_checkpoints=None):
42
+ """Greedy base reasoning then bounded forced letter readout; replay is qualification only."""
43
+ validate_request(state,n_letters,max_tokens)
44
+ checkpoints=tuple(cap_checkpoints or ())
45
+ if any(not isinstance(c,int) or isinstance(c,bool) or not 1<=c<=max_tokens for c in checkpoints):raise ValueError('invalid cap checkpoints')
46
+ if checkpoints and (replay_tokens is not None or execution!='cached'):raise ValueError('checkpoints require cached generation')
47
+ if self.placement!='question':raise ValueError('reasoning needs base document state')
48
+ if execution not in ('cached','full'):raise ValueError('bad execution')
49
+ torch=self.torch;p=state['prefix_tokens'];previous=self.ctx['start']
50
+ from transformers import DynamicCache
51
+ try:
52
+ self.ctx['start']=None
53
+ with torch.inference_mode():
54
+ text,ids,embeds,pos=self._reason_inputs(state,block)
55
+ cache=copy.deepcopy(state['cache']) if execution=='cached' else DynamicCache(config=self.lm.config)
56
+ start=p if execution=='cached' else 0
57
+ h=self.lm(inputs_embeds=embeds[:,start:],position_ids=pos[...,start:],past_key_values=cache,use_cache=True).last_hidden_state
58
+ generated=[];snapshots={};stop='token_cap';lastpos=pos[...,-1:];close=self.t.encode('</think>',add_special_tokens=False)
59
+ eos=self.t.eos_token_id
60
+ for i in range(0 if execution=='full' and replay_tokens is not None else max_tokens):
61
+ token=int(replay_tokens[i]) if replay_tokens is not None and i<len(replay_tokens) else int(self.model.lm_head(h[:,-1]).argmax(-1))
62
+ if replay_tokens is not None and i>=len(replay_tokens):break
63
+ generated.append(token)
64
+ one=torch.tensor([[token]],device=ids.device);lastpos=lastpos+1
65
+ h=self.lm(input_ids=one,position_ids=lastpos,past_key_values=cache,use_cache=True).last_hidden_state
66
+ if len(generated) in checkpoints:
67
+ sf=self.t.encode(FORCE,add_special_tokens=False);sfids=torch.tensor([sf],device=ids.device)
68
+ sfpos=lastpos+torch.arange(1,len(sf)+1,device=ids.device).view(1,1,-1)
69
+ sh=self.lm(input_ids=sfids,position_ids=sfpos,past_key_values=copy.deepcopy(cache),use_cache=True).last_hidden_state
70
+ sl=self.model.lm_head(sh[:,-1]).float()[0]
71
+ li=[self.t.encode(c,add_special_tokens=False)[0] for c in 'ABCDEFGHIJ'[:n_letters]]
72
+ sc=sl[li];sp=sc.softmax(-1)
73
+ snapshots[str(len(generated))]={'letter_logits':sc.cpu().tolist(),'probabilities':sp.cpu().tolist(),'prediction':int(sp.argmax()),'mass':float(sl.softmax(-1)[li].sum()),'generation_tokens':len(generated),'finish_reason':'token_cap'}
74
+ if replay_tokens is None and (token==eos or generated[-len(close):]==close):stop='closed_reasoning' if token!=eos else 'eos';break
75
+ if execution=='full' and replay_tokens is not None:
76
+ generated=list(replay_tokens[:max_tokens]);lastpos=pos[...,-1:]+len(generated)
77
+ suffix=self.t.encode(FORCE,add_special_tokens=False);suffix_ids=torch.tensor([suffix],device=ids.device)
78
+ suffix_pos=lastpos+torch.arange(1,len(suffix)+1,device=ids.device).view(1,1,-1)
79
+ if execution=='full' and replay_tokens is not None:
80
+ extra=torch.tensor([generated+suffix],device=ids.device)
81
+ all_embeds=torch.cat((embeds,self.model.get_input_embeddings()(extra)),dim=1)
82
+ extra_pos=pos[...,-1:]+torch.arange(1,extra.shape[1]+1,device=ids.device).view(1,1,-1)
83
+ h=self.lm(inputs_embeds=all_embeds,position_ids=torch.cat((pos,extra_pos),dim=-1),use_cache=False).last_hidden_state
84
+ else:
85
+ h=self.lm(input_ids=suffix_ids,position_ids=suffix_pos,past_key_values=cache,use_cache=True).last_hidden_state
86
+ logits=self.model.lm_head(h[:,-1]).float()[0]
87
+ letter_ids=[]
88
+ for c in 'ABCDEFGHIJ'[:n_letters]:
89
+ token_ids=self.t.encode(c,add_special_tokens=False)
90
+ if len(token_ids)!=1:raise ValueError('non-single letter token')
91
+ letter_ids.append(token_ids[0])
92
+ chosen=logits[letter_ids];probs=chosen.softmax(-1)
93
+ return {'cap_checkpoints':snapshots,'letter_logits':chosen.cpu().tolist(),'probabilities':probs.cpu().tolist(),'mass':float(logits.softmax(-1)[letter_ids].sum()),'prediction':int(probs.argmax()),'generated_tokens':generated,'generation_tokens':len(generated),'text':self.t.decode(generated),'finish_reason':stop,'forced_answer':True,'execution':execution,'prompt_tokens':int(ids.shape[1]),'input_tokens':int(ids.shape[1])-p+len(suffix),'branch_tokens':int(ids.shape[1])-p+len(suffix),'reused_prefix_tokens':p if execution=='cached' else 0,'adapter_enabled':False,'identity':self.reasoning_identity()}
94
+ finally:self.ctx['start']=previous
95
+
96
+ def exit_features(self,state,block,n_letters,layers=(31,47,55)):
97
+ """Full-depth feature capture only; explicitly does not execute early exit."""
98
+ captured={};handles=[]
99
+ def hook(layer):
100
+ def capture(module,args,output):
101
+ value=output[0] if isinstance(output,tuple) else output
102
+ captured[layer]=value[:,-1].detach().clone()
103
+ return capture
104
+ try:
105
+ for layer in layers:handles.append(self.lm.layers[layer].register_forward_hook(hook(layer)))
106
+ full=self.ask(state,block,n_letters)
107
+ result={}
108
+ with self.torch.inference_mode():
109
+ text=self._render(state['parts'],block);raw=self.t.encode(text,add_special_tokens=False)
110
+ letter_ids=[self.t.encode(text+c,add_special_tokens=False)[-1] for c in 'ABCDEFGHIJ'[:n_letters]]
111
+ for layer,value in captured.items():
112
+ logits=self.model.lm_head(self.lm.norm(value)).float()[0,letter_ids]
113
+ result[str(layer)]={'feature':value.float().cpu().tolist()[0],'letter_logits':logits.cpu().tolist(),'prediction':int(logits.argmax())}
114
+ return {'full':{k:(v.tolist() if hasattr(v,'tolist') else v) for k,v in full.items()},'layers':result,'executed_truncated':False,'total_layers':len(self.lm.layers)}
115
+ finally:
116
+ for handle in handles:handle.remove()
src/solomon/engine_reference.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The reference engine: task-agnostic document prefix, float32 arithmetic, chunked prefill.
2
+
3
+ Contract v2
4
+ -----------
5
+ prefix = chat template(system=GENERIC, user="Document:\n" + document ...) <- cached once
6
+ branch = "\n\n" + task block (instructions, question, options, answer cue) + generation prompt
7
+
8
+ The document state therefore carries no task instructions: one state serves Boolean and
9
+ choice questions. Historical sources (qwen38/, decision_service/, backbone_comparison/) are
10
+ not modified.
11
+ """
12
+ import copy
13
+ import hashlib
14
+ import json
15
+ from pathlib import Path
16
+
17
+ import numpy as np
18
+
19
+ ROOT = Path(__file__).resolve().parents[1]
20
+ MODEL = ROOT / 'runtime/qwen38-8bit'
21
+ ART = ROOT / 'artifacts/reference'
22
+ CONTRACT = 'solomon-document-prefix-v2'
23
+ CLASSES = ['yes_only', 'no_only', 'neither', 'both']
24
+ LETTERS = 'ABCDEFGH'
25
+ CAPTURE_LAYERS = (31, 47, 55) # zero-based decoder layers; final normed state is always captured
26
+ CHUNK = 2048
27
+ TOKEN_CAP = 40960
28
+
29
+ SYSTEM = ('You answer questions about the supplied document. Use only the document. '
30
+ 'Task instructions follow the document; follow them exactly.')
31
+
32
+ BOOLEAN_TASK = ('Task: classify the evidence for the question using only the document and its explicit rules. '
33
+ 'A = Yes only. B = No only. C = neither Yes nor No is established. D = both Yes and No are established. '
34
+ 'A missing fact is not a negative fact. Evidence about another person or subject does not contradict '
35
+ 'the queried one. Apply explicit time and replacement rules before deciding. '
36
+ 'Respond with exactly one letter: A, B, C, or D. Do not explain.')
37
+
38
+ CHOICE_TASK = ('Task: choose the single option that the document best supports. '
39
+ 'Respond with exactly one letter. Do not explain.')
40
+
41
+
42
+ def sha(path):
43
+ return hashlib.sha256(Path(path).read_bytes()).hexdigest()
44
+
45
+
46
+ def dump(path, value):
47
+ path = Path(path)
48
+ path.parent.mkdir(parents=True, exist_ok=True)
49
+ tmp = path.with_suffix(path.suffix + '.tmp')
50
+ tmp.write_text(json.dumps(value, indent=2) + '\n')
51
+ tmp.replace(path)
52
+
53
+
54
+ def read_rows(path):
55
+ return [json.loads(s) for s in Path(path).read_text().splitlines() if s.strip()]
56
+
57
+
58
+ def softmax(a):
59
+ a = np.asarray(a, dtype=np.float64)
60
+ p = np.exp(a - a.max())
61
+ return p / p.sum()
62
+
63
+
64
+ def boolean_block(question):
65
+ return BOOLEAN_TASK + '\nQuestion: ' + question + '\nAnswer (one letter):'
66
+
67
+
68
+ def choice_block(question, options):
69
+ if not 2 <= len(options) <= len(LETTERS):
70
+ raise ValueError('Choice needs 2-8 options')
71
+ lines = [f'{LETTERS[i]}. {text}' for i, text in enumerate(options)]
72
+ return CHOICE_TASK + '\nQuestion: ' + question + '\nOptions:\n' + '\n'.join(lines) + '\nAnswer (one letter):'
73
+
74
+
75
+ def block_for(row):
76
+ """Task block and number of answer letters for a benchmark row."""
77
+ inp = row['input']
78
+ if row.get('task', 'boolean') == 'choice':
79
+ return choice_block(inp['question'], inp['options']), len(inp['options'])
80
+ return boolean_block(inp['question']), 4
81
+
82
+
83
+ def messages(document, block):
84
+ return [{'role': 'system', 'content': SYSTEM},
85
+ {'role': 'user', 'content': 'Document:\n' + document + '\n\n' + block}]
86
+
87
+
88
+ class Ledger:
89
+ def __init__(self, path, caps=None):
90
+ self.path = Path(path)
91
+ self.caps = caps or {}
92
+ self.counts = json.loads(self.path.read_text()) if self.path.exists() else {
93
+ 'forwards': 0, 'input_tokens': 0, 'generated_tokens': 0}
94
+
95
+ def add(self, forwards=0, input_tokens=0, generated_tokens=0):
96
+ c = self.counts
97
+ c['forwards'] += forwards
98
+ c['input_tokens'] += input_tokens
99
+ c['generated_tokens'] += generated_tokens
100
+ for key, cap in self.caps.items():
101
+ if c[key] > cap:
102
+ raise RuntimeError(f'Budget cap exceeded: {key} {c[key]} > {cap}')
103
+ dump(self.path, c)
104
+
105
+
106
+ class Engine:
107
+ def __init__(self, arithmetic='float32', ledger=None, adapter=None):
108
+ import mlx.core as mx
109
+ from mlx_vlm import load
110
+ if arithmetic not in ('float32', 'bfloat16'):
111
+ raise ValueError('arithmetic must be float32 or bfloat16')
112
+ self.mx = mx
113
+ self.arithmetic = arithmetic
114
+ self.model, self.processor = load(str(MODEL), trust_remote_code=False, local_files_only=True)
115
+ self.model.eval()
116
+ self.t = self.processor.tokenizer if hasattr(self.processor, 'tokenizer') else self.processor
117
+ self.lm = self.model.language_model
118
+ self.adapter = None
119
+ if adapter is not None:
120
+ from solomon.lora import apply_lora, load_adapter
121
+ apply_lora(self.lm)
122
+ load_adapter(self.lm, adapter)
123
+ self.adapter = str(adapter)
124
+ if arithmetic == 'float32':
125
+ # Same packed 8-bit weights; floating parameters and activations promoted.
126
+ self.model.apply(lambda x: x.astype(mx.float32) if mx.issubdtype(x.dtype, mx.floating) else x)
127
+ mx.eval(self.model.parameters())
128
+ mx.clear_cache()
129
+ self.ledger = ledger
130
+ self._letters = {}
131
+
132
+ # ---- rendering -------------------------------------------------------------------
133
+ def render(self, document, block):
134
+ text = self.t.apply_chat_template(messages(document, block), tokenize=False,
135
+ add_generation_prompt=True, enable_thinking=False)
136
+ return text, self.t.encode(text, add_special_tokens=False)
137
+
138
+ def prefix_ids(self, document):
139
+ """Token ids of the task-agnostic prefix: everything up to the end of the document."""
140
+ text, _ = self.render(document, 'X')
141
+ marker = '\n\nX'
142
+ end = text.rfind(marker)
143
+ if end < 0:
144
+ raise ValueError('Document boundary missing')
145
+ # Leave the boundary token uncached: its tokenisation can depend on what follows.
146
+ ids = self.t.encode(text[:end], add_special_tokens=False)[:-1]
147
+ if not ids:
148
+ raise ValueError('Empty prefix')
149
+ return ids
150
+
151
+ def letter_ids(self, text, ids, n):
152
+ out = []
153
+ for letter in LETTERS[:n]:
154
+ key = letter
155
+ if key not in self._letters:
156
+ ext = self.t.encode(text + letter, add_special_tokens=False)
157
+ if len(ext) != len(ids) + 1 or ext[:-1] != ids:
158
+ raise ValueError('Unstable answer-letter continuation')
159
+ self._letters[key] = ext[-1]
160
+ out.append(self._letters[key])
161
+ return out
162
+
163
+ # ---- execution -------------------------------------------------------------------
164
+ def _run(self, ids, cache, offset, capture, chunk=CHUNK):
165
+ """Process ids through the language model. Returns (last logits, {layer: vector})."""
166
+ mx = self.mx
167
+ if offset + len(ids) > TOKEN_CAP:
168
+ raise ValueError(f'{offset + len(ids)} tokens exceeds the {TOKEN_CAP}-token scope cap')
169
+ if self.ledger is not None:
170
+ self.ledger.add(forwards=1, input_tokens=len(ids))
171
+ n = len(ids)
172
+ step = n if chunk is None else chunk
173
+ if cache is None and step < n:
174
+ raise ValueError('Chunked execution needs a cache')
175
+ start = 0
176
+ logits = feats = None
177
+ while start < n:
178
+ stop = min(start + step, n)
179
+ last = stop == n
180
+ piece = mx.array([ids[start:stop]])
181
+ pos = mx.broadcast_to(mx.arange(offset + start, offset + stop)[None, None, :], (3, 1, stop - start))
182
+ kwargs = dict(cache=cache, position_ids=pos, skip_logits=True, return_hidden=True)
183
+ if last and capture:
184
+ kwargs['capture_layer_ids'] = list(CAPTURE_LAYERS)
185
+ out = self.lm(piece, **kwargs)
186
+ hidden = out.hidden_states
187
+ if last:
188
+ final = hidden[-1][:, -1:, :]
189
+ lg = self.lm.lm_head(final)[0, -1].astype(mx.float32)
190
+ vecs = {}
191
+ if capture:
192
+ for layer, h in zip(CAPTURE_LAYERS, hidden[:-1]):
193
+ vecs[layer] = h[0, -1].astype(mx.float32)
194
+ vecs['final'] = final[0, -1].astype(mx.float32)
195
+ mx.eval(lg, *vecs.values())
196
+ logits = np.array(lg)
197
+ feats = {k: np.array(v) for k, v in vecs.items()}
198
+ elif cache is not None:
199
+ mx.eval([c.state for c in cache])
200
+ del out, hidden
201
+ start = stop
202
+ if not np.isfinite(logits).all() or any(not np.isfinite(v).all() for v in feats.values()):
203
+ raise ValueError('Non-finite model output')
204
+ if mx.get_peak_memory() > 100 * 2**30:
205
+ raise MemoryError('100 GiB MLX allocation cap exceeded')
206
+ return logits, feats
207
+
208
+ def prefill(self, document, chunk=CHUNK):
209
+ """Encode the task-agnostic document prefix once."""
210
+ ids = self.prefix_ids(document)
211
+ cache = self.lm.make_cache()
212
+ mx = self.mx
213
+ if self.ledger is not None:
214
+ self.ledger.add(forwards=1, input_tokens=len(ids))
215
+ if len(ids) > TOKEN_CAP:
216
+ raise ValueError('Prefix exceeds scope cap')
217
+ start = 0
218
+ while start < len(ids):
219
+ stop = min(start + chunk, len(ids))
220
+ pos = mx.broadcast_to(mx.arange(start, stop)[None, None, :], (3, 1, stop - start))
221
+ self.lm(mx.array([ids[start:stop]]), cache=cache, position_ids=pos, skip_logits=True)
222
+ mx.eval([c.state for c in cache])
223
+ start = stop
224
+ mx.clear_cache()
225
+ return {'prefix_ids': ids, 'cache': cache}
226
+
227
+ def score(self, document, block, n_letters, state=None, capture=True, execution='cached', full_chunk=None):
228
+ """Answer-letter distribution (and features) for one task block."""
229
+ text, ids = self.render(document, block)
230
+ letters = self.letter_ids(text, ids, n_letters)
231
+ fallback = None
232
+ if execution == 'cached':
233
+ if state is None:
234
+ raise ValueError('cached execution needs a prefilled state')
235
+ prefix = state['prefix_ids']
236
+ if ids[:len(prefix)] != prefix:
237
+ execution, fallback = 'full', 'prefix token mismatch'
238
+ if execution == 'cached':
239
+ branch = copy.deepcopy(state['cache'])
240
+ logits, feats = self._run(ids[len(prefix):], branch, len(prefix), capture, chunk=None)
241
+ del branch
242
+ reused = len(prefix)
243
+ elif full_chunk:
244
+ # Long prompts: unchunked float32 attention scores would not fit in memory. The whole
245
+ # prompt is still processed from scratch, in chunks at different split points.
246
+ logits, feats = self._run(ids, self.lm.make_cache(), 0, capture, chunk=full_chunk)
247
+ reused = 0
248
+ else:
249
+ logits, feats = self._run(ids, None, 0, capture, chunk=None)
250
+ reused = 0
251
+ full = softmax(logits)
252
+ self.mx.clear_cache()
253
+ return {'letter_logits': logits[letters].astype(np.float64), 'probabilities': softmax(logits[letters]),
254
+ 'mass': float(full[letters].sum()), 'top_token': int(logits.argmax()),
255
+ 'top_is_letter': int(logits.argmax()) in letters, 'features': feats,
256
+ 'execution': execution, 'fallback': fallback, 'prompt_tokens': len(ids),
257
+ 'reused_prefix_tokens': reused, 'branch_tokens': len(ids) - reused}
258
+
259
+ def generate(self, document, block, max_tokens=2048, thinking=True):
260
+ """Reasoning-enabled reference. Uses the library generator on the same contract."""
261
+ from mlx_vlm import stream_generate
262
+ text = self.t.apply_chat_template(messages(document, block), tokenize=False,
263
+ add_generation_prompt=True, enable_thinking=thinking)
264
+ pieces, last = [], None
265
+ for x in stream_generate(self.model, self.processor, prompt=text, max_tokens=max_tokens,
266
+ temperature=0., top_p=1., top_k=0, repetition_penalty=1.):
267
+ pieces.append(x.text)
268
+ last = x
269
+ n = getattr(last, 'generation_tokens', 0)
270
+ if self.ledger is not None:
271
+ self.ledger.add(generated_tokens=n)
272
+ return {'text': ''.join(pieces), 'generation_tokens': n,
273
+ 'finish_reason': getattr(last, 'finish_reason', None)}
274
+
275
+
276
+ def identity(engine):
277
+ """Runtime fingerprint for state handles: no task prompt inside it any more."""
278
+ from importlib.metadata import version
279
+ payload = {'contract': CONTRACT, 'system_sha256': hashlib.sha256(SYSTEM.encode()).hexdigest(),
280
+ 'arithmetic': engine.arithmetic, 'adapter': engine.adapter and sha(engine.adapter),
281
+ 'engine_sha256': sha(Path(__file__)), 'capture_layers': list(CAPTURE_LAYERS),
282
+ 'model_config_sha256': sha(MODEL / 'config.json'),
283
+ 'versions': {p: version(p) for p in ('mlx', 'mlx-vlm', 'transformers')}}
284
+ payload['fingerprint'] = hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()
285
+ return payload
src/solomon/evidence.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic source references and explicit evidence interventions.
2
+
3
+ Offsets count Python Unicode code points, never bytes. Candidate ranking is lexical
4
+ and is labelled as such; only an independent model callback supplies support scores.
5
+ Interventions re-encode edited source; an existing KV state cannot prove removal.
6
+ """
7
+ import hashlib
8
+ import re
9
+ from pathlib import Path
10
+
11
+
12
+ def digest(text):
13
+ return hashlib.sha256(text.encode()).hexdigest()
14
+
15
+
16
+ def passages(text, max_chars=1200):
17
+ if not isinstance(text,str) or max_chars < 1:
18
+ raise ValueError('text and positive passage size required')
19
+ result=[]
20
+ # Cover every character, including whitespace; splitting does not normalize text.
21
+ start=0
22
+ while start < len(text):
23
+ limit=min(len(text),start+max_chars)
24
+ end=limit
25
+ if limit < len(text):
26
+ candidates=[m.end() for m in re.finditer(r'\n\s*\n|(?<=[.!?])\s+',text[start:limit])]
27
+ if candidates and candidates[-1] >= max_chars//2:end=start+candidates[-1]
28
+ result.append({'id':f'text:{start}:{end}','kind':'text','start':start,'end':end,
29
+ 'text':text[start:end],'source_sha256':digest(text)})
30
+ start=end
31
+ return result
32
+
33
+
34
+ def image_pages(paths):
35
+ return [{'id':f'page:{i+1}','kind':'image','page':i+1,'path':str(p),
36
+ 'source_sha256':hashlib.sha256(Path(p).read_bytes()).hexdigest()} for i,p in enumerate(paths)]
37
+
38
+
39
+ def validate_spans(text, spans):
40
+ ordered=sorted(spans,key=lambda s:(s['start'],s['end']))
41
+ last=0
42
+ for span in ordered:
43
+ start,end=span['start'],span['end']
44
+ if type(start) is not int or type(end) is not int or not 0<=start<end<=len(text) or start<last:
45
+ raise ValueError('invalid or overlapping evidence range')
46
+ if span.get('source_sha256',digest(text))!=digest(text) or span.get('text',text[start:end])!=text[start:end]:
47
+ raise ValueError('evidence no longer matches source')
48
+ last=end
49
+ return ordered
50
+
51
+
52
+ def rank_candidates(question, candidates, limit=8):
53
+ if limit<1:raise ValueError('positive candidate limit required')
54
+ tokens=set(re.findall(r'\w+',question.casefold()))
55
+ ranked=[]
56
+ for c in candidates:
57
+ words=set(re.findall(r'\w+',c.get('text','').casefold()))
58
+ ranked.append({**c,'candidate_score':len(words&tokens)/max(1,len(tokens)),
59
+ 'candidate_method':'lexical_overlap' if c['kind']=='text' else 'page_order'})
60
+ # Stable ties retain source order (page 2 must precede page 10).
61
+ return sorted(ranked,key=lambda c:-c['candidate_score'])[:limit]
62
+
63
+
64
+ def select(question, candidates, support_score, limit=8, minimum_support=.5):
65
+ """Callback receives only question+candidate, never benchmark gold."""
66
+ if not 0<=minimum_support<=1:raise ValueError('invalid support threshold')
67
+ results=[]
68
+ for candidate in rank_candidates(question,candidates,limit):
69
+ score=float(support_score(question,candidate))
70
+ if not 0<=score<=1:raise ValueError('finite support probability required')
71
+ results.append({**candidate,'support_score':score})
72
+ chosen=[r for r in results if r['support_score']>=minimum_support]
73
+ return {'evidence':chosen,'candidates':results,'verification':'model_support_only',
74
+ 'faithfulness_established':False,'no_support_found':not chosen}
75
+
76
+
77
+ def intervene(text, spans, question, decide):
78
+ """decide(document,question) must prefill each supplied document afresh.
79
+
80
+ All three actual calls are returned; agreement/disagreement is evidence, not a
81
+ guarantee that a passage is the unique cause of an answer.
82
+ """
83
+ spans=validate_spans(text,spans)
84
+ evidence='\n\n'.join(text[s['start']:s['end']] for s in spans)
85
+ pieces=[];start=0
86
+ for span in spans:
87
+ pieces.append(text[start:span['start']]);start=span['end']
88
+ pieces.append(text[start:]);removed=''.join(pieces)
89
+ full=decide(text,question)
90
+ only=decide(evidence,question)
91
+ removal=decide(removed,question)
92
+ return {'full':full,'evidence_only':only,'evidence_removed':removal,
93
+ 'evidence_only_agrees':only==full,'removal_changes_answer':removal!=full,
94
+ 'verification':'fresh_source_reencoding','source_sha256':digest(text),
95
+ 'evidence_sha256':digest(evidence),'removed_sha256':digest(removed),
96
+ 'calls':3,'input_characters':len(text)+len(evidence)+len(removed)}
97
+
98
+
99
+ def validate_pages(pages, selected):
100
+ """Validate ordered page manifests and selected immutable references."""
101
+ indexed = {}
102
+ for expected, page in enumerate(pages, 1):
103
+ if page.get('kind') != 'image' or type(page.get('page')) is not int or page['page'] != expected:
104
+ raise ValueError('image manifest must use consecutive source page IDs')
105
+ if page.get('id') != f'page:{expected}':
106
+ raise ValueError('image page ID does not match source position')
107
+ actual = hashlib.sha256(Path(page['path']).read_bytes()).hexdigest()
108
+ if page.get('source_sha256') != actual:
109
+ raise ValueError('image no longer matches source')
110
+ indexed[expected] = page
111
+ ids = []
112
+ for reference in selected:
113
+ number = reference.get('page')
114
+ if type(number) is not int or number not in indexed or number in ids:
115
+ raise ValueError('invalid or duplicate evidence page')
116
+ source = indexed[number]
117
+ if any(reference.get(key) != source[key] for key in ('id', 'kind', 'path', 'source_sha256')):
118
+ raise ValueError('evidence page no longer matches source manifest')
119
+ ids.append(number)
120
+ return [indexed[number] for number in sorted(ids)]
121
+
122
+
123
+ def intervene_pages(pages, selected, question, decide, text=''):
124
+ """Re-encode full, evidence-only and page-removed multimodal documents.
125
+
126
+ decide(text, image_paths, question) must create a fresh state each time and
127
+ accept an empty image list. Evidence-only has no accompanying source text;
128
+ removal retains all source text and unselected pages. This isolates page
129
+ evidence and makes text-only sufficiency a visible competing explanation.
130
+ Original page IDs are recorded because subset images are renumbered on input.
131
+ """
132
+ if not isinstance(text, str):
133
+ raise ValueError('source text must be a string')
134
+ selected = validate_pages(pages, selected)
135
+ selected_ids = {p['page'] for p in selected}
136
+ removed = [p for p in pages if p['page'] not in selected_ids]
137
+ calls = [(text, pages), ('', selected), (text, removed)]
138
+ answers = []
139
+ for source_text, source_pages in calls:
140
+ # Recheck all originals before each call: never silently mix revisions.
141
+ validate_pages(pages, selected)
142
+ answers.append(decide(source_text, [p['path'] for p in source_pages], question))
143
+ validate_pages(pages, selected)
144
+ full, only, removal = answers
145
+ return {'full': full, 'evidence_only': only, 'evidence_removed': removal,
146
+ 'evidence_only_agrees': only == full, 'removal_changes_answer': removal != full,
147
+ 'verification': 'fresh_source_reencoding', 'faithfulness_established': False,
148
+ 'source_text_sha256': digest(text),
149
+ 'source_pages': [{k: p[k] for k in ('id', 'page', 'source_sha256')} for p in pages],
150
+ 'evidence_page_ids': [p['page'] for p in selected],
151
+ 'removed_input_page_ids': [p['page'] for p in removed],
152
+ 'calls': 3, 'input_images': sum(len(p) for _, p in calls),
153
+ 'input_image_bytes': sum(Path(p['path']).stat().st_size for _, ps in calls for p in ps),
154
+ 'input_characters': 2 * len(text)}
src/solomon/evidence_packages.py ADDED
@@ -0,0 +1,423 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Evidence packages (v3): selected spans plus source-derived governing context, per question unit.
2
+
3
+ A package is a genuine subset of one source document: every range is an exact, validated slice
4
+ of the source (Python code-point offsets), rendered in source order with whitespace-only
5
+ separators. Nothing is paraphrased, summarised or generated. Context is attached by
6
+ question-independent document structure plus the unit's own selected spans and question text;
7
+ gold/authoring data is never an input.
8
+
9
+ Roles
10
+ evidence spans chosen by the selector (or, in oracle diagnostics, gold anchors). Span
11
+ precision/recall gates are computed on these only, exactly as before.
12
+ context ranges attached automatically, each with one or more reasons:
13
+ header document title block (identity of the source, author/compiler, date)
14
+ interpretation generic reading rules (solomon.retrieval.governing_context, unchanged regex)
15
+ locator container of an included span: message header line (date, author ->
16
+ recipient), minute number + heading, schedule/section heading, entry number
17
+ correction a withdrawal/rescission/deletion elsewhere that refers to the container of an
18
+ included statement and names the same subject and topic (or the exact entry)
19
+ withdrawn the statement(s) that an included withdrawal refers to, so the chain is
20
+ readable (the withdrawn text is marked by the withdrawal, not by us)
21
+ rule a general rule / band scale whose operative topic matches the unit question
22
+ (attached only when the unit has evidence)
23
+ exception the exception clause governing an included rule, or the rule an included
24
+ exception limits
25
+ definition the sentence defining a capitalised class term used by an included rule,
26
+ when it names the unit's subject
27
+ condition a statement about the unit's subject that bears on an included rule's
28
+ conditions or exception (>=2 shared content words beyond the question topic,
29
+ or one document-rare shared word)
30
+ convention the document's own reading conventions (sentences of the paragraphs that hold
31
+ generic reading rules) that the package needs: silence always; conflict and vocabulary when
32
+ there is evidence; removal when a withdrawal/deletion chain is present;
33
+ condition when a rule is present; exception when an exception is present
34
+
35
+ Size is measured as covered source characters / source characters and reported per package. A
36
+ package above the registered cap (default 0.30) sheds context in TRIM_ORDER (never evidence, rule,
37
+ exception, condition, correction or withdrawn context) and records what was trimmed.
38
+ """
39
+ import re
40
+ from solomon.evidence import digest, validate_spans
41
+ from solomon.retrieval import candidates, governing_context
42
+
43
+ SCHEMA = 'solomon-evidence-package-v3.1'
44
+ SIZE_CAP = .30
45
+ # Context dropped first when a package exceeds the size cap (evidence is never dropped).
46
+ TRIM_ORDER = ('interpretation', 'convention/silence', 'convention/vocabulary', 'convention/conflict', 'header', 'definition',
47
+ 'convention/condition', 'convention/exception', 'convention/removal', 'locator')
48
+ MONTHS = 'January|February|March|April|May|June|July|August|September|October|November|December'
49
+ _WORD = re.compile(r'\w+')
50
+ _CAP = re.compile(r"\b[A-Z][\w&'-]*")
51
+ _WITHDRAWAL = re.compile(r"withdr[ae]w|withdrawn|take back|disregard|rescind|retract|should not be relied|"
52
+ r"substituted|\bis deleted|\bdelete[sd]?\b|struck out|replaced by|no further effect", re.I)
53
+ _REF_DATE = re.compile(r'(?:message|wrote|written|letter|note)\D{0,14}?(\d{1,2} (?:' + MONTHS + r'))')
54
+ _REF_MINUTE = re.compile(r'\bminute (\d+)\b', re.I)
55
+ _REF_ENTRY = re.compile(r'\b[Ee]ntry (\d+) of [Ss]chedule (\d+)')
56
+ _MSG_HEAD = re.compile(r'Message \d+\. (\d{1,2} (?:' + MONTHS + r'))\.')
57
+ _MINUTE_HEAD = re.compile(r'(\d+)\.\s+[^.\n]{1,80}\.')
58
+ _SCHEDULE_HEAD = re.compile(r'SCHEDULE (\d+)\b')
59
+ _ENTRY_PREFIX = re.compile(r'[A-Z]?\d+(?:\.\d+)*\.?\s*')
60
+ _PERMISSION = re.compile(r'\bmay\b|permitted|authorised|entitled|leave to|allowed|cleared|confers?', re.I)
61
+ _RULE = re.compile(r"(?i:\b(?:any|each|every)\s+[a-z]+(?:\s+[a-z]+)?\s+(?:who|that)\b|\ban?\s+[a-z]+\s+who\b|general rule|standing rule|"
62
+ r"office rule|rule governing|\bif that\b|where one and the same|\b[a-z]+s who\b|\bwhere (?:an?|any|one)\b)|\b[A-Z][a-z]+ [A-Z][a-z]+s? (?:that|who)\b")
63
+ _SCALE = re.compile(r'\bbands?\b|\bscale\b|from lowest to highest|order of the levels|worked out from|fixed by that number|\bfewer than \d+', re.I)
64
+ _EXCEPTION = re.compile(r'does not apply|confers nothing on|is outside (?:clause|the rule)|not engaged|does not reach|switched off|'
65
+ r'disapplied|subject to (?:one|the) exception|nothing in the rule|save that|except (?:where|that|for)\b', re.I)
66
+ CONVENTIONS = {
67
+ 'removal': re.compile(r"withdr[ae]w|rescind|delet|substitut|struck out|take back|displace|disregard|\bspent\b|express(?:ly)? (?:withdrawal|rescission)", re.I),
68
+ 'condition': re.compile(r"\bconditions?\b|\blimbs?\b|requirements?\b|only part|part of the way|whole of it|each of its|all of its", re.I),
69
+ 'exception': re.compile(r"\bexcept", re.I),
70
+ 'conflict': re.compile(r"both (?:stand|remain|hold|are in force|left standing)|opposite (?:ways|things)|inconsistent|contradict|"
71
+ r"point opposite|not say which|not chosen between|this office does not say", re.I),
72
+ 'vocabulary': re.compile(r"interchangeabl|one and the same (?:permission|refusal)|are one (?:grant|refusal)|mean the same|same thing|words to like effect", re.I),
73
+ 'silence': re.compile(r"silen|absence of|unminuted|nothing has been decided|has not been said|undecided|left open", re.I)}
74
+ _DEFINES = re.compile(r'\bare\b|\bmeans\b|\bidentified\b|\binclude', re.I)
75
+ _STOP = {'this', 'that', 'these', 'those', 'with', 'under', 'which', 'what', 'does', 'file', 'correspondence', 'record', 'records',
76
+ 'recorded', 'minutes', 'agreement', 'bundle', 'messages', 'message', 'stand', 'stands', 'taking', 'reading', 'whole',
77
+ 'strength', 'position', 'open', 'given', 'have', 'been', 'applies', 'apply', 'entitled', 'allowed', 'liberty', 'free',
78
+ 'from', 'there', 'their', 'they', 'decisions', 'here', 'schedules', 'schedule', 'papers', 'office', 'shown', 'show',
79
+ 'shows', 'case', 'matters', 'terms', 'place', 'placed', 'about', 'question', 'whether', 'should', 'relied', 'either',
80
+ 'wrote', 'withdraw', 'withdrawn', 'passage', 'treat', 'nothing', 'follows', 'please', 'disregard', 'concerns', 'deals',
81
+ 'resolved', 'rescinded', 'much', 'decision', 'minute', 'further', 'effect', 'permission', 'permitted', 'refused',
82
+ 'barred', 'prohibited', 'authorised', 'cleared', 'leave', 'allows', 'allow', 'bars', 'refuses', 'grant', 'refusal',
83
+ 'entry', 'deleted', 'substituted', 'following', 'replaced', 'struck', 'committee', 'secretary', 'chair', 'principal'}
84
+ ROLES = ('evidence', 'context')
85
+ # Capitalised words that are never subject names (sentence openers, document furniture).
86
+ _NOT_NAMES = {'the', 'this', 'that', 'these', 'those', 'it', 'its', 'i', 'we', 'our', 'my', 'on', 'for', 'so', 'as', 'at', 'in', 'of',
87
+ 'please', 'treat', 'where', 'when', 'what', 'which', 'who', 'whether', 'any', 'each', 'every', 'no', 'nothing', 'there',
88
+ 'message', 'messages', 'entry', 'schedule', 'clause', 'minute', 'minutes', 'agreement', 'principal', 'resolved', 'note',
89
+ 'committee', 'secretary', 'chair', 'treasurer', 'register', 'records', 'record', 'permission', 'an', 'a', 'if', 'all',
90
+ 'both', 'neither', 'either', 'one', 'two', 'words', 'dates', 'decisions', 'rules', 'only', 'once', 'part', 'to', 'by',
91
+ 'read', 'do', 'what', 'should', 'with', 'from', 'under', 'after', 'before', 'reading', 'taking', 'is', 'has', 'have'}
92
+
93
+
94
+ def _words(s):
95
+ return set(_WORD.findall(s.casefold()))
96
+
97
+
98
+ def _topic(s, names=()):
99
+ low = {w for n in names for w in _words(n)}
100
+ return {w for w in _words(s) if len(w) >= 4 and w not in _STOP and w not in low and not w.isdigit()
101
+ and not re.fullmatch(MONTHS.casefold(), w)}
102
+
103
+
104
+ class Structure:
105
+ """Question-independent source structure: sentences, paragraphs, lines and containers."""
106
+
107
+ def __init__(self, text):
108
+ self.text = text
109
+ self.sentences = candidates(text)
110
+ self.paragraphs = []
111
+ start = 0
112
+ for m in list(re.finditer(r'\n\s*\n', text)) + [None]:
113
+ end = m.start() if m else len(text)
114
+ if text[start:end].strip():
115
+ self.paragraphs.append((start, end))
116
+ start = m.end() if m else len(text)
117
+ self.lines = [(m.start(), m.end()) for m in re.finditer(r'[^\n]+', text)]
118
+ df = {}
119
+ for s in self.sentences:
120
+ for w in _words(s['text']):
121
+ df[w] = df.get(w, 0) + 1
122
+ self.df = df
123
+ self.interpretation = [(s['start'], s['end']) for s in governing_context(text, self.sentences)]
124
+ # containers: message date -> paragraph; minute number -> paragraph; (schedule, entry) -> line
125
+ self.messages, self.minutes, self.entries = {}, {}, {}
126
+ for a, b in self.paragraphs:
127
+ first = text[a:b].split('\n', 1)[0]
128
+ m = _MSG_HEAD.match(first)
129
+ if m:
130
+ self.messages.setdefault(m.group(1), (a, b))
131
+ m = re.match(r'(\d+)\. ', text[a:b])
132
+ if m and '\n' not in text[a:b].strip():
133
+ self.minutes.setdefault(m.group(1), (a, b))
134
+ m = _SCHEDULE_HEAD.match(first)
135
+ if m:
136
+ for la, lb in self.lines:
137
+ if a <= la and lb <= b:
138
+ e = re.match(r'(\d+)\. ', text[la:lb])
139
+ if e:
140
+ self.entries[(m.group(1), e.group(1))] = (la, lb)
141
+ self.rules = [s for s in self.sentences if (_RULE.search(s['text']) and _PERMISSION.search(s['text'])) or _SCALE.search(s['text'])]
142
+ self.exceptions = [s for s in self.sentences if _EXCEPTION.search(s['text'])]
143
+ self.withdrawals = [s for s in self.sentences if _WITHDRAWAL.search(s['text'])]
144
+ # Reading conventions: sentences of the interpretation paragraphs (those holding a generic reading rule).
145
+ blocks = {self.paragraph_of(a) for a, _ in self.interpretation} - {None}
146
+ general = [s for s in self.sentences if self.paragraph_of(s['start']) in blocks and s not in self.rules]
147
+ self.conventions = {k: [(s['start'], s['end']) for s in general if rx.search(s['text'])] for k, rx in CONVENTIONS.items()}
148
+
149
+ def governed_rule(self, exception):
150
+ """The rule an exception limits: nearest preceding rule in the same paragraph (or the same sentence)."""
151
+ para = self.paragraph_of(exception['start'])
152
+ prior = [r for r in self.rules if r['start'] <= exception['start'] and para and para[0] <= r['start'] < para[1]
153
+ and not _SCALE.search(r['text'])]
154
+ return prior[-1] if prior else None
155
+
156
+ def names(self, s, limit=16):
157
+ """Capitalised tokens that are rare in this source (subject names); months/number words excluded."""
158
+ out = set()
159
+ for tok in _CAP.findall(s):
160
+ tok = re.sub(r"'s$", '', tok)
161
+ w = tok.casefold()
162
+ if re.fullmatch(MONTHS, tok) or len(w) < 3 or w in _NOT_NAMES or (tok.isupper() and len(tok) > 1):
163
+ continue
164
+ if self.df.get(w, 0) <= limit:
165
+ out.add(tok)
166
+ return out
167
+
168
+ def paragraph_of(self, pos):
169
+ for a, b in self.paragraphs:
170
+ if a <= pos < b:
171
+ return a, b
172
+ return None
173
+
174
+ def line_of(self, pos):
175
+ for a, b in self.lines:
176
+ if a <= pos < b:
177
+ return a, b
178
+ return None
179
+
180
+ def container(self, span):
181
+ """(kind, key) of the message/minute/entry holding a span, else None."""
182
+ for key, (a, b) in self.entries.items():
183
+ if a <= span['start'] < b:
184
+ return ('entry', key)
185
+ para = self.paragraph_of(span['start'])
186
+ if para is None:
187
+ return None
188
+ for key, rng in self.messages.items():
189
+ if rng == para:
190
+ return ('message', key)
191
+ for key, rng in self.minutes.items():
192
+ if rng == para:
193
+ return ('minute', key)
194
+ return None
195
+
196
+ def references(self, sentence):
197
+ """Containers a withdrawal-type sentence refers to."""
198
+ out = []
199
+ for m in _REF_ENTRY.finditer(sentence):
200
+ out.append(('entry', (m.group(2), m.group(1))))
201
+ for m in _REF_DATE.finditer(sentence):
202
+ out.append(('message', m.group(1)))
203
+ for m in _REF_MINUTE.finditer(sentence):
204
+ out.append(('minute', m.group(1)))
205
+ return out
206
+
207
+ def container_range(self, ref):
208
+ kind, key = ref
209
+ return {'entry': self.entries, 'message': self.messages, 'minute': self.minutes}[kind].get(key)
210
+
211
+ def locators(self, span):
212
+ """Header ranges that place a span in its container (never the span's own text)."""
213
+ text, out = self.text, []
214
+ para = self.paragraph_of(span['start'])
215
+ if para is None:
216
+ return out
217
+ a, b = para
218
+ nl = text.find('\n', a, b)
219
+ if nl >= 0 and span['start'] > nl:
220
+ out.append((a, nl)) # first line of a multi-line block: message/section/schedule heading
221
+ else:
222
+ m = _MINUTE_HEAD.match(text, a)
223
+ if m and m.end() <= span['start']:
224
+ out.append((a, m.end())) # numbered minute and its heading
225
+ line = self.line_of(span['start'])
226
+ if line and line[0] < span['start']:
227
+ prefix = text[line[0]:span['start']]
228
+ if len(prefix) <= 16 and _ENTRY_PREFIX.fullmatch(prefix):
229
+ out.append((line[0], span['start'])) # entry / clause number
230
+ return out
231
+
232
+ def sentence_ranges_in(self, rng):
233
+ a, b = rng
234
+ return [s for s in self.sentences if a <= s['start'] < b]
235
+
236
+
237
+ def _strip(text, a, b):
238
+ while a < b and text[a].isspace():
239
+ a += 1
240
+ while b > a and text[b - 1].isspace():
241
+ b -= 1
242
+ return a, b
243
+
244
+
245
+ def _merge(text, items):
246
+ """items: (start, end, role, reason) -> merged validated ranges; evidence role wins on overlap."""
247
+ cleaned = []
248
+ for a, b, role, reason in items:
249
+ a, b = _strip(text, a, b)
250
+ if a < b:
251
+ cleaned.append((a, b, role, reason))
252
+ cleaned.sort()
253
+ merged = []
254
+ for a, b, role, reason in cleaned:
255
+ if merged and a <= merged[-1]['end']:
256
+ m = merged[-1]
257
+ m['end'] = max(m['end'], b)
258
+ m['roles'].add(role)
259
+ m['reasons'].add(reason)
260
+ else:
261
+ merged.append({'start': a, 'end': b, 'roles': {role}, 'reasons': {reason}})
262
+ h = digest(text)
263
+ out = [{'id': f"text:{m['start']}:{m['end']}", 'kind': 'text', 'start': m['start'], 'end': m['end'],
264
+ 'text': text[m['start']:m['end']], 'source_sha256': h,
265
+ 'role': 'evidence' if 'evidence' in m['roles'] else 'context', 'reasons': sorted(m['reasons'])} for m in merged]
266
+ validate_spans(text, out)
267
+ return out
268
+
269
+
270
+ def render(text, spans):
271
+ """Source-order rendering; separators are whitespace only and mirror the source layout."""
272
+ parts, last = [], None
273
+ for s in sorted(spans, key=lambda s: s['start']):
274
+ if last is not None:
275
+ gap = text[last:s['start']]
276
+ parts.append('\n\n' if '\n\n' in gap or re.search(r'\n\s*\n', gap) else ('\n' if '\n' in gap else ' '))
277
+ parts.append(text[s['start']:s['end']])
278
+ last = s['end']
279
+ return ''.join(parts)
280
+
281
+
282
+ def build(text, question, evidence, *, subject=None, structure=None, options=None, cap=SIZE_CAP):
283
+ """One unit's evidence package.
284
+
285
+ evidence: selected (or gold, for oracle diagnostics) source spans for this unit.
286
+ subject: optional explicit subject string (entity name); otherwise rare capitalised question tokens.
287
+ """
288
+ opts = {'header': True, 'interpretation': True, 'locator': True, 'correction': True, 'withdrawn': True,
289
+ 'rule': True, 'exception': True, 'definition': True, 'condition': True, 'convention': True, **(options or {})}
290
+ st = structure or Structure(text)
291
+ evidence = validate_spans(text, [{k: s[k] for k in ('start', 'end')} for s in evidence]) if evidence else []
292
+ items = [(s['start'], s['end'], 'evidence', 'selected') for s in evidence]
293
+ subj = st.names(subject if subject else question, limit=10 ** 9 if subject else 16)
294
+ if subject:
295
+ subj |= {subject}
296
+ qtopic = _topic(question, subj)
297
+ rare = st.names(question)
298
+
299
+ def mentions(t):
300
+ return (subject in t) if subject else bool(st.names(t) & rare)
301
+ if opts['header'] and st.paragraphs:
302
+ a, b = st.paragraphs[0]
303
+ items.append((a, min(b, a + 400), 'context', 'header'))
304
+ if opts['interpretation']:
305
+ items += [(a, b, 'context', 'interpretation') for a, b in st.interpretation]
306
+ if evidence:
307
+ included = [dict(s) for s in evidence]
308
+ if opts['rule']:
309
+ for r in st.rules:
310
+ if len(_topic(r['text'], subj) & qtopic) >= (3 if 'Attribute:' in question else 2):
311
+ items.append((r['start'], r['end'], 'context', 'rule'))
312
+ included.append(r)
313
+ # Iterate twice: attached statements can themselves need locators/corrections.
314
+ for _ in range(3):
315
+ current = [{'start': a, 'end': b} for a, b, role, reason in items
316
+ if role == 'evidence' or reason in ('rule', 'exception', 'withdrawn', 'correction', 'definition', 'condition')]
317
+ spans = [s for s in st.sentences if any(max(s['start'], c['start']) < min(s['end'], c['end']) for c in current)]
318
+ for s in spans:
319
+ s_text = s['text']
320
+ if opts['exception'] and s in st.rules:
321
+ for e in st.exceptions:
322
+ g = st.governed_rule(e)
323
+ if g is not None and g['start'] == s['start']:
324
+ items.append((e['start'], e['end'], 'context', 'exception'))
325
+ if opts['exception'] and s in st.exceptions:
326
+ g = st.governed_rule(s)
327
+ if g is not None:
328
+ items.append((g['start'], g['end'], 'context', 'exception'))
329
+ if opts['definition'] and s in st.rules:
330
+ for term in set(re.findall(r'(?<=[a-z,;] )([A-Z][a-z]+ [A-Z][a-z]+?)s?\b', s_text)):
331
+ for d in st.sentences:
332
+ if term in d['text'] and _DEFINES.search(d['text']) and d['start'] < s['start'] and mentions(d['text']):
333
+ items.append((d['start'], d['end'], 'context', 'definition'))
334
+ if opts['condition'] and s in st.rules:
335
+ # Facts about this unit's subject that bear on the rule's conditions or its exception.
336
+ governing = [s] + [e for e in st.exceptions if (st.governed_rule(e) or {}).get('start') == s['start']]
337
+ words = set().union(*(_topic(g['text'], subj) for g in governing)) - qtopic
338
+ for t in st.sentences:
339
+ shared = _topic(t['text'], subj) & words
340
+ if t['start'] != s['start'] and mentions(t['text']) and (len(shared) >= 2 or any(st.df.get(w, 0) <= 3 for w in shared)):
341
+ items.append((t['start'], t['end'], 'context', 'condition'))
342
+ if opts['locator']:
343
+ items += [(a, b, 'context', 'locator') for a, b in st.locators(s)]
344
+ is_withdrawal = bool(_WITHDRAWAL.search(s_text))
345
+ if opts['withdrawn'] and is_withdrawal:
346
+ wnames = st.names(s_text)
347
+ for ref in st.references(s_text):
348
+ rng = st.container_range(ref)
349
+ if rng is None:
350
+ continue
351
+ if ref[0] == 'entry':
352
+ items.append((rng[0], rng[1], 'context', 'withdrawn'))
353
+ continue
354
+ for t in st.sentence_ranges_in(rng):
355
+ if t['start'] == s['start']:
356
+ continue
357
+ if st.names(t['text']) & wnames and _topic(t['text'], wnames) & _topic(s_text, wnames):
358
+ items.append((t['start'], t['end'], 'context', 'withdrawn'))
359
+ if opts['correction'] and not is_withdrawal:
360
+ where = st.container(s)
361
+ if where is None:
362
+ continue
363
+ snames = st.names(s_text)
364
+ for w in st.withdrawals:
365
+ if w['start'] == s['start'] or where not in st.references(w['text']):
366
+ continue
367
+ if where[0] == 'entry' or (st.names(w['text']) & snames and _topic(w['text'], snames) & _topic(s_text, snames)):
368
+ items.append((w['start'], w['end'], 'context', 'correction'))
369
+ if opts['convention']:
370
+ reasons = {r for _, _, _, r in items}
371
+ ev_text = ' '.join(text[a:b] for a, b, role, _ in items if role == 'evidence')
372
+ wanted = {'silence'}
373
+ if evidence:
374
+ wanted |= {'conflict', 'vocabulary'}
375
+ if reasons & {'correction', 'withdrawn'} or _WITHDRAWAL.search(ev_text):
376
+ wanted.add('removal')
377
+ if 'rule' in reasons or any(r['start'] < b and a < r['end'] for r in st.rules if not _SCALE.search(r['text'])
378
+ for a, b, role, _ in items if role == 'evidence'):
379
+ wanted.add('condition')
380
+ if 'exception' in reasons:
381
+ wanted.add('exception')
382
+ for kind in sorted(wanted):
383
+ items += [(a, b, 'context', 'convention/'+kind) for a, b in st.conventions[kind]]
384
+ spans = _merge(text, items);trimmed = []
385
+ def size(sp):return sum(x['end'] - x['start'] for x in sp) / len(text) if text else 0.
386
+ for reason in (TRIM_ORDER if cap is not None else ()):
387
+ if size(spans) <= cap:
388
+ break
389
+ keep = [it for it in items if it[3] != reason]
390
+ if len(keep) != len(items):
391
+ items = keep;trimmed.append(reason);spans = _merge(text, items)
392
+ rendered = render(text, spans)
393
+ covered = sum(s['end'] - s['start'] for s in spans)
394
+ return {'schema': SCHEMA, 'question': question, 'source_sha256': digest(text), 'text': rendered, 'spans': spans,
395
+ 'size_cap': cap, 'within_size_cap': cap is None or covered <= cap * len(text), 'trimmed_for_cap': trimmed,
396
+ 'evidence_ranges': [{'start': s['start'], 'end': s['end']} for s in evidence],
397
+ 'no_support_found': not evidence, 'source_characters': len(text), 'covered_characters': covered,
398
+ 'rendered_characters': len(rendered), 'source_fraction': covered / len(text) if text else 0.,
399
+ 'context_reasons': sorted({r for s in spans for r in s['reasons'] if r != 'selected'}),
400
+ 'faithfulness_established': False}
401
+
402
+
403
+ def union(text, packages):
404
+ """One document-level package: union of unit packages (used for whole-question rendering)."""
405
+ items = [(s['start'], s['end'], s['role'], r) for p in packages for s in p['spans'] for r in s['reasons']]
406
+ if not items:
407
+ return {'schema': SCHEMA, 'text': '', 'spans': [], 'source_fraction': 0., 'covered_characters': 0,
408
+ 'source_characters': len(text), 'rendered_characters': 0, 'source_sha256': digest(text)}
409
+ spans = _merge(text, items)
410
+ rendered = render(text, spans)
411
+ covered = sum(s['end'] - s['start'] for s in spans)
412
+ return {'schema': SCHEMA, 'text': rendered, 'spans': spans, 'source_fraction': covered / len(text),
413
+ 'covered_characters': covered, 'source_characters': len(text), 'rendered_characters': len(rendered),
414
+ 'source_sha256': digest(text)}
415
+
416
+
417
+ def with_pages(package, text, page_map):
418
+ """Attach renderer page IDs to every package span (solomon.sources.evidence_pages)."""
419
+ from solomon.sources import evidence_pages
420
+ out = dict(package)
421
+ out['spans'] = [{**s, 'pages': evidence_pages(text, [s], page_map)} for s in package['spans']]
422
+ out['pages'] = sorted({p for s in out['spans'] for p in s['pages']})
423
+ return out
src/solomon/heads.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Final normalized feature extraction, preserving the qualified CUDA engine."""
2
+ import hashlib,json
3
+ from pathlib import Path
4
+ import numpy as np
5
+
6
+ def sha(path):return hashlib.sha256(Path(path).read_bytes()).hexdigest()
7
+
8
+ def token_ids_for(engine,state,block,n):
9
+ text=engine._render(state['parts'],block);raw=engine.t.encode(text,add_special_tokens=False);ids=[]
10
+ for c in 'ABCDEFGHIJ'[:n]:
11
+ ext=engine.t.encode(text+c,add_special_tokens=False)
12
+ if ext[:-1]!=raw or len(ext)!=len(raw)+1:raise ValueError('unstable answer token continuation')
13
+ ids.append(ext[-1])
14
+ return ids
15
+
16
+ def capture(engine,state,block,n):
17
+ """Prehook sees precisely the post-final-norm input used by the vocabulary head."""
18
+ captured=[]
19
+ def hook(module,args):
20
+ h=args[0]
21
+ if h.ndim!=2 or h.shape[0]!=1:raise ValueError('unexpected final head input shape')
22
+ captured.append(h.detach().float().cpu().numpy()[0].copy())
23
+ handle=engine.model.lm_head.register_forward_pre_hook(hook)
24
+ try:result=engine.ask(state,block,n,execution='cached')
25
+ finally:handle.remove()
26
+ if len(captured)!=1:raise ValueError('expected exactly one vocabulary projection')
27
+ ids=token_ids_for(engine,state,block,n)
28
+ if not np.isfinite(captured[0]).all():raise ValueError('nonfinite hidden features')
29
+ return captured[0],ids,result
30
+
31
+ def copy_letter_head(engine):
32
+ ids=[]
33
+ for c in 'ABCDEFGHIJ':
34
+ pieces=engine.t.encode(c,add_special_tokens=False)
35
+ if len(pieces)!=1:raise ValueError('letters must be one token')
36
+ ids.append(pieces[0])
37
+ head=engine.model.lm_head;w=head.weight.detach()[ids].float().cpu().numpy().copy();b=getattr(head,'bias',None)
38
+ return {'weight':w,'bias':np.zeros(10,np.float32) if b is None else b.detach()[ids].float().cpu().numpy().copy(),'token_ids':np.array(ids,np.int64),'vocabulary_size':np.array(head.weight.shape[0],np.int64),'bias_present':np.array(b is not None)}
39
+
40
+ def atomic_json(path,value):
41
+ path=Path(path);tmp=path.with_suffix(path.suffix+'.tmp');tmp.write_text(json.dumps(value,sort_keys=True,indent=2));tmp.replace(path)
42
+
43
+ def write_document(path,features,token_ids,results,metadata,identity):
44
+ """NPZ first, then checksummed completion JSON. No cumulative shard rewrite."""
45
+ path=Path(path);n=len(features)
46
+ if not n or not(len(token_ids)==len(results)==len(metadata)==n):raise ValueError('document arrays must align')
47
+ h=np.asarray(features,np.float32);logits=np.zeros((n,10),np.float32);tokens=np.full((n,10),-1,np.int64);widths=[]
48
+ if h.ndim!=2 or not np.isfinite(h).all():raise ValueError('invalid document feature matrix')
49
+ rows=[]
50
+ for i,(ids,r,m) in enumerate(zip(token_ids,results,metadata)):
51
+ values=np.asarray(r['letter_logits'],np.float32);width=len(ids)
52
+ if not 2<=width<=10 or values.shape!=(width,) or not np.isfinite(values).all():raise ValueError('invalid teacher row')
53
+ logits[i,:width]=values;tokens[i,:width]=ids;widths.append(width)
54
+ rows.append({**m,'n':width,'mass':float(r['mass']),'top_is_letter':bool(r['top_is_letter']),'prompt_tokens':int(r['prompt_tokens']),'branch_tokens':int(r['branch_tokens']),'reused_prefix_tokens':int(r['reused_prefix_tokens'])})
55
+ tmp=path.with_suffix('.npz.tmp')
56
+ with tmp.open('wb') as f:np.savez(f,hidden=h,teacher_logits=logits,token_ids=tokens,widths=np.asarray(widths,np.int64))
57
+ tmp.replace(path)
58
+ report={'complete':True,'identity':identity,'rows':rows,'npz_sha256':sha(path),'feature_shape':list(h.shape),'feature_kind':'final-normalized-lm-head-input','storage':'uncompressed-npz-float32'}
59
+ atomic_json(path.with_suffix('.json'),report)
60
+ return report
61
+
62
+ def validate_document(path,identity,expected_ids):
63
+ path=Path(path);meta=path.with_suffix('.json')
64
+ if not path.exists() or not meta.exists():return False
65
+ r=json.loads(meta.read_text())
66
+ if r.get('complete')is not True or r.get('identity')!=identity or r.get('npz_sha256')!=sha(path) or [x['id'] for x in r['rows']]!=list(expected_ids):raise ValueError('resumed document identity mismatch')
67
+ return True
68
+
69
+ class TrainedHeads:
70
+ """Validated saved answer/correctness heads. No backbone or label access."""
71
+ def __init__(self,directory,*,expected_report_sha256=None,expected_weights_sha256=None):
72
+ directory=Path(directory);report_path=directory/'report.json';weights_path=directory/'weights.npz'
73
+ self.report_sha256=sha(report_path);self.weights_sha256=sha(weights_path)
74
+ if expected_report_sha256 is not None and self.report_sha256!=expected_report_sha256:raise ValueError('selected head report changed')
75
+ if expected_weights_sha256 is not None and self.weights_sha256!=expected_weights_sha256:raise ValueError('selected head weights changed')
76
+ self.report=json.loads(report_path.read_text())
77
+ if self.report['weights_sha256']!=self.weights_sha256:raise ValueError('trained head weight checksum mismatch')
78
+ self.models={}
79
+ with np.load(weights_path,allow_pickle=False) as archive:
80
+ for kind,entries in self.report['models'].items():
81
+ self.models[kind]={}
82
+ for key,fields in entries.items():
83
+ model={name:archive[value['array']].astype(np.float64) if isinstance(value,dict) and set(value)=={'array'} else value for name,value in fields.items()}
84
+ if any(not np.isfinite(value).all() for value in model.values() if isinstance(value,np.ndarray)):raise ValueError('nonfinite trained head')
85
+ if kind=='heads':
86
+ if model['weight'].ndim!=2 or model['weight'].shape[0]!=10 or model['bias'].shape!=(10,):raise ValueError('invalid answer head shape')
87
+ elif kind=='correctness':
88
+ if model['mean'].ndim!=1 or model['scale'].shape!=model['mean'].shape or np.any(model['scale']<=0) or model['weights'].shape!=(len(model['mean'])+1,):raise ValueError('invalid correctness head shape')
89
+ else:raise ValueError('unknown trained model kind')
90
+ self.models[kind][key]=model
91
+ if not self.models.get('heads') or not self.models.get('correctness'):raise ValueError('both trained answer and correctness heads required')
92
+
93
+ def answer(self,hidden,key,n):
94
+ if key not in self.models['heads']:raise ValueError('no trained answer head for '+str(key))
95
+ if type(n)is not int or not 2<=n<=10:raise ValueError('invalid head output width')
96
+ h=np.asarray(hidden,np.float64);model=self.models['heads'][key]
97
+ if h.shape!=(model['weight'].shape[1],) or not np.isfinite(h).all():raise ValueError('invalid hidden state for answer head')
98
+ return (model['weight']@h+model['bias'])[:n]
99
+
100
+ def correctness(self,task,branches):
101
+ from scipy.special import expit
102
+ if task not in self.models['correctness'] or not branches:raise ValueError('no trained whole-answer correctness head')
103
+ hidden=np.asarray([r['hidden'] for r in branches],np.float64);probs=[]
104
+ if hidden.ndim!=2 or not np.isfinite(hidden).all():raise ValueError('invalid correctness hidden representations')
105
+ for row in branches:
106
+ p=np.asarray(row['probabilities'],float)
107
+ if p.ndim!=1 or len(p)<2 or not np.isfinite(p).all() or np.any(p<0) or abs(p.sum()-1)>1e-6:raise ValueError('invalid correctness answer distribution')
108
+ probs.append(p)
109
+ feature=np.r_[hidden.mean(0),min(float(p.max()) for p in probs),min(float(np.sort(p)[-1]-np.sort(p)[-2]) for p in probs),max(float(-np.sum(p*np.log(np.maximum(p,1e-300)))/np.log(len(p))) for p in probs),float(len(branches)),float(sum(len(p) for p in probs))]
110
+ model=self.models['correctness'][task]
111
+ if feature.shape!=model['mean'].shape:raise ValueError('whole-answer confidence feature width mismatch')
112
+ value=float(expit(np.r_[1.,(feature-model['mean'])/model['scale']]@model['weights']))
113
+ return {'reliability':value,'features':feature.tolist(),'task':task,'target':'whole_return_exact_correctness','calibration_established':False,'heads_sha256':self.weights_sha256}
114
+
115
+
116
+ def semantic_head_key(task,block):
117
+ from solomon.engine_contract import SUFFICIENCY,SINGLE_R,SINGLE_S,ORDERED_R,ORDERED_S,LABEL,BOOLEAN_TASK
118
+ if task not in ('boolean','single','ordered','multilabel','entity'):raise ValueError('explicit answering task required')
119
+ if block.startswith(SUFFICIENCY) and task in ('single','ordered'):return task+'/sufficiency3'
120
+ for prefix,t,form in ((SINGLE_R,'single','R'),(SINGLE_S,'single','S'),(ORDERED_R,'ordered','R'),(ORDERED_S,'ordered','S')):
121
+ if block.startswith(prefix) and task==t:return task+'/choice'+form
122
+ if block.startswith(LABEL) and task=='multilabel':return 'multilabel/state4'
123
+ if block.startswith(BOOLEAN_TASK):
124
+ if task in ('boolean','entity'):return task+'/state4'
125
+ if task=='ordered':return 'ordered/threshold4'
126
+ raise ValueError('task block has no trained semantic head mapping')
127
+
128
+
129
+ from solomon.engine_reasoning import ReasoningEngine
130
+ class HeadsEngine(ReasoningEngine):
131
+ """Question-only backbone with trained small heads; native LM head retained for reasoning.
132
+
133
+ Wrap a complete readout in task_context(task), or supply ask(head_key=...).
134
+ Answer projection is deliberately evaluated in CPU float64 on the exact copied
135
+ float32 hidden vector to match saved-feature evaluation; no speedup is claimed.
136
+ """
137
+ def __init__(self,heads_dir,*,expected_base_fingerprint,expected_report_sha256=None,expected_weights_sha256=None,**kwargs):
138
+ import threading
139
+ self.heads=TrainedHeads(heads_dir,expected_report_sha256=expected_report_sha256,expected_weights_sha256=expected_weights_sha256)
140
+ super().__init__(**kwargs)
141
+ if self.identity['fingerprint']!=expected_base_fingerprint:raise ValueError('trained head backbone/adapter runtime mismatch')
142
+ self.base_identity=dict(self.identity);self._head_task=None;self._head_lock=threading.RLock()
143
+ self.identity={**self.identity,'base_fingerprint':expected_base_fingerprint,'trained_heads_sha256':self.heads.weights_sha256,'trained_heads_report_sha256':self.heads.report_sha256,'heads_runtime_sha256':sha(__file__),'answer_projection':'trained-semantic-head-float64-cpu'}
144
+ self.identity.pop('fingerprint',None);self.identity['fingerprint']=hashlib.sha256(json.dumps(self.identity,sort_keys=True).encode()).hexdigest()
145
+
146
+ def task_context(self,task):
147
+ from contextlib import contextmanager
148
+ @contextmanager
149
+ def context():
150
+ with self._head_lock:
151
+ previous=self._head_task;self._head_task=task
152
+ try:yield self
153
+ finally:self._head_task=previous
154
+ return context()
155
+
156
+ def prefill(self,document):
157
+ with self._head_lock:return super().prefill(document)
158
+
159
+ def ask(self,state,block,n_letters,execution='cached',head_key=None):
160
+ import copy
161
+ with self._head_lock:
162
+ key=head_key or semantic_head_key(self._head_task,block)
163
+ if key not in self.heads.models['heads']:raise ValueError('missing trained head '+key)
164
+ if self.placement!='question':raise ValueError('trained heads require question-only adaptation')
165
+ if execution not in ('cached','full'):raise ValueError('invalid execution')
166
+ torch=self.torch;p=state['prefix_tokens'];previous=self.ctx['start']
167
+ try:
168
+ with torch.inference_mode():
169
+ text=self._render(state['parts'],block);ids,embeds,pos,_=self._encode(state['parts'],text,state['features'])
170
+ if not torch.equal(ids[:,:p],state['prefix_ids']):raise ValueError('head question prefix mismatch')
171
+ self.ctx['start']=(0 if execution=='cached' or self.placement=='full' else p) if self.adapter else None
172
+ if execution=='cached':h=self.lm(inputs_embeds=embeds[:,p:],position_ids=pos[...,p:],past_key_values=copy.deepcopy(state['cache']),use_cache=True).last_hidden_state
173
+ else:h=self.lm(inputs_embeds=embeds,position_ids=pos,use_cache=False).last_hidden_state
174
+ hidden=h[0,-1].float().cpu().numpy().copy()
175
+ logits=self.heads.answer(hidden,key,n_letters);probs=np.exp(logits-logits.max());probs/=probs.sum()
176
+ return {'letter_logits':logits,'probabilities':probs,'prediction':int(probs.argmax()),'hidden':hidden.tolist(),'head_key':key,'mass':None,'top_is_letter':None,'mass_available':False,'execution':execution,'fallback':'','prompt_tokens':int(ids.shape[1]),'branch_tokens':int(ids.shape[1])-p,'input_tokens':int(ids.shape[1])-p,'reused_prefix_tokens':p if execution=='cached' else 0,'generation_tokens':0,'fingerprint':self.identity['fingerprint']}
177
+ finally:self.ctx['start']=previous
178
+
179
+ def estimate(self,state,block,n,stage='fast',max_new_tokens=512):
180
+ if stage!='fast' or not any('image' in part for part in state['parts']):
181
+ return super().estimate(state,block,n,stage=stage,max_new_tokens=max_new_tokens)
182
+ if type(n)is not int or not 2<=n<=10:raise ValueError('invalid letter count')
183
+ # Reuse prefetched vision features; no transformer branch is evaluated.
184
+ with self._head_lock,self.torch.inference_mode():
185
+ ids,_,_,_=self._encode(state['parts'],self._render(state['parts'],block),state['features'])
186
+ prefix=state['prefix_tokens']
187
+ if not self.torch.equal(ids[:,:prefix],state['prefix_ids']):raise ValueError('image budget prefix mismatch')
188
+ return {'input_tokens':int(ids.shape[1])-prefix,'generated_tokens':0,'branches':1,
189
+ 'full_prompt_tokens':int(ids.shape[1]),'reused_prefix_tokens':prefix}
190
+
191
+ def predict_correctness(self,task,branches):return self.heads.correctness(task,branches)
192
+
193
+ def reason(self,*args,**kwargs):
194
+ with self._head_lock:return super().reason(*args,**kwargs)
src/solomon/prompts_two_letter.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Solomon two-letter (Noul) prompts and block conversions.
2
+
3
+ The two_letter readout asks every yes/no, entity-candidate, multi-label and ordered-threshold branch with two letters: A = yes, B = no.
4
+ The wording is the four-state wording (solomon.engine_reference.BOOLEAN_TASK, solomon.engine_contract.LABEL) with only the letter
5
+ definitions changed to the Solomon rule (not stated -> no, conflicting -> no). The sentence 'A missing fact is not a negative
6
+ fact.' is removed: it argued for the reserved C letter and contradicts 'not stated -> B'. Everything else is verbatim.
7
+
8
+ Choice (single, ordered) uses the existing listed-only S prompt (solomon.engine_contract.listwise_block(..., reserved=False)).
9
+ """
10
+ import re
11
+
12
+ from solomon.engine_reference import BOOLEAN_TASK
13
+ from solomon.engine_contract import LABEL, ORDERED_R, SINGLE_R, listwise_block, RESERVED
14
+
15
+ MISSING = ' A missing fact is not a negative fact.'
16
+
17
+ BOOLEAN_TASK2 = ('Task: classify the evidence for the question using only the document and its explicit rules. '
18
+ 'A = Yes: the document establishes Yes, and nothing in it establishes No. '
19
+ 'B = No: anything else (the document establishes No, establishes neither, or establishes both). '
20
+ 'Evidence about another person or subject does not contradict '
21
+ 'the queried one. Apply explicit time and replacement rules before deciding. '
22
+ 'Respond with exactly one letter: A or B. Do not explain.')
23
+
24
+ LABEL2 = ('Task: decide whether the label applies, using only the document. A = the document establishes that it applies, and nothing in '
25
+ 'it establishes that it does not. B = anything else (the document establishes that it does not apply, establishes neither, '
26
+ 'or establishes both). '
27
+ 'Evidence about another person or subject does not count. A replaced or withdrawn statement establishes nothing. '
28
+ 'Respond with exactly one letter: A or B. Do not explain.')
29
+
30
+ assert MISSING in BOOLEAN_TASK and MISSING in LABEL
31
+
32
+
33
+ def noul_block(question):
34
+ return BOOLEAN_TASK2 + '\nQuestion: ' + question + '\nAnswer (one letter):', 2
35
+
36
+
37
+ def label_block2(question, label):
38
+ return LABEL2 + '\nQuestion: ' + question + '\nLabel: ' + label + '\nAnswer (one letter):', 2
39
+
40
+
41
+ def to_two_letter(block):
42
+ """Four-state boolean/label block -> the identical block with the two-letter task text. Raises on anything else."""
43
+ for old, new in ((BOOLEAN_TASK, BOOLEAN_TASK2), (LABEL, LABEL2)):
44
+ if block.startswith(old + '\nQuestion: '):
45
+ rest = block[len(old):]
46
+ if not rest.endswith('\nAnswer (one letter):'):
47
+ raise ValueError('unexpected four-state block tail')
48
+ return new + rest
49
+ raise ValueError('not a four-state boolean/label block')
50
+
51
+
52
+ _OPT = re.compile(r'^([A-J])\. (.*)$')
53
+
54
+
55
+ def parse_listwise(block):
56
+ """Reserved (R) listwise block -> (question, shown_options, ordered). Verified by exact reconstruction."""
57
+ for task, ordered in ((SINGLE_R, False), (ORDERED_R, True)):
58
+ if block.startswith(task + '\nQuestion: '):
59
+ body = block[len(task) + len('\nQuestion: '):]
60
+ q, _, rest = body.partition('\nOptions:\n')
61
+ lines = rest[:-len('\nAnswer (one letter):')].split('\n')
62
+ opts = []
63
+ for i, line in enumerate(lines):
64
+ m = _OPT.match(line)
65
+ if not m or m.group(1) != 'ABCDEFGHIJ'[i]:
66
+ raise ValueError('unparseable option line')
67
+ opts.append(m.group(2))
68
+ if opts[-2:] != RESERVED:
69
+ raise ValueError('R block without reserved options')
70
+ shown = opts[:-2]
71
+ if listwise_block(q, shown, ordered=ordered, reserved=True)[0] != block:
72
+ raise ValueError('R block reconstruction mismatch')
73
+ return q, shown, ordered
74
+ raise ValueError('not a reserved listwise block')
75
+
76
+
77
+ def r_to_s(block):
78
+ """R block -> listed-only S block (same question, same shown order) and its width."""
79
+ q, shown, ordered = parse_listwise(block)
80
+ return listwise_block(q, shown, ordered=ordered, reserved=False)
src/solomon/readout.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Contract v3 readouts: branch jobs for every answer type, predictions from letter logits, and metrics.
2
+
3
+ Job ids are '<row id>|<kind>[|<detail>]':
4
+ b / bp four-state Boolean question / its paraphrase
5
+ E|j L|j t|j entity j, label j, threshold j (four-state)
6
+ R|<perm> listwise with reserved options, caller options in order <perm> (digits; identity = caller order)
7
+ S|<perm> listwise without reserved options; suf = the separate sufficiency branch
8
+ P|i per-option four-state branch for option i
9
+ """
10
+ import random
11
+ import zlib
12
+
13
+ import numpy as np
14
+
15
+ from solomon.engine_contract import CONFLICTING, NOT_STATED, four_state_block, label_block, listwise_block, option_block, sufficiency_block
16
+
17
+
18
+ def softmax(x):
19
+ x = np.asarray(x, np.float64)
20
+ e = np.exp(x - x.max())
21
+ return e / e.sum()
22
+
23
+
24
+ def perm_key(perm):
25
+ return ''.join(str(i) for i in perm)
26
+
27
+
28
+ def order_set(row_id, n, extra=3):
29
+ """Caller order, every other cyclic rotation, and `extra` seeded random permutations (deduplicated)."""
30
+ orders = [tuple((i + r) % n for i in range(n)) for r in range(n)]
31
+ rng = random.Random(zlib.crc32(row_id.encode()))
32
+ tries = 0
33
+ while len(orders) < n + extra and tries < 50:
34
+ p = list(range(n))
35
+ rng.shuffle(p)
36
+ if tuple(p) not in orders:
37
+ orders.append(tuple(p))
38
+ tries += 1
39
+ return orders
40
+
41
+
42
+ def rotations_of(perm):
43
+ n = len(perm)
44
+ return [tuple(perm[(i + r) % n] for i in range(n)) for r in range(n)]
45
+
46
+
47
+ def jobs_for(rows, designs, docs=None):
48
+ """designs: subset of {'four', 'para', 'R', 'Rrot', 'Rrotfull', 'S', 'Srot', 'suf', 'P'}. docs maps document text -> parts."""
49
+ out = []
50
+ for r in rows:
51
+ inp = r['input']
52
+ doc = inp['document']['text'] if docs is None else docs[inp['document']['text']]
53
+ add = lambda kind, blk: out.append({'id': f"{r['id']}|{kind}", 'doc': doc, 'block': blk[0], 'n': blk[1]})
54
+ task = r['task']
55
+ if task == 'boolean' and 'four' in designs:
56
+ add('b', four_state_block(inp['question']))
57
+ if 'para' in designs and inp.get('paraphrase'):
58
+ add('bp', four_state_block(inp['paraphrase']))
59
+ elif task == 'entity' and 'four' in designs:
60
+ for j, name in enumerate(inp['entities']):
61
+ add(f'E|{j}', four_state_block(inp['template'].format(entity=name)))
62
+ elif task == 'multilabel' and 'four' in designs:
63
+ for j, label in enumerate(inp['labels']):
64
+ add(f'L|{j}', label_block(inp['question'], label))
65
+ elif task in ('single', 'ordered'):
66
+ opts = inp['options']
67
+ ident = tuple(range(len(opts)))
68
+ for d, reserved in (('R', True), ('S', False)):
69
+ if not {d, d + 'rot', d + 'rotfull'} & set(designs):
70
+ continue
71
+ orders = [ident]
72
+ if task == 'single' and (d + 'rot' in designs or d + 'rotfull' in designs):
73
+ orders = order_set(r['id'], len(opts))
74
+ if d + 'rotfull' in designs:
75
+ orders = list(dict.fromkeys(o for p in orders for o in rotations_of(p)))
76
+ for perm in orders:
77
+ add(f'{d}|{perm_key(perm)}', listwise_block(inp['question'], [opts[i] for i in perm], ordered=task == 'ordered', reserved=reserved))
78
+ if 'suf' in designs:
79
+ add('suf', sufficiency_block(inp['question'], opts))
80
+ if 'P' in designs and task == 'single':
81
+ for i, o in enumerate(opts):
82
+ add(f'P|{i}', option_block(inp['question'], o))
83
+ if task == 'ordered' and 'four' in designs:
84
+ for j, t in enumerate(inp.get('thresholds', [])):
85
+ add(f't|{j}', four_state_block(t['question']))
86
+ return out
87
+
88
+
89
+ # ---------------------------------------------------------------- predictions
90
+ def listwise_logprobs(scores, row, design, perm, prior=None):
91
+ """Log-probabilities over [option 0..n-1 in CALLER indexing] + reserved (if design R), from the branch scored in order `perm`."""
92
+ n = len(row['input']['options'])
93
+ logits = np.asarray(scores[f"{row['id']}|{design}|{perm_key(perm)}"]['letter_logits'], np.float64)
94
+ if prior is not None:
95
+ logits = logits - prior[n if design == 'S' else n + 2]
96
+ lp = logits - np.logaddexp.reduce(logits)
97
+ out = np.empty_like(lp)
98
+ for pos, i in enumerate(perm):
99
+ out[i] = lp[pos]
100
+ out[n:] = lp[n:]
101
+ return out
102
+
103
+
104
+ def decode(lp, n):
105
+ k = int(np.argmax(lp))
106
+ return k if k < n else (NOT_STATED if k == n else CONFLICTING)
107
+
108
+
109
+ def predict_listwise(scores, row, design='R', perm=None, average=None, prior=None):
110
+ """average: None (one pass), or k = number of cyclic rotations of `perm` to average in log space ('all' = every rotation)."""
111
+ n = len(row['input']['options'])
112
+ perm = tuple(range(n)) if perm is None else perm
113
+ if average is None:
114
+ lp = listwise_logprobs(scores, row, design, perm, prior)
115
+ else:
116
+ rots = rotations_of(perm)
117
+ k = n if average == 'all' else min(average, n)
118
+ picks = [rots[round(j * n / k) % n] for j in range(k)]
119
+ lp = np.mean([listwise_logprobs(scores, row, design, p, prior) for p in dict.fromkeys(picks)], axis=0)
120
+ if design == 'R':
121
+ return decode(lp, n)
122
+ suf = int(np.argmax(scores[f"{row['id']}|suf"]['letter_logits']))
123
+ return int(np.argmax(lp[:n])) if suf == 0 else (NOT_STATED if suf == 1 else CONFLICTING)
124
+
125
+
126
+ def predict_per_option(scores, row):
127
+ n = len(row['input']['options'])
128
+ p = np.stack([softmax(scores[f"{row['id']}|P|{i}"]['letter_logits']) for i in range(n)])
129
+ yes, neither = p[:, 0] + p[:, 3], p[:, 2]
130
+ if (yes > 0.5).sum() >= 2:
131
+ return CONFLICTING
132
+ if not (yes > neither).any():
133
+ return NOT_STATED
134
+ return int(np.argmax(p[:, 0]))
135
+
136
+
137
+ def position_prior(scores, rows, design='R'):
138
+ """PriDe-style prior over letter positions, per option count: mean log-probability of each position over all
139
+ cyclic rotations of the estimation rows (every option visits every position, so content averages out)."""
140
+ acc = {}
141
+ for r in rows:
142
+ if r['task'] != 'single':
143
+ continue
144
+ n = len(r['input']['options'])
145
+ for perm in rotations_of(tuple(range(n))):
146
+ key = f"{r['id']}|{design}|{perm_key(perm)}"
147
+ if key not in scores:
148
+ break
149
+ l = np.asarray(scores[key]['letter_logits'], np.float64)
150
+ acc.setdefault(len(l), []).append(l - np.logaddexp.reduce(l))
151
+ prior = {}
152
+ for width, vals in acc.items():
153
+ m = np.mean(vals, axis=0)
154
+ n = width - 2 if design == 'R' else width
155
+ prior[width] = np.zeros(width) # reserved positions are never rotated: left unadjusted
156
+ prior[width][:n] = m[:n] - m[:n].mean()
157
+ return prior
158
+
159
+
160
+ def four_state_pred(scores, key):
161
+ return int(np.argmax(scores[key]['letter_logits'][:4]))
162
+
163
+
164
+ def derived_threshold(scores, row, k, design='R'):
165
+ """P(level >= k | some level) from the listwise distribution: monotone in k by construction."""
166
+ n = len(row['input']['options'])
167
+ p = np.exp(listwise_logprobs(scores, row, design, tuple(range(n))))[:n]
168
+ return float(p[k:].sum() / p.sum())
169
+
170
+
171
+ # ---------------------------------------------------------------- metrics
172
+ def bootstrap(correct_a, correct_b, families, n=2000, seed=4):
173
+ rng = np.random.default_rng(seed)
174
+ correct_a, correct_b, families = np.asarray(correct_a, float), np.asarray(correct_b, float), np.asarray(families)
175
+ fams = np.unique(families)
176
+ idx = {f: np.flatnonzero(families == f) for f in fams}
177
+ diffs = []
178
+ for _ in range(n):
179
+ take = np.concatenate([idx[f] for f in rng.choice(fams, len(fams), replace=True)])
180
+ diffs.append(correct_a[take].mean() - correct_b[take].mean())
181
+ lo, hi = np.percentile(diffs, [2.5, 97.5])
182
+ return {'difference': float(correct_a.mean() - correct_b.mean()), 'ci95': [float(lo), float(hi)]}
183
+
184
+
185
+ def interval(correct, families, n=2000, seed=4):
186
+ rng = np.random.default_rng(seed)
187
+ correct, families = np.asarray(correct, float), np.asarray(families)
188
+ fams = np.unique(families)
189
+ idx = {f: np.flatnonzero(families == f) for f in fams}
190
+ vals = [correct[np.concatenate([idx[f] for f in rng.choice(fams, len(fams), replace=True)])].mean() for _ in range(n)]
191
+ lo, hi = np.percentile(vals, [2.5, 97.5])
192
+ return [float(lo), float(hi)]
193
+
194
+
195
+ def decisions(rows, scores, design='R', average=None, prior=None, per_option=False):
196
+ """One record per scored decision: {'row', 'task', 'unit', 'family', 'generator', 'panel', 'gold', 'pred', 'correct', ...}."""
197
+ out = []
198
+ for r in rows:
199
+ base = {'row': r['id'], 'task': r['task'], 'family': r['family_id'], 'generator': r['generator'], 'panel': r['panel'],
200
+ 'mechanism': r.get('mechanism')}
201
+ if r['task'] == 'boolean':
202
+ pred = four_state_pred(scores, f"{r['id']}|b")
203
+ out.append({**base, 'unit': 'b', 'gold': r['target'], 'pred': pred, 'correct': pred == r['target']})
204
+ elif r['task'] == 'entity':
205
+ for j, gold in enumerate(r['targets']):
206
+ pred = four_state_pred(scores, f"{r['id']}|E|{j}")
207
+ out.append({**base, 'unit': f'E|{j}', 'gold': gold, 'pred': pred, 'correct': pred == gold, 'absent': r['absent'][j]})
208
+ elif r['task'] == 'multilabel':
209
+ for j, gold in enumerate(r['targets']):
210
+ pred = four_state_pred(scores, f"{r['id']}|L|{j}")
211
+ out.append({**base, 'unit': f'L|{j}', 'gold': gold, 'pred': pred, 'correct': pred == gold})
212
+ else:
213
+ pred = predict_per_option(scores, r) if (per_option and r['task'] == 'single') else predict_listwise(
214
+ scores, r, design, average=average if r['task'] == 'single' else None, prior=prior if r['task'] == 'single' else None)
215
+ out.append({**base, 'unit': 'choice', 'gold': r['target'], 'pred': pred, 'correct': pred == r['target'],
216
+ 'reserved_gold': not isinstance(r['target'], int), 'n_options': len(r['input']['options'])})
217
+ return out
218
+
219
+
220
+ def summarise(decs):
221
+ out = {}
222
+ for task in sorted({d['task'] for d in decs}):
223
+ sel = [d for d in decs if d['task'] == task]
224
+ ok = [d['correct'] for d in sel]
225
+ entry = {'correct': int(sum(ok)), 'n': len(sel), 'accuracy': float(np.mean(ok)), 'ci95': interval(ok, [d['family'] for d in sel]),
226
+ 'by_generator': {}, 'by_panel': {}}
227
+ for key in ('generator', 'panel'):
228
+ for v in sorted({d[key] for d in sel}):
229
+ s = [d['correct'] for d in sel if d[key] == v]
230
+ entry['by_' + key][v] = f'{int(sum(s))}/{len(s)}'
231
+ if task == 'boolean':
232
+ entry['by_mechanism'] = {m: f"{sum(d['correct'] for d in sel if d['mechanism'] == m)}/{sum(d['mechanism'] == m for d in sel)}"
233
+ for m in sorted({d['mechanism'] for d in sel})}
234
+ if task in ('single', 'ordered'):
235
+ for name, flag in (('reserved_gold', True), ('index_gold', False)):
236
+ s = [d['correct'] for d in sel if d['reserved_gold'] == flag]
237
+ entry[name] = f'{int(sum(s))}/{len(s)}'
238
+ if task in ('multilabel', 'entity'):
239
+ groups = {}
240
+ for d in sel:
241
+ groups.setdefault(d['row'], []).append(d['correct'])
242
+ entry['all_units_correct'] = f'{sum(all(v) for v in groups.values())}/{len(groups)}'
243
+ if task == 'entity':
244
+ s = [d['correct'] for d in sel if d['absent']]
245
+ entry['absent_entities'] = f'{int(sum(s))}/{len(s)}'
246
+ out[task] = entry
247
+ return out
248
+
249
+
250
+ def flip_rate(rows, scores, design='R', average=None, prior=None):
251
+ """Share of single-choice rows whose top answer (as an option identity) changes under any order in the order set."""
252
+ flips, n = [], 0
253
+ for r in rows:
254
+ if r['task'] != 'single':
255
+ continue
256
+ opts = len(r['input']['options'])
257
+ base = predict_listwise(scores, r, design, None, average, prior)
258
+ preds = [predict_listwise(scores, r, design, perm, average, prior) for perm in order_set(r['id'], opts)[1:]]
259
+ flips.append(any(p != base for p in preds))
260
+ n += 1
261
+ return {'rows': n, 'flipped': int(sum(flips)), 'rate': float(np.mean(flips)) if flips else None}
262
+
263
+
264
+ def threshold_consistency(rows, scores, design='R'):
265
+ agree, total, derived_ok, asked_ok, decided = 0, 0, 0, 0, 0
266
+ for r in rows:
267
+ if r['task'] != 'ordered':
268
+ continue
269
+ for j, t in enumerate(r['input']['thresholds']):
270
+ asked = four_state_pred(scores, f"{r['id']}|t|{j}")
271
+ gold = r['threshold_targets'][j]
272
+ asked_ok += asked == gold
273
+ total += 1
274
+ if gold in (0, 1):
275
+ d = 0 if derived_threshold(scores, r, t['k'], design) >= 0.5 else 1
276
+ decided += 1
277
+ derived_ok += d == gold
278
+ agree += d == asked
279
+ return {'threshold_questions': total, 'asked_correct': int(asked_ok), 'decided_gold': decided, 'derived_correct': int(derived_ok),
280
+ 'derived_agrees_with_asked': int(agree)}
281
+
282
+
283
+ def paraphrase_consistency(rows, scores):
284
+ same = [four_state_pred(scores, f"{r['id']}|b") == four_state_pred(scores, f"{r['id']}|bp") for r in rows
285
+ if r['task'] == 'boolean' and f"{r['id']}|bp" in scores]
286
+ return {'pairs': len(same), 'same_answer': int(sum(same))}
287
+
288
+
289
+ def negation_consistency(rows, scores):
290
+ """Positive and negative query of one subject: the four-state answers must be swaps of each other."""
291
+ swap = {0: 1, 1: 0, 2: 2, 3: 3}
292
+ pairs = {}
293
+ for r in rows:
294
+ if r['task'] == 'boolean' and 'subject' in r:
295
+ pairs.setdefault((r['family_id'], r['subject']), {})[r['negative_query']] = four_state_pred(scores, f"{r['id']}|b")
296
+ ok = [swap[v[0]] == v[1] for v in pairs.values() if set(v) == {0, 1}]
297
+ return {'pairs': len(ok), 'consistent': int(sum(ok))}
src/solomon/reliability.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """What the readout says about its own answer, with nothing fitted behind it.
2
+
3
+ A question is decoded correctly when every unit of it is, so the readout's statement about a question is
4
+ the product of its statement about each unit. No parameter is fitted here; the only parameter on this path
5
+ is the per-task temperature in `solomon/calibration.py`.
6
+
7
+ The product assumes the units of a question are independent. That has never been validated as a joint
8
+ probability: it orders multi-candidate questions well and it is not a calibrated joint. Read the
9
+ per-candidate numbers if you need a magnitude. `solomon.service.ORDERING_DISCLOSURE` says the same thing
10
+ in the response itself.
11
+ """
12
+ import numpy as np
13
+ from scipy.special import logsumexp
14
+
15
+ TASKS = ('boolean', 'single', 'ordered', 'multilabel', 'entity')
16
+
17
+
18
+ def unit_correct_probability(unit, t=1.0):
19
+ """The readout's stated P(this unit is decoded correctly).
20
+
21
+ Noul -> max(p, 1-p) with p = P(yes); the prediction is argmax, so this is P(prediction right).
22
+ Choice -> the listed top-1 probability.
23
+ t rescales the logits; t = 1 is the raw readout.
24
+ """
25
+ if unit['kind'] == 'noul':
26
+ x = np.asarray([unit['z'], 0.0], float) / t
27
+ else:
28
+ x = np.asarray(unit['logits'], float) / t
29
+ return float(np.exp(x.max() - logsumexp(x)))
30
+
31
+
32
+ def question_reliability(units, t=1.0):
33
+ """P(every unit correct) under the readout, assuming unit independence within a question."""
34
+ return float(np.prod([unit_correct_probability(u, t) for u in units]))
src/solomon/retrieval.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Inference-only source candidates and explicitly labelled retrieval baselines."""
2
+ import re
3
+ from solomon.evidence import digest,rank_candidates,validate_spans
4
+
5
+ def candidates(text):
6
+ """Source sentences retaining exact character ranges; no authoring labels."""
7
+ ends=[m.end() for m in re.finditer(r'(?<=[.!?])(?:[ \t]+|\n+)|\n\s*\n',text)]+[len(text)]
8
+ result=[];start=0
9
+ for end in ends:
10
+ if end>start and text[start:end].strip():
11
+ result.append({'id':f'text:{start}:{end}','kind':'text','start':start,'end':end,
12
+ 'text':text[start:end],'source_sha256':digest(text)})
13
+ start=end
14
+ return result
15
+
16
+ def governing_context(text,spans=None):
17
+ """Generic rule/retraction interpretation context, independent of question gold."""
18
+ spans=candidates(text) if spans is None else spans
19
+ pattern=re.compile(r'general rule|both limbs|same (?:person|courier|member|officer)|neither limb|missing requirement|silence|withdrawn passage|dates and seniority|a withdrawn|outside these|bands are|order of the levels|no.*precedence|each passage|a grant in force|an exception to a rule',re.I)
20
+ return [s for s in spans if pattern.search(s['text'])]
21
+
22
+ def merge(text,spans):
23
+ intervals=[]
24
+ for span in sorted(spans,key=lambda s:(s['start'],s['end'])):
25
+ a,b=span['start'],span['end']
26
+ if intervals and a<=intervals[-1][1]:intervals[-1]=(intervals[-1][0],max(b,intervals[-1][1]))
27
+ else:intervals.append((a,b))
28
+ result=[{'id':f'text:{a}:{b}','kind':'text','start':a,'end':b,'text':text[a:b],'source_sha256':digest(text)} for a,b in intervals]
29
+ return validate_spans(text,result)
30
+
31
+ def render_subset(text,spans,*,include_context=True):
32
+ selected=merge(text,list(spans)+(governing_context(text) if include_context else []))
33
+ return '\n\n'.join(s['text'] for s in selected),selected
34
+
35
+ _WORD=re.compile(r'\w+')
36
+ _SCALE=re.compile(r'\bbands?\b|\bscale\b|from lowest to highest|order of the levels',re.I)
37
+ POOL_V2={'name':'idf-rare-rule-v2','idf_limit':24,'rare_df':16,'rules':True}
38
+
39
+ def _words(s):return set(_WORD.findall(s.casefold()))
40
+
41
+ def rule_candidates(text,spans=None):
42
+ """Question-independent rule, exception, withdrawal-convention and scale passages."""
43
+ spans=candidates(text) if spans is None else spans
44
+ rules={s['id'] for s in governing_context(text,spans)}
45
+ return [s for s in spans if s['id'] in rules or _SCALE.search(s['text'])]
46
+
47
+ def candidate_pool(question,spans,text=None,*,idf_limit=24,rare_df=16,rules=True,**_):
48
+ """Bounded source-only pool: document-IDF top-k, every passage sharing a rare
49
+ question term (typically the subject's name), plus question-independent rules.
50
+
51
+ Candidate order is source order. candidate_score stays the plain lexical-overlap
52
+ fraction used by the frozen relevance-head feature, so heads remain comparable.
53
+ Gold is never an input.
54
+ """
55
+ import math
56
+ if idf_limit<1 or rare_df<0:raise ValueError('invalid candidate pool policy')
57
+ ranked=rank_candidates(question,spans,len(spans)) if spans else []
58
+ words=[_words(c['text']) for c in ranked];q=_words(question);n=len(ranked)
59
+ df={}
60
+ for ws in words:
61
+ for w in ws:df[w]=df.get(w,0)+1
62
+ idf=[sum(math.log((n+1)/(df[w]+.5)) for w in ws&q) for ws in words]
63
+ order=sorted(range(n),key=lambda i:(-idf[i],ranked[i]['start']))
64
+ reason={}
65
+ for i in order[:idf_limit]:reason.setdefault(ranked[i]['id'],'idf')
66
+ rare={w for w in q if df.get(w,0)<=rare_df}
67
+ for c,ws in zip(ranked,words):
68
+ if ws&rare:reason.setdefault(c['id'],'rare_term')
69
+ if rules:
70
+ for c in rule_candidates(text or '',ranked):reason.setdefault(c['id'],'rule')
71
+ return sorted(({**c,'pool_reason':reason[c['id']]} for c in ranked if c['id'] in reason),key=lambda c:c['start'])
72
+
73
+ _WITHDRAW=re.compile(r'withdr[ae]w|withdrawn|take back|disregard|rescind|retract|should not be relied|there is substituted|is deleted|expressly delete',re.I)
74
+ _REFERENCE=re.compile(r'(?:message of|wrote on|message dated) (\d{1,2} [A-Z][a-z]+)|minute (\d+)|[Ee]ntry (\d+) of [Ss]chedule (\d+)|clause ([\d.]+)|passage in my message')
75
+ _EXCEPTION=re.compile(r'does not apply to|subject to the exception|is an exception|except (?:where|that|for)\b',re.I)
76
+ _STOP={'this','that','these','those','with','under','which','what','does','file','correspondence','record','records','recorded',
77
+ 'minutes','agreement','bundle','messages','message','stand','stands','taking','reading','whole','strength','position',
78
+ 'open','given','have','been','applies','apply','entitled','allowed','liberty','free','from','there','their','they',
79
+ 'decisions','here','schedules','schedule','papers','office','shown','show','shows','case','matters','terms','place','placed'}
80
+ DEPENDENCIES_V1={'name':'withdrawal-exception-v1','withdrawals':True,'exceptions':True,'prune_withdrawn':False,'rare_df':16}
81
+
82
+ def _topic(words,exclude):
83
+ return {w for w in words if len(w)>=4 and w not in _STOP and w not in exclude and not w.isdigit()}
84
+
85
+ def _withdrawn_block(text,passage):
86
+ """Source range that a withdrawal refers to (dated message or numbered minute); None if not resolvable."""
87
+ m=_REFERENCE.search(passage)
88
+ if not m:return None
89
+ if m.group(1):head=re.search(r'Message \d+\. '+re.escape(m.group(1))+r'\.',text)
90
+ elif m.group(2):head=re.search(r'(?:^|\n)'+m.group(2)+r'\. ',text)
91
+ else:return None
92
+ if not head:return None
93
+ end=text.find('\n\n',head.end());return head.start(),(len(text) if end<0 else end)
94
+
95
+ def dependency_expand(question,spans,selected_ids,text,*,withdrawals=True,exceptions=True,prune_withdrawn=False,rare_df=16,**_):
96
+ """Complete a unit's selected evidence with its withdrawal/exception dependencies.
97
+
98
+ Source text and the already-selected passages only; never gold. Units with no
99
+ selection are unchanged, so no-positive-support decisions are preserved.
100
+ - withdrawal: a passage with a withdrawal verb AND an explicit reference (message/minute/
101
+ entry/clause) that names the question's subject (a rare capitalised name, also present in a
102
+ selected passage) and its most specific in-source topic word;
103
+ - exception: an exception clause immediately following a selected passage;
104
+ - prune_withdrawn (optional): drop selected passages inside the dated message / numbered
105
+ minute a kept withdrawal refers to, when they share its subject and a topic word.
106
+ Returns {'keep','added','pruned'} as candidate id lists in source order.
107
+ """
108
+ selected=[s for s in spans if s['id'] in set(selected_ids)]
109
+ if not selected:return {'keep':[],'added':[],'pruned':[]}
110
+ words=[_words(s['text']) for s in spans];df={}
111
+ for ws in words:
112
+ for w in ws:df[w]=df.get(w,0)+1
113
+ # Subject: capitalised non-initial question tokens (names) that are rare in the source.
114
+ names=re.findall(r'(?<!^)(?<![.?!] )\b[A-Z][\w&\'-]*',question.strip())
115
+ subject={w for n in names for w in _words(n) if len(w)>=3 and df.get(w,0)<=rare_df}
116
+ q=_words(question);present=[w for w in _topic(q,subject) if df.get(w,0)]
117
+ # The withdrawal must name the question's most specific in-source topic word (e.g. the attribute).
118
+ topic={min(present,key=lambda w:(df[w],w))} if present else set()
119
+ chosen={s['id'] for s in selected};sel_words=set().union(*(_words(s['text']) for s in selected));added=[]
120
+ for i,(s,ws) in enumerate(zip(spans,words)):
121
+ if s['id'] in chosen:continue
122
+ if (withdrawals and _WITHDRAW.search(s['text']) and _REFERENCE.search(s['text'])
123
+ and ws&subject&sel_words and ws&topic):added.append(s['id']);continue
124
+ if exceptions and i>0 and spans[i-1]['id'] in chosen and _EXCEPTION.search(s['text']):added.append(s['id'])
125
+ keep=chosen|set(added);pruned=[]
126
+ if prune_withdrawn:
127
+ for s,ws in zip(spans,words):
128
+ if s['id'] not in keep or not _WITHDRAW.search(s['text']):continue
129
+ block=_withdrawn_block(text,s['text'])
130
+ if block is None:continue
131
+ key=ws&subject;about=_topic(ws,subject)
132
+ for t,tw in zip(spans,words):
133
+ if (t['id'] in keep and t['id']!=s['id'] and block[0]<=t['start'] and t['end']<=block[1]+2
134
+ and tw&key and tw&about and not _WITHDRAW.search(t['text'])):pruned.append(t['id'])
135
+ order=[s['id'] for s in spans];pruned=set(pruned)
136
+ return {'keep':[i for i in order if i in keep and i not in pruned],'added':[i for i in order if i in set(added)],
137
+ 'pruned':[i for i in order if i in pruned]}
138
+
139
+ def lexical_select(text,questions,limit=4):
140
+ source=candidates(text);chosen={}
141
+ for q in questions:
142
+ for candidate in rank_candidates(q,source,limit):
143
+ if candidate['candidate_score']>0:chosen[candidate['id']]=candidate
144
+ return {'evidence':sorted(chosen.values(),key=lambda c:c['start']),
145
+ 'method':'lexical_overlap','verification':'retrieval_only','faithfulness_established':False}
146
+
147
+ def remove(text,spans):
148
+ spans=merge(text,spans);cursor=0;parts=[]
149
+ for s in spans:parts.append(text[cursor:s['start']]);cursor=s['end']
150
+ parts.append(text[cursor:]);return ''.join(parts)
src/solomon/routing.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Real callback-driven escalation. Internal budget/escalation layer: the answer
2
+ contract above it always answers and refuses to emit any deferral field."""
3
+ from dataclasses import dataclass
4
+ import math
5
+ from numbers import Integral, Real
6
+
7
+ @dataclass(frozen=True)
8
+ class Budget:
9
+ branches: int = 8
10
+ input_tokens: int = 8192
11
+ generated_tokens: int = 3072
12
+
13
+
14
+ def route(stages, budget=Budget()):
15
+ """stages are (name, reserved_cost, callback). Callback returns answer/confidence/cost.
16
+
17
+ Reservations are hard maxima enforced by the backend, not optimistic estimates.
18
+ Callbacks must honor the reservation passed to them. Overspending fails closed.
19
+ """
20
+ used = {'branches':0,'input_tokens':0,'generated_tokens':0}
21
+ valid_cost=lambda value:isinstance(value,Integral) and not isinstance(value,bool) and value>=0
22
+ valid_probability=lambda value:isinstance(value,Real) and not isinstance(value,bool) and math.isfinite(value) and 0<=value<=1
23
+ if any(not valid_cost(getattr(budget,k)) for k in used):
24
+ raise ValueError('invalid compute budget')
25
+ traces, last = [], None
26
+ reasons = {'fast':'full_depth','views':'escalated_views','reasoning':'escalated_reasoning','exit':'early_exit'}
27
+ for name,reserve,call in stages:
28
+ if name not in reasons or set(reserve)!=set(used) or any(not valid_cost(v) for v in reserve.values()):
29
+ raise ValueError('invalid stage reservation')
30
+ if any(used[k]+reserve.get(k,0) > getattr(budget,k) for k in used):
31
+ return {'answer':None,'candidate':last,'abstained':True,'compute':{'stop_reason':'budget_exhausted','cost':used,'stages':traces}}
32
+ result = call(dict(reserve))
33
+ cost = result['cost']
34
+ if set(cost)!=set(used) or any(not valid_cost(cost[k]) or cost[k] > reserve[k] for k in used):
35
+ raise ValueError('backend exceeded reserved compute budget')
36
+ for k in used:
37
+ used[k] += cost.get(k,0)
38
+ last = result.get('answer')
39
+ confidence = result.get('confidence') or {}
40
+ if not isinstance(confidence,dict):
41
+ confidence={}
42
+ traces.append({'stage':name,'cost':cost,'confidence':confidence})
43
+ certified = confidence.get('calibration_support') == 'in_validated_scope' and confidence.get('policy_status') == 'confirmed'
44
+ accepted = (certified and last is not None and valid_probability(confidence.get('reliability'))
45
+ and valid_probability(confidence.get('threshold')) and confidence['reliability'] >= confidence['threshold'])
46
+ if accepted:
47
+ return {'answer':last,'abstained':False,'confidence':confidence,'compute':{'stop_reason':reasons[name],'cost':used,'stages':traces}}
48
+ return {'answer':None,'candidate':last,'abstained':True,'compute':{'stop_reason':'abstain','cost':used,'stages':traces}}
49
+
50
+
51
+ def forced_answer_suffix(trace):
52
+ """Backend appends this to a capped trace and performs a letter-logit forward."""
53
+ return ('' if '</think>' in trace else '\n</think>') + '\nAnswer (one letter):'
src/solomon/semantics.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Solomon answer semantics (design note, not distributed).
2
+
3
+ Yes/no, entity and multi-label candidates are Nouls: one probability P(yes). Gold yes only when the
4
+ document clearly establishes it; not stated and conflicting are no. Choice (single, ordered) is a
5
+ distribution over the listed options only; reserved-gold items have no Solomon target.
6
+
7
+ Works for both readouts: four_collapsed (four-state letter logits A/B/C/D, collapsed) and two_letter (A/B).
8
+ """
9
+ import numpy as np
10
+
11
+ YES, NO, NOT_STATED, CONFLICTING = 0, 1, 2, 3
12
+
13
+
14
+ def softmax(x, t=1.0):
15
+ z = np.asarray(x, np.float64) / t
16
+ z = z - z.max()
17
+ e = np.exp(z)
18
+ return e / e.sum()
19
+
20
+
21
+ def noul_gold(gold4):
22
+ """Four-state (or two-state) gold -> 1 for yes, 0 for no."""
23
+ return int(int(gold4) == YES)
24
+
25
+
26
+ def noul_logit(letter_logits):
27
+ """Binary log-odds z = log P(yes)/P(no) of a Noul branch: letter A against everything else."""
28
+ logits = np.asarray(letter_logits, np.float64)
29
+ if len(logits) not in (2, 4):
30
+ raise ValueError(f'Noul branch must have 2 or 4 letters, got {len(logits)}')
31
+ rest = logits[1:] - logits[1:].max()
32
+ return float(logits[YES] - (logits[1:].max() + np.log(np.exp(rest).sum())))
33
+
34
+
35
+ def p_yes(letter_logits, t=1.0):
36
+ """P(yes) from a Noul branch: letter A of a 2-letter (two_letter) or 4-state (four_collapsed) readout.
37
+
38
+ Temperature applies to the COLLAPSED binary logit, not to the letters: a Noul is a binary unit whose
39
+ 'no' mass may be spread over several reserved letters, so p_yes(t) = sigmoid(z/t) with z = noul_logit.
40
+ At t = 1 this is exactly softmax over the letters at A (the two forms only differ once t != 1, where the
41
+ letterwise form would decay toward 1/len(letters) instead of toward 1/2). Solomon.qualification.p_yes and
42
+ abstention_refit/readout.py fit and evaluate the collapsed form, so the serving path must match it.
43
+ """
44
+ logits = np.asarray(letter_logits, np.float64)
45
+ if len(logits) not in (2, 4):
46
+ raise ValueError(f'Noul branch must have 2 or 4 letters, got {len(logits)}')
47
+ if t == 1.0:
48
+ return float(softmax(logits)[YES])
49
+ z = noul_logit(logits) / float(t)
50
+ return float(1.0 / (1.0 + np.exp(-z))) if z > -700 else 0.0
51
+
52
+
53
+ def noul_confidence(p):
54
+ return max(p, 1.0 - p)
55
+
56
+
57
+ def listed_gold(gold, n_options):
58
+ """Listed option index, or None when the old gold was a reserved slot (not stated / none-of-listed / conflicting)."""
59
+ return int(gold) if isinstance(gold, (int, np.integer)) and 0 <= int(gold) < n_options else None
60
+
61
+
62
+ def listed_probs(letter_logits, n_options, t=1.0):
63
+ """Choice distribution over the listed options only (reserved slots, if present, are discarded)."""
64
+ return softmax(np.asarray(letter_logits, np.float64)[:n_options], t)
65
+
66
+
67
+ def complement_deviation(p, p_negated):
68
+ """G3a under Solomon: a statement and its negation should sum to 1."""
69
+ return abs(p - (1.0 - p_negated))
src/solomon/service.py ADDED
@@ -0,0 +1,535 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Solomon decision layer: the Solomon serving contract over the pinned readout chain.
2
+
3
+ A new layer over the unchanged, hash-pinned serving chain:
4
+ PackageEvidenceService (solomon/service_packages) -> ConfidenceHeadsService (solomon/serving) -> HeadsService
5
+ (solomon/service_heads) -> solomon/service_answers -> the answer contract readout -> engine (solomon/engine).
6
+ None of those files is edited. The layer does three things the chain cannot:
7
+
8
+ 1. Engine proxy (`_EngineProxy`), passed to the chain instead of the raw engine:
9
+ - records the real letter logits and hidden state of every answer branch (so the layer reads P(yes) / listed
10
+ probabilities itself, rather than trusting the pinned chain's own four-state reading);
11
+ - in 'two_letter' mode rewrites each four-state Noul prompt (BOOLEAN_TASK / LABEL header) to the registered
12
+ two-letter A=yes / B=no header and passes the semantic head key explicitly (the pinned
13
+ `semantic_head_key` routes by prompt prefix and would raise on the new header). The 2 real logits are padded
14
+ with a finite -1e4 to the 4 letters the pinned readout expects; padding never reaches a Solomon response;
15
+ - answers the S-form sufficiency block synthetically ("A", zero tokens, no model call): the sufficiency branch is
16
+ removed from Solomon (the design note). Only listed-option probabilities are read.
17
+ - returns reliability None from `predict_correctness`: the old four-state correctness head is never applied.
18
+ 2. The serving stack is bound to the stack that was measured (`RuntimeBinding`): every key of the binding's
19
+ `runtime` must equal the live engine identity, or the service refuses to load. That is the only safety
20
+ property this layer enforces, and it is enforced before a single question is asked.
21
+ 3. The request/response shapes of the serving contract (see `parse_questions` and solomon/api.py).
22
+
23
+ v1.1 semantics -- THE MODEL ALWAYS ANSWERS. There is no abstention, no threshold, no policy freeze and no fitted
24
+ correctness head anywhere on this path. Every question of every answer type is answered with a probability, and
25
+ entity / multi-label questions return one probability per candidate, which is the unit they are accurate at.
26
+ The probabilities ORDER well and their MAGNITUDE overstates reliability at the top of the range (see
27
+ ORDERING_DISCLOSURE). That is disclosed, not gated on, and no response field may read as a certified error rate.
28
+
29
+ Readout modes (named by the selection file, see `load_selection`):
30
+ four_collapsed the four-state prompts; P(yes) = softmax over the 4 letters [A]; choice renormalised over the
31
+ listed options (reserved R slots dropped). This is the shipped readout.
32
+ two_letter two-letter prompts (A = yes, B = no); P(yes) = softmax over 2 letters [A]; choice S (listed).
33
+ """
34
+ from solomon.binding import (BINDING_SCHEMA, CONTRACT, DEFAULT_BINDING, DESIGN_FREEZE, MODES, # noqa: F401
35
+ SELECTION, RuntimeBinding, TwoLetterPrompts, UnboundServing, default_design,
36
+ load_binding, load_prompts, load_selection)
37
+ from solomon.calibration import (ROOT, TEMPERATURE, TEMPERATURE_SCHEMA, TEMPERATURE_SCHEMAS, # noqa: F401
38
+ TEMPERATURE_TASKS, NoTemperature, ReadoutTemperature, _all_keys,
39
+ _structural_keys, digest, load_temperature)
40
+ import copy
41
+ import hashlib
42
+ import importlib
43
+ import json
44
+ import math
45
+ from pathlib import Path
46
+
47
+ import numpy as np
48
+
49
+ from solomon.engine_contract import BOOLEAN_TASK, LABEL, SUFFICIENCY
50
+ from solomon.heads import semantic_head_key
51
+ from solomon import semantics as sem
52
+
53
+ PAD = -1e4
54
+ MAX_CANDIDATES = 64
55
+ # Response keys that must never appear in a Solomon answer (the design note: no reserved labels).
56
+ RESERVED_KEYS = ('not_stated', 'conflicting', 'none_of_listed', 'sufficiency', 'evidence_sufficiency')
57
+ # Response keys that would reintroduce abstention or imply a certified error rate. Nothing may emit these (v1.1).
58
+ FORBIDDEN_KEYS = ('abstain', 'abstain_reason', 'abstention', 'confidence', 'confidence_source', 'policy_status',
59
+ 'threshold', 'certified_error_rate', 'error_rate_guarantee', 'calibration_guarantee',
60
+ 'guaranteed_accuracy', 'certified_accuracy')
61
+ ORDERING_DISCLOSURE = (
62
+ 'ordering_score is the readout\'s own top-class probability, read off the per-task temperature-scaled softmax. '
63
+ 'It has no fitted decision behind it and it certifies nothing. IT MEANS TWO DIFFERENT THINGS depending on how '
64
+ 'many units the question has. SINGLE-UNIT (a yes/no question, a single or ordered choice, and EVERY '
65
+ 'per-candidate value inside an entity or multi-label answer): the score is exactly the tempered readout '
66
+ 'probability, and a held-out panel of 1,500 fresh documents, never seen by the fit, says that is a usable '
67
+ 'CALIBRATED MAGNITUDE, honest to mildly conservative in the top bin on every task, largest understatement '
68
+ '+0.00078. MULTI-UNIT, i.e. the rolled-up question-level score for an entity or multi-label question with more '
69
+ 'than one candidate: it is the PRODUCT of the per-unit probabilities, which assumes the units are independent. '
70
+ 'That assumption has never been validated as a joint probability. It orders such questions well and it is a '
71
+ 'HEURISTIC ORDERING, not a calibrated probability -- read the per-candidate numbers if you need a magnitude. '
72
+ 'WEAKEST CELL: boolean still carries 14.3% of its errors above a stated 0.99 (ordered 4.8%, multi-label 13.9%, '
73
+ 'entity 3.2%), so a boolean answer above 0.99 is worth less than an entity candidate above 0.99. All of this '
74
+ 'is measured behaviour on fresh panels, NOT a certified error rate, and nothing here is guaranteed. Every '
75
+ 'question is answered; nothing abstains.')
76
+
77
+
78
+ # ------------------------------------------------------------------ engine proxy
79
+ class _EngineProxy:
80
+ """See module docstring. Phases: 'idle' (ignore), 'answer' (record rows), 'evidence' (record fresh-prefill segments)."""
81
+
82
+ def __init__(self, engine, mode, prompts=None):
83
+ if mode not in MODES:
84
+ raise ValueError('unknown readout mode')
85
+ if mode == 'two_letter' and prompts is None:
86
+ raise ValueError('two_letter mode requires two-letter prompts')
87
+ self._engine, self._mode, self._prompts = engine, mode, prompts
88
+ self._task = None
89
+ self.phase = 'idle'
90
+ self.rows = []
91
+ self.segments = []
92
+
93
+ def __getattr__(self, name):
94
+ return getattr(self._engine, name)
95
+
96
+ def reset(self):
97
+ self.phase = 'idle'; self.rows = []; self.segments = []
98
+
99
+ def task_context(self, task):
100
+ from contextlib import contextmanager
101
+
102
+ @contextmanager
103
+ def context():
104
+ previous = self._task; self._task = task
105
+ try:
106
+ with self._engine.task_context(task):
107
+ yield self
108
+ finally:
109
+ self._task = previous
110
+ return context()
111
+
112
+ def prefill(self, *args, **kwargs):
113
+ state = self._engine.prefill(*args, **kwargs)
114
+ if self.phase == 'evidence':
115
+ self.segments.append([])
116
+ return state
117
+
118
+ def predict_correctness(self, task, branches):
119
+ return {'reliability': None}
120
+
121
+ def estimate(self, state, block, n, stage='fast', max_new_tokens=512):
122
+ if block.startswith(SUFFICIENCY):
123
+ return {'input_tokens': 0, 'generated_tokens': 0, 'branches': 1, 'full_prompt_tokens': 0,
124
+ 'reused_prefix_tokens': state.get('prefix_tokens', 0) if isinstance(state, dict) else 0}
125
+ if self._mode == 'two_letter':
126
+ swapped = self._prompts.rewrite(self._task, block)
127
+ if swapped is not None:
128
+ block, n = swapped
129
+ return self._engine.estimate(state, block, n, stage=stage, max_new_tokens=max_new_tokens)
130
+
131
+ def ask(self, state, block, n, execution='cached', head_key=None, **kwargs):
132
+ if block.startswith(SUFFICIENCY):
133
+ # Removed from Solomon: constant "sufficient", no model call, zero tokens.
134
+ logits = np.r_[0., PAD, PAD][:n]
135
+ p = np.exp(logits - logits.max()); p /= p.sum()
136
+ return {'letter_logits': logits, 'probabilities': p, 'prediction': 0, 'hidden': None, 'head_key': None,
137
+ 'mass': None, 'top_is_letter': None, 'mass_available': False, 'execution': execution, 'fallback': 'solomon-removed',
138
+ 'prompt_tokens': 0, 'branch_tokens': 0, 'input_tokens': 0, 'reused_prefix_tokens': 0, 'generation_tokens': 0,
139
+ 'synthetic': True, 'fingerprint': self._engine.identity.get('fingerprint')}
140
+ width = n
141
+ if self._mode == 'two_letter':
142
+ swapped = self._prompts.rewrite(self._task, block)
143
+ if swapped is not None:
144
+ head_key = head_key or semantic_head_key(self._task, block)
145
+ block, width = swapped
146
+ row = (self._engine.ask(state, block, width, execution=execution, head_key=head_key, **kwargs) if head_key is not None
147
+ else self._engine.ask(state, block, width, execution=execution, **kwargs))
148
+ logits = np.asarray(row['letter_logits'], np.float64)
149
+ if logits.shape != (width,) or not np.isfinite(logits).all():
150
+ raise ValueError('engine returned invalid letter logits')
151
+ record = {'block': block, 'task': self._task, 'letter_logits': logits.copy(), 'hidden': row.get('hidden'),
152
+ 'head_key': row.get('head_key', head_key), 'input_tokens': int(row.get('input_tokens', row.get('branch_tokens', 0))),
153
+ 'execution': execution}
154
+ if self.phase == 'answer':
155
+ self.rows.append(record)
156
+ elif self.phase == 'evidence':
157
+ if not self.segments:
158
+ self.segments.append([])
159
+ self.segments[-1].append(record)
160
+ if width == n:
161
+ return row
162
+ padded = np.r_[logits, np.full(n - width, PAD)]
163
+ p = np.exp(padded - padded.max()); p /= p.sum()
164
+ return {**row, 'letter_logits': padded, 'probabilities': p, 'prediction': int(p.argmax())}
165
+
166
+
167
+ class _PhasedAnswers:
168
+ """Wraps the ConfidenceHeadsService so the proxy knows which branches belong to the answer."""
169
+
170
+ def __init__(self, answers, proxy):
171
+ self._answers, self._proxy = answers, proxy
172
+
173
+ def __getattr__(self, name):
174
+ return getattr(self._answers, name)
175
+
176
+ def ask(self, *args, **kwargs):
177
+ self._proxy.phase = 'answer'
178
+ try:
179
+ return self._answers.ask(*args, **kwargs)
180
+ finally:
181
+ self._proxy.phase = 'evidence'
182
+
183
+
184
+ # ------------------------------------------------------------------ identity binding and the ordering score
185
+ def ordering_score(distributions):
186
+ """The readout's own top-class probability, multiplied over the units of a question.
187
+
188
+ Read ORDERING_DISCLOSURE before using this number. The short version, and the reason this is not called
189
+ `probability`:
190
+
191
+ * ONE unit -> the score IS the tempered readout probability; the held-out panel validates it as a calibrated magnitude.
192
+ This covers yes/no, single and ordered choice, and every PER-CANDIDATE value that entity and
193
+ multi-label answers report in `candidates` / `candidate_ordering_scores`.
194
+ * MANY units -> the score is a product across units, which assumes they are independent. That assumption has
195
+ never been validated as a joint probability. It orders well; it is not a calibrated joint.
196
+ Only the rolled-up question-level number for a multi-candidate entity or multi-label question
197
+ is affected -- the per-candidate numbers beside it are single-unit and calibrated.
198
+
199
+ Naming it `probability` would be right for the single-unit case and would overclaim for the multi-unit one,
200
+ which is the wrong direction to be wrong in on a serving path with no abstention behind it.
201
+
202
+ Delegates the per-unit statement to solomon.reliability so there is one implementation of "what the readout says
203
+ about itself"; the qualification side uses the same function. No fitted parameters beyond the temperature."""
204
+ from solomon import reliability as R
205
+ units = []
206
+ for d in distributions:
207
+ d = np.asarray(d, float)
208
+ units.append({'kind': 'choice', 'logits': np.log(np.maximum(d, 1e-300))})
209
+ return R.question_reliability(units, 1.0)
210
+
211
+
212
+ def forbidden_keys(value):
213
+ """Every FORBIDDEN_KEYS / RESERVED_KEYS name anywhere in a response. Must always be empty (v1.1)."""
214
+ return _all_keys(value) & set(FORBIDDEN_KEYS + RESERVED_KEYS)
215
+
216
+
217
+ # ------------------------------------------------------------------ request parsing
218
+ def _text(value, name):
219
+ if not isinstance(value, str) or not value.strip():
220
+ raise ValueError(name + ' must be a nonempty string')
221
+ return value
222
+
223
+
224
+ def parse_questions(questions):
225
+ """Questions {id: spec} -> ordered list of normalised specs.
226
+
227
+ noul: {"type": "noul", "instructions": str} -> task boolean
228
+ {"type": "noul", "instructions": "Is {candidate} ...?", "candidates": [...]} -> task entity (one Noul per candidate)
229
+ {"type": "noul", "instructions": str, "candidates": [...], "candidate_kind": "label"} -> task multilabel
230
+ (candidate_kind defaults to 'entity' when instructions contain {candidate}, else 'label')
231
+ choice: {"type": "choice", "instructions": str, "options": [str, ...] | {key: text}, "ordered": bool}
232
+ ('criteria' is accepted as a compatibility alias of 'options')
233
+ score: {"type": "score", "instructions": str, "levels": [str, ...]} (alias 'criteria'); an ordered choice keyed
234
+ "0".."K-1" with a legend and score = sum_i i * p_i.
235
+ """
236
+ if not isinstance(questions, dict) or not questions:
237
+ raise ValueError('questions must be a nonempty mapping of id -> question')
238
+ out = []
239
+ for qid, spec in questions.items():
240
+ if not isinstance(qid, str) or not qid:
241
+ raise ValueError('question ids must be nonempty strings')
242
+ if isinstance(spec, str):
243
+ spec = {'type': 'noul', 'instructions': spec}
244
+ if not isinstance(spec, dict):
245
+ raise ValueError(f'question {qid}: spec must be an object')
246
+ kind = str(spec.get('type', 'noul')).lower()
247
+ instructions = _text(spec.get('instructions', spec.get('question')), f'question {qid}: instructions')
248
+ if kind == 'noul':
249
+ if 'candidates' not in spec:
250
+ out.append({'id': qid, 'type': 'noul', 'task': 'boolean', 'request': {'question': instructions}})
251
+ continue
252
+ candidates = spec['candidates']
253
+ if (not isinstance(candidates, list) or not 1 <= len(candidates) <= MAX_CANDIDATES or len(set(candidates)) != len(candidates)
254
+ or any(not isinstance(c, str) or not c.strip() for c in candidates)):
255
+ raise ValueError(f'question {qid}: candidates must be 1 to {MAX_CANDIDATES} distinct nonempty strings')
256
+ ckind = spec.get('candidate_kind', 'entity' if '{candidate}' in instructions else 'label')
257
+ if ckind == 'entity':
258
+ if instructions.count('{candidate}') != 1 or '{entity}' in instructions:
259
+ raise ValueError(f'question {qid}: entity instructions need exactly one {{candidate}} placeholder')
260
+ request = {'template': instructions.replace('{candidate}', '{entity}'), 'entities': list(candidates)}
261
+ task = 'entity'
262
+ elif ckind == 'label':
263
+ if '{candidate}' in instructions:
264
+ raise ValueError(f'question {qid}: label candidates take no {{candidate}} placeholder')
265
+ request = {'question': instructions, 'labels': list(candidates)}
266
+ task = 'multilabel'
267
+ else:
268
+ raise ValueError(f'question {qid}: candidate_kind must be entity or label')
269
+ out.append({'id': qid, 'type': 'noul', 'task': task, 'candidates': list(candidates), 'request': request})
270
+ elif kind in ('choice', 'score'):
271
+ raw = spec.get('levels', spec.get('options', spec.get('criteria'))) if kind == 'score' else spec.get('options', spec.get('criteria'))
272
+ if isinstance(raw, dict):
273
+ keys, texts = [str(k) for k in raw], [raw[k] if isinstance(raw[k], str) and raw[k].strip() else str(k) for k in raw]
274
+ elif isinstance(raw, list):
275
+ texts = list(raw); keys = [str(i) for i in range(len(raw))] if kind == 'score' else list(raw)
276
+ else:
277
+ raise ValueError(f'question {qid}: options must be a list or a mapping')
278
+ if not 2 <= len(texts) <= 8 or any(not isinstance(t, str) or not t.strip() for t in texts) or len(set(texts)) != len(texts):
279
+ raise ValueError(f'question {qid}: provide 2 to 8 distinct nonempty options')
280
+ ordered = kind == 'score' or bool(spec.get('ordered', False))
281
+ if not isinstance(spec.get('ordered', False), bool):
282
+ raise ValueError(f'question {qid}: ordered must be Boolean')
283
+ out.append({'id': qid, 'type': kind, 'task': 'ordered' if ordered else 'single', 'keys': keys, 'texts': texts,
284
+ 'request': {'question': instructions, 'options': texts}})
285
+ else:
286
+ raise ValueError(f'question {qid}: type must be noul, choice or score')
287
+ return out
288
+
289
+
290
+ def _state_parts(state):
291
+ if isinstance(state, str):
292
+ return [{'text': state}]
293
+ if isinstance(state, list):
294
+ return state
295
+ if isinstance(state, dict):
296
+ return [{'text': json.dumps(state, ensure_ascii=False, indent=2, sort_keys=False)}]
297
+ raise ValueError('state must be text, an object, or a list of document parts')
298
+
299
+
300
+ # ------------------------------------------------------------------ the layer
301
+ class SolomonService:
302
+ def __init__(self, api, proxy, *, mode, design, binding, prompts=None, selection=None, temperature=None):
303
+ self.api, self.proxy, self.mode, self.design = api, proxy, mode, copy.deepcopy(design)
304
+ self.binding, self.prompts, self.selection = binding, prompts, selection
305
+ # An explicit temperature= overrides the binding's (development and tests only); otherwise the bound one.
306
+ self.calibration = load_temperature(temperature) if temperature is not None else binding.calibration
307
+ if self.design.get('single_choice') not in ('R', 'S') or self.design.get('ordered') not in ('R', 'S'):
308
+ raise ValueError('Solomon serves the R or S listwise readout only')
309
+
310
+ @property
311
+ def runtime_identity(self):
312
+ return self.api.runtime_identity
313
+
314
+ def temperature(self, task, head_keys=()):
315
+ """The readout temperature actually applied to this task's logits, verified against the served head keys."""
316
+ return self.calibration.temperature(task, head_keys)
317
+
318
+ def health(self):
319
+ return {'contract': CONTRACT, 'readout': self.mode, 'question_types': ['noul', 'choice', 'score'],
320
+ 'noul_candidate_kinds': ['entity', 'label'], 'evidence_levels': ['none', 'support', 'sufficiency', 'removal'],
321
+ 'answer_policy': 'always_answers',
322
+ 'ordering_score_semantics': ORDERING_DISCLOSURE,
323
+ 'calibration': self.calibration.describe(),
324
+ 'design': self.design, 'binding': self.binding.describe(),
325
+ 'prompts_sha256': self.prompts.sha256 if self.prompts is not None else None,
326
+ 'selection_sha256': (self.selection or {}).get('sha256'), 'runtime_identity': copy.deepcopy(self.runtime_identity)}
327
+
328
+ def create(self, state):
329
+ result = self.api.create(_state_parts(state))
330
+ return {'state_id': result['state_id'], 'contract': CONTRACT, 'document_sha256': result.get('document_sha256')}
331
+
332
+ def decide(self, *, questions, state=None, state_id=None, population=None, evidence='support', evidence_max_calls=64,
333
+ evidence_detail=False, budget=None):
334
+ specs = parse_questions(questions)
335
+ if (state is None) == (state_id is None):
336
+ raise ValueError('provide exactly one of state or state_id')
337
+ if evidence not in ('none', 'support', 'sufficiency', 'removal'):
338
+ raise ValueError('invalid evidence level')
339
+ if population is not None and (not isinstance(population, str) or not population):
340
+ raise ValueError('population must be a nonempty string')
341
+ if type(evidence_detail) is not bool:
342
+ raise ValueError('evidence_detail must be Boolean')
343
+ key = state_id if state_id is not None else self.create(state)['state_id']
344
+ answers, usage = {}, {'branches': 0, 'input_tokens': 0, 'document_prefill_tokens': 0, 'evidence_calls': 0}
345
+ for spec in specs:
346
+ answer, cost = self._one(key, spec, population=population, evidence=evidence, evidence_max_calls=evidence_max_calls,
347
+ evidence_detail=evidence_detail, budget=budget)
348
+ answers[spec['id']] = answer
349
+ for k in usage:
350
+ usage[k] += cost.get(k, 0)
351
+ out = {'contract': CONTRACT, 'readout': self.mode, 'state_id': key, 'answers': answers, 'usage': usage,
352
+ 'answer_policy': 'always_answers', 'ordering_score_semantics': ORDERING_DISCLOSURE,
353
+ 'binding': self.binding.describe(), 'runtime_fingerprint': self.runtime_identity.get('fingerprint')}
354
+ bad = forbidden_keys(out) # structural: a response can never carry abstention or a certified rate
355
+ if bad:
356
+ raise ValueError('response carries forbidden fields: ' + ', '.join(sorted(bad)))
357
+ return out
358
+
359
+ # -------------------------------------------------------------- one question
360
+ def _budget(self, spec, budget):
361
+ if budget is not None:
362
+ return budget
363
+ units = len(spec.get('candidates', [])) or 1
364
+ return {'branches': units + 1, 'input_tokens': 4096 * (units + 1), 'generated_tokens': 0}
365
+
366
+ def _one(self, key, spec, *, population, evidence, evidence_max_calls, evidence_detail, budget):
367
+ task = spec['task']
368
+ with self.api.answers.lock:
369
+ self.proxy.reset()
370
+ try:
371
+ result = self.api.ask(key, task, evidence=evidence, evidence_max_calls=evidence_max_calls,
372
+ budget=self._budget(spec, budget), population=population, question_id=spec['id'], **spec['request'])
373
+ rows, segments = self.proxy.rows, self.proxy.segments
374
+ state = self.api.answers._warm(key)
375
+ finally:
376
+ self.proxy.phase = 'idle'
377
+ cost = {'branches': len(rows), 'input_tokens': sum(r['input_tokens'] for r in rows),
378
+ 'document_prefill_tokens': (result.get('document_prefill') or {}).get('tokens', 0) or 0}
379
+ out = {'type': spec['type']}
380
+ if result.get('candidate') is None:
381
+ # Not an abstention: the caller's own branch/token budget stopped the chain before it produced anything.
382
+ stop = (result.get('compute') or {}).get('stop_reason', 'no_answer')
383
+ out.update(self._empty(spec), error=stop, ordering_score=None, evidence=[], evidence_status='not_run')
384
+ return out, cost
385
+ T = self.temperature(task, [r.get('head_key') for r in rows])
386
+ units = self._units(spec, rows, result['candidate'])
387
+ shown = self._distributions(spec, units, T)
388
+ out.update(self._present(spec, shown))
389
+ out['ordering_score'] = ordering_score(shown)
390
+ body = result.get('evidence')
391
+ out['temperature'] = float(T)
392
+ ev = self._evidence(spec, body, segments, out, T, evidence_detail)
393
+ cost['evidence_calls'] = ev.pop('_calls', 0)
394
+ out.update(ev)
395
+ return out, cost
396
+
397
+ def _units(self, spec, rows, candidate):
398
+ """Answer-branch logits per unit, cross-checked against the pinned chain's own candidate."""
399
+ task = spec['task']
400
+ n_units = len(spec.get('candidates', [])) or 1
401
+ if len(rows) != n_units:
402
+ raise ValueError(f'expected {n_units} answer branches, captured {len(rows)} (only R/S single-order designs are served)')
403
+ logits = [r['letter_logits'] for r in rows]
404
+ if task in ('boolean', 'entity', 'multilabel'):
405
+ width = 2 if self.mode == 'two_letter' else 4
406
+ if any(len(x) != width for x in logits):
407
+ raise ValueError('Noul branch width does not match the readout mode')
408
+ pinned = [candidate['probabilities']] if task == 'boolean' else candidate['probabilities']
409
+ for x, p in zip(logits, pinned):
410
+ if abs(sem.p_yes(x) - float(p[0])) > 1e-6:
411
+ raise ValueError('captured branch does not match the pinned candidate')
412
+ else:
413
+ n = len(spec['texts'])
414
+ p = np.asarray(candidate['probabilities'], float)
415
+ if len(logits[0]) < n or np.max(np.abs(sem.listed_probs(logits[0], n) - p[:n] / p[:n].sum())) > 1e-6:
416
+ raise ValueError('captured choice branch does not match the pinned candidate')
417
+ return logits
418
+
419
+ def _distributions(self, spec, units, T):
420
+ if spec['task'] in ('boolean', 'entity', 'multilabel'):
421
+ return [np.array([sem.p_yes(x, T), 1 - sem.p_yes(x, T)]) for x in units]
422
+ return [sem.listed_probs(units[0], len(spec['texts']), T)]
423
+
424
+ @staticmethod
425
+ def _empty(spec):
426
+ if spec['type'] == 'noul':
427
+ return {'candidates': None} if 'candidates' in spec else {'noul': None}
428
+ return {'probabilities': None, 'answer': None}
429
+
430
+ @staticmethod
431
+ def _present(spec, dists):
432
+ if spec['type'] == 'noul':
433
+ if 'candidates' in spec:
434
+ # Entity and multi-label are accurate per candidate, so the probability is reported per candidate
435
+ # and so is the ordering score. There is no single whole-question number for these types.
436
+ return {'candidate_kind': 'entity' if spec['task'] == 'entity' else 'label',
437
+ 'candidates': {c: float(d[0]) for c, d in zip(spec['candidates'], dists)},
438
+ 'candidate_ordering_scores': {c: float(max(d[0], 1 - d[0])) for c, d in zip(spec['candidates'], dists)}}
439
+ return {'noul': float(dists[0][0])}
440
+ p = dists[0]; keys = spec['keys']
441
+ out = {'probabilities': {k: float(v) for k, v in zip(keys, p)}, 'answer': keys[int(np.argmax(p))]}
442
+ out['choice'] = out['answer'] # compatibility alias of 'answer'
443
+ if spec['type'] == 'score':
444
+ out['score'] = float(np.dot(np.arange(len(p)), p))
445
+ out['legend'] = dict(zip(keys, spec['texts']))
446
+ elif spec['task'] == 'ordered':
447
+ out['ordered'] = True
448
+ return out
449
+
450
+ def _evidence(self, spec, body, segments, answer, T, detail):
451
+ if body is None:
452
+ return {'evidence': [], 'evidence_status': 'not_requested'}
453
+ status = body.get('status')
454
+ out = {'evidence_status': status, 'evidence': [], '_calls': int(body.get('calls', 0))}
455
+ if status in ('found', 'no_support_found'):
456
+ out['evidence'] = [{k: r[k] for k in ('start', 'end', 'text', 'page', 'path') if k in r} for r in body.get('references', [])]
457
+ if 'candidates' in spec and body.get('package_format') == 'per_unit' and len(body.get('packages', [])) == len(spec['candidates']):
458
+ out['candidate_evidence'] = {c: [{k: s[k] for k in ('start', 'end', 'text', 'pages') if k in s}
459
+ for s in p['spans'] if s.get('role') == 'evidence']
460
+ for c, p in zip(spec['candidates'], body['packages'])}
461
+ verification = self._verification(spec, body, segments, answer, T)
462
+ if verification:
463
+ out['evidence_verification'] = verification
464
+ if detail:
465
+ out['evidence_detail'] = {k: v for k, v in body.items() if k not in ('evidence_only', 'evidence_removed', 'union_package')}
466
+ return out
467
+
468
+ def _verification(self, spec, body, segments, answer, T):
469
+ """Evidence-only / evidence-removed re-asks in Solomon terms (from the captured fresh-prefill segments)."""
470
+ modes = [m for m in ('evidence_only', 'evidence_removed') if m in body]
471
+ if not modes:
472
+ return None
473
+ per_unit = 'evidence_only' in body and 'per_unit' in body['evidence_only']
474
+ calls = (len(body['evidence_only']['per_unit']) if per_unit else int('evidence_only' in body)) + int('evidence_removed' in body)
475
+ if len(segments) < calls:
476
+ raise ValueError('evidence re-ask branches were not captured')
477
+ used = segments[len(segments) - calls:]
478
+ groups = {}
479
+ if 'evidence_only' in body:
480
+ k = len(body['evidence_only']['per_unit']) if per_unit else 1
481
+ groups['evidence_only'] = [r for seg in used[:k] for r in seg]
482
+ if 'evidence_removed' in body:
483
+ groups['evidence_removed'] = used[-1]
484
+ out = {}
485
+ for mode, rows in groups.items():
486
+ n_units = len(spec.get('candidates', [])) or 1
487
+ if len(rows) != n_units:
488
+ raise ValueError(f'{mode}: expected {n_units} branches, captured {len(rows)}')
489
+ dists = self._distributions(spec, [r['letter_logits'] for r in rows], T)
490
+ shown = self._present(spec, dists)
491
+ shown.pop('choice', None)
492
+ shown.pop('candidate_ordering_scores', None)
493
+ out[mode] = {**shown, 'agrees_with_full': self._decision(spec, shown) == self._decision(spec, answer)}
494
+ return out
495
+
496
+ @staticmethod
497
+ def _decision(spec, shown):
498
+ if spec['type'] == 'noul':
499
+ if 'candidates' in spec:
500
+ return {c: p >= .5 for c, p in shown['candidates'].items()}
501
+ return shown['noul'] >= .5
502
+ return shown['answer']
503
+
504
+
505
+ def service(store, engine, *, selection=SELECTION, mode=None, design=None, prompts=None, binding=None, temperature=None,
506
+ selector=None, page_selector=None, page_maps=None, size_cap=None, package_format='per_unit'):
507
+ """Build the pinned chain around a proxied engine and wrap it in the Solomon layer.
508
+
509
+ mode/design/prompts/binding override selection.json (for tests and development); binding may be a path, a
510
+ binding object, or None (selection 'binding' key, else DEFAULT_BINDING, else UnboundServing). A binding that
511
+ is present but does not match the live runtime identity raises here, before any question is asked.
512
+ """
513
+ from solomon.serving import ConfidenceHeadsService, FreshDecider
514
+ from solomon.service_packages import PackageEvidenceService, SIZE_CAP
515
+ chosen = None
516
+ if mode is None:
517
+ chosen = load_selection(selection)
518
+ mode = chosen['mode']
519
+ design = design or chosen['design']
520
+ prompts = prompts if prompts is not None else chosen['prompts']
521
+ binding = binding if binding is not None else chosen['binding']
522
+ if isinstance(binding, str) and not Path(binding).is_absolute() and (Path(chosen['dir']) / binding).exists():
523
+ binding = Path(chosen['dir']) / binding # the selection names a binding beside itself
524
+ if mode not in MODES:
525
+ raise ValueError('unknown readout mode')
526
+ design = copy.deepcopy(design or default_design(mode))
527
+ prompt_set = load_prompts(prompts) if mode == 'two_letter' else None
528
+ proxy = _EngineProxy(engine, mode, prompt_set)
529
+ answers = ConfidenceHeadsService(store, proxy, design)
530
+ api = PackageEvidenceService(_PhasedAnswers(answers, proxy), FreshDecider(proxy, design, Path(store) / '.evidence-readout'),
531
+ selector, page_selector, page_maps=page_maps, size_cap=size_cap or SIZE_CAP, package_format=package_format)
532
+ runtime = answers.runtime_identity
533
+ loaded = load_binding(binding, mode=mode, runtime=runtime, design=design, prompts_sha256=prompt_set.sha256 if prompt_set else None)
534
+ return SolomonService(api, proxy, mode=mode, design=design, binding=loaded, prompts=prompt_set, selection=chosen,
535
+ temperature=temperature)
src/solomon/service_answers.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Confidence-aware five-task service, reusing immutable answer-contract input persistence.
2
+
3
+ The confidence predictor is an injected pure CPU callback:
4
+ predictor(artifact, event, expected_identity) -> confidence mapping
5
+ Event contains the whole answer, branch distributions/logits, optional measured
6
+ views, task/modality, prefix length, stage and cumulative executed history.
7
+ Artifacts are checksummed envelopes {identity, policy_status, ... , sha256}.
8
+ No artifact/callback means unqualified candidates, never accepted answers.
9
+ Compute budgets cover question branches, including forced reasoning suffixes;
10
+ one-time document prefill is reported separately and is not a question branch.
11
+ """
12
+ import copy
13
+ import hashlib
14
+ import inspect
15
+ import json
16
+ from pathlib import Path
17
+
18
+ import numpy as np
19
+
20
+ from solomon.service_checked import Service as StateService, handler as state_handler
21
+ from solomon.service_states import Service as ReadoutService
22
+ from solomon.engine_contract import four_state_block, listwise_block
23
+ from solomon.readout import order_set, softmax
24
+ from solomon.routing import Budget, route
25
+
26
+ TASKS=('boolean','single','ordered','multilabel','entity')
27
+ COST_KEYS=('branches','input_tokens','generated_tokens')
28
+
29
+
30
+ def digest(value):
31
+ return hashlib.sha256(json.dumps(value,sort_keys=True,separators=(',',':'),allow_nan=False).encode()).hexdigest()
32
+
33
+
34
+ def _cost(value):
35
+ if not isinstance(value,dict) or any(type(value.get(k)) is not int or value[k]<0 for k in COST_KEYS):
36
+ raise ValueError('backend must provide nonnegative integer reservation costs')
37
+ return {k:value[k] for k in COST_KEYS}
38
+
39
+
40
+ def predict_confidence(artifact,event,identity):
41
+ """Default bridge to confidence_v2; task fits and support are explicit.
42
+
43
+ Envelope.tasks[task] supplies correctness, optional temperature, threshold,
44
+ status and support {modality, population, prefix_tokens:[min,max]}.
45
+ Fit identities equal expected_identity(stage) plus the task key. A feature
46
+ support box remains diagnostic and never establishes population membership.
47
+ """
48
+ from solomon.confidence import calibrate,features,predict
49
+ task=event['task']; cell=artifact.get('tasks',{}).get(task)
50
+ if not cell: return {'calibration_support':'unsupported_task','policy_status':'unsupported'}
51
+ fit_identity={**identity,'task':task}
52
+ source=event['branches'] if event['stage']!='views' else event['history'][0]['branches']
53
+ raw=[np.asarray(r['probabilities'],float) for r in source]
54
+ if task in ('single','ordered') and len(raw)==2:
55
+ p,q=raw
56
+ raw=[np.r_[q[0]*p,q[1:]]]
57
+ if task not in ('entity','multilabel') and len(raw)!=1:
58
+ raise ValueError('confidence does not support this readout composition')
59
+ if task in ('boolean','entity','multilabel'): suff=min(1-float(p[2]) for p in raw)
60
+ else: suff=1-float(raw[0][len(event['request']['options'])])
61
+ length=sum(len(p) for p in raw)
62
+ fs=[features(p,suff,event['disagreement'] or 0.,length) for p in raw]
63
+ aggregate=[min(f[0] for f in fs),min(f[1] for f in fs),max(f[2] for f in fs),suff,
64
+ event['disagreement'] or 0.,float(length)]
65
+ probability,in_box=predict(cell['correctness'],aggregate,fit_identity)
66
+ support=cell.get('support',{}); interval=support.get('prefix_tokens',[])
67
+ supported=(support.get('modality')==event['modality']=='text' and
68
+ isinstance(support.get('population'),str) and bool(support['population']) and
69
+ support['population']==event.get('population') and len(interval)==2 and
70
+ all(type(v) is int for v in interval) and interval[0]<=event['prefix_tokens']<=interval[1])
71
+ calibrated=None
72
+ if cell.get('temperature'):
73
+ # Temperature is fitted to the actual returned joint/marginal distributions.
74
+ calibrated=[calibrate(cell['temperature'],np.log(np.maximum(p,1e-300)),fit_identity).tolist() for p in raw]
75
+ return {'calibration_support':'in_validated_scope' if supported else 'outside_declared_population',
76
+ 'policy_status':cell.get('status','unqualified'),'reliability':probability,
77
+ 'threshold':cell.get('threshold'),'calibrated':bool(cell.get('distribution_confirmed',False)),
78
+ 'calibrated_distributions':calibrated,'feature_box_diagnostic':in_box,
79
+ 'support_population':support.get('population')}
80
+
81
+
82
+ class _Readout(ReadoutService):
83
+ def __init__(self,store,engine,design,state):
84
+ super().__init__(store,engine,design)
85
+ self.fixed_state=state
86
+ def _warm(self,key):
87
+ return self.fixed_state
88
+
89
+
90
+ class _Planner:
91
+ def __init__(self): self.calls=[]
92
+ def ask(self,state,block,n,execution='cached'):
93
+ self.calls.append((block,n))
94
+ return {'letter_logits':np.zeros(n),'branch_tokens':0}
95
+
96
+
97
+ class _Execute:
98
+ def __init__(self,service,stage,state,estimates):
99
+ self.service,self.stage,self.state,self.estimates=service,stage,state,estimates
100
+ self.rows=[]
101
+ def ask(self,state,block,n,execution='cached'):
102
+ index=len(self.rows)
103
+ if index>=len(self.estimates): raise ValueError('readout exceeded planned branches')
104
+ engine=self.service.backend
105
+ if self.stage=='reasoning':
106
+ row=engine.reason(state,block,n,max_tokens=self.service.reasoning_cap,execution=execution)
107
+ else: row=engine.ask(state,block,n,execution=execution)
108
+ logits=np.asarray(row.get('letter_logits'),dtype=float)
109
+ if logits.shape!=(n,) or not np.isfinite(logits).all(): raise ValueError('invalid stage logits')
110
+ generated=row.get('generation_tokens',0)
111
+ tokens=row.get('input_tokens',row.get('branch_tokens'))
112
+ cost=_cost({'branches':1,'input_tokens':tokens,'generated_tokens':generated})
113
+ if any(cost[k]>self.estimates[index][k] for k in COST_KEYS): raise ValueError('backend exceeded reserved compute budget')
114
+ clean={'letter_logits':logits.tolist(),'probabilities':softmax(logits).tolist(),'cost':cost,
115
+ 'prompt_tokens':row.get('prompt_tokens'),'finish_reason':row.get('finish_reason'),
116
+ 'forced_answer':row.get('forced_answer',False)}
117
+ self.rows.append(clean)
118
+ return {**row,'letter_logits':logits,'branch_tokens':tokens}
119
+
120
+
121
+ class Service(StateService):
122
+ def __init__(self,store,engine,design=None,*,artifacts=None,confidence_predictor=None,
123
+ reasoning_cap=512,enable_views=True,enable_reasoning=True,stage_recipe=None):
124
+ super().__init__(store,engine,design)
125
+ if type(reasoning_cap) is not int or not 1<=reasoning_cap<=3072: raise ValueError('invalid reasoning cap')
126
+ self.backend=engine
127
+ self.stage_recipe=copy.deepcopy(stage_recipe or {t:['fast','views','reasoning'] for t in TASKS})
128
+ if set(self.stage_recipe)!=set(TASKS) or any(not stages or stages[0]!='fast' or len(set(stages))!=len(stages) or any(x not in ('fast','views','reasoning') for x in stages) or stages != sorted(stages,key=('fast','views','reasoning').index) for stages in self.stage_recipe.values()): raise ValueError('invalid stage recipe')
129
+ self.reasoning_cap=reasoning_cap
130
+ self.enable_views=bool(enable_views)
131
+ self.enable_reasoning=bool(enable_reasoning)
132
+ self.confidence_predictor=confidence_predictor or predict_confidence
133
+ self.artifacts=copy.deepcopy(artifacts or {})
134
+ if not set(self.artifacts)<= {'fast','views','reasoning'}: raise ValueError('unknown artifact stage')
135
+ for stage,artifact in self.artifacts.items(): self._validate_artifact(stage,artifact)
136
+
137
+ def expected_identity(self,stage):
138
+ if stage not in ('fast','views','reasoning'): raise ValueError('unknown stage')
139
+ source=Path(__file__).resolve().parents[1]/'the answer contract'
140
+ result={'runtime':copy.deepcopy(self.runtime_identity),'design_sha256':self.design_sha256,
141
+ 'prompt_sha256':digest({name:hashlib.sha256((source/name).read_bytes()).hexdigest()
142
+ for name in ('engine.py','readout.py','service.py')}),
143
+ 'stage':stage,'stopping_policy':{'reasoning_cap':self.reasoning_cap,
144
+ 'enable_views':self.enable_views,'enable_reasoning':self.enable_reasoning,'stage_recipe':self.stage_recipe,
145
+ 'views':'boolean-supplied-paraphrase-or-single-order-set-v1'},
146
+ 'service_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
147
+ 'confidence_provider_sha256':hashlib.sha256(Path(inspect.getsourcefile(self.confidence_predictor)).read_bytes()).hexdigest()}
148
+ if stage=='reasoning':
149
+ value=getattr(self.backend,'reasoning_identity',None)
150
+ result['reasoning']=value() if callable(value) else None
151
+ return result
152
+
153
+ def _validate_artifact(self,stage,artifact):
154
+ if not isinstance(artifact,dict) or artifact.get('sha256')!=digest({k:v for k,v in artifact.items() if k!='sha256'}):
155
+ raise ValueError('confidence artifact checksum mismatch')
156
+ if artifact.get('identity')!=self.expected_identity(stage): raise ValueError('confidence artifact identity mismatch')
157
+
158
+ def create(self,document):
159
+ result=super().create(document)
160
+ result['contract']='solomon-answer-confidence-v2'
161
+ return result
162
+
163
+ def _confidence(self,stage,event):
164
+ artifact=self.artifacts.get(stage)
165
+ default={'calibration_support':'unsupported_modality' if event['modality']!='text' else 'unqualified',
166
+ 'policy_status':'unqualified','reliability':None,'threshold':None,
167
+ 'disagreement':event['disagreement'],'disagreement_available':event['disagreement'] is not None}
168
+ if artifact is None or self.confidence_predictor is None or event['modality']!='text': return default
169
+ self._validate_artifact(stage,artifact)
170
+ result=self.confidence_predictor(copy.deepcopy(artifact),copy.deepcopy(event),self.expected_identity(stage))
171
+ if not isinstance(result,dict): raise ValueError('confidence callback must return a mapping')
172
+ # The callback cannot promote an unconfirmed artifact to confirmed status.
173
+ result={**default,**result,'policy_status':(result.get('policy_status',artifact.get('policy_status','unqualified'))
174
+ if artifact.get('policy_status')=='confirmed' else artifact.get('policy_status','unqualified'))}
175
+ for key in ('reliability','threshold'):
176
+ value=result.get(key)
177
+ if value is not None and (isinstance(value,bool) or not isinstance(value,(int,float)) or not np.isfinite(value) or not 0<=value<=1):
178
+ raise ValueError('invalid '+key)
179
+ result['artifact_sha256']=artifact['sha256']
180
+ return result
181
+
182
+ @staticmethod
183
+ def _distribution_change(before,after):
184
+ if before is None or after is None or before is after: return None
185
+ a,b=before.get('probabilities'),after.get('probabilities')
186
+ if a is None or b is None: return None
187
+ a,b=np.asarray(a,float),np.asarray(b,float)
188
+ return float(np.abs(a-b).max()) if a.shape==b.shape else None
189
+
190
+ @staticmethod
191
+ def _sufficiency(task,answer,request):
192
+ # This is evidence availability, not confidence in correctness.
193
+ p=answer.get('probabilities')
194
+ if p is None: return None
195
+ if task in ('entity','multilabel'):
196
+ return min(1-float(row[2]) for row in p)
197
+ if task=='boolean': return 1-float(p[2])
198
+ n=len(request['options'])
199
+ return 1-float(p[n]) if len(p)==n+2 else None
200
+
201
+ def ask(self,key,task,*,budget=None,strict=True,paraphrase=None,question_id=None,population=None,**kwargs):
202
+ if type(strict) is not bool: raise ValueError('strict must be Boolean')
203
+ if kwargs.get('execution','cached')!='cached': raise ValueError('the confidence layer budgets require cached execution')
204
+ budget=Budget() if budget is None else Budget(**budget) if isinstance(budget,dict) else budget
205
+ if not isinstance(budget,Budget): raise ValueError('invalid compute budget')
206
+ # Validate request and create exact branch plan before any model operation.
207
+ planner=_Planner()
208
+ _Readout(self.store,planner,self.design,None).ask(key,task,**kwargs)
209
+ if paraphrase is not None and (task!='boolean' or not isinstance(paraphrase,str) or not paraphrase.strip()):
210
+ raise ValueError('paraphrase is a nonempty Boolean question')
211
+ if question_id is not None and (not isinstance(question_id,str) or not question_id): raise ValueError('invalid question id')
212
+ with self.lock:
213
+ self._check_runtime()
214
+ # Reject invalid and zero budgets before warming a document.
215
+ route([],budget)
216
+ if budget.branches< len(planner.calls):
217
+ result=route([('fast',{'branches':len(planner.calls),'input_tokens':0,'generated_tokens':0},lambda _:None)],budget)
218
+ return {**result,'state_id':key,'task':task,'strict':strict,'contract':'solomon-answer-confidence-v2'}
219
+ cold=self.state_id!=key
220
+ state=self._warm(key)
221
+ record=json.loads((self.store/key/'record.json').read_text())
222
+ image_count=sum('image' in p for p in record['document'])
223
+ modality='mixed' if image_count and image_count<len(record['document']) else 'image' if image_count else 'text'
224
+ prefix=state.get('prefix_tokens',0)
225
+ estimate=getattr(self.backend,'estimate',None)
226
+ if not callable(estimate): raise ValueError('backend needs exact pre-execution estimate for hard budgets')
227
+ history=[]; candidate=None; original=None; measured=None
228
+ def reservations(calls,stage):
229
+ estimates=[_cost(estimate(state,block,n,stage='reasoning' if stage=='reasoning' else 'fast',
230
+ max_new_tokens=self.reasoning_cap)) for block,n in calls]
231
+ return estimates,{k:sum(c[k] for c in estimates) for k in COST_KEYS}
232
+ def execute(stage,calls,estimates,reserve):
233
+ nonlocal candidate,original,measured
234
+ executor=_Execute(self,stage,state,estimates)
235
+ if stage=='views':
236
+ mapped=[]
237
+ for block,n,perm in view_calls:
238
+ row=executor.ask(state,block,n)
239
+ p=softmax(row['letter_logits']);q=p.copy()
240
+ if perm is not None:
241
+ for pos,index in enumerate(perm): q[index]=p[pos]
242
+ mapped.append(q.tolist())
243
+ basepred=original.get('prediction')
244
+ if task in ('single','ordered'):
245
+ n=len(kwargs['options'])
246
+ rawpred=n if basepred=='not_stated' else n+1 if basepred=='conflicting' else basepred
247
+ else: rawpred=basepred
248
+ measured=sum(int(np.argmax(p))!=rawpred for p in mapped)/len(mapped)
249
+ answer=copy.deepcopy(original)
250
+ answer['view_probabilities']=mapped
251
+ else:
252
+ answer=_Readout(self.store,executor,self.design,state).ask(key,task,**kwargs)
253
+ if stage=='fast': original=copy.deepcopy(answer)
254
+ candidate=answer
255
+ event={'task':task,'modality':modality,'stage':stage,'answer':answer,
256
+ 'branches':executor.rows,'prefix_tokens':prefix,'disagreement':measured if stage=='views' else None,
257
+ 'history':copy.deepcopy(history),'question_id':question_id,
258
+ 'request':copy.deepcopy(kwargs),'population':population,'candidate_before_stage':copy.deepcopy(original),
259
+ 'raw_probabilities':answer.get('probabilities'),
260
+ 'sufficiency':self._sufficiency(task,answer,kwargs)}
261
+ confidence=self._confidence(stage,event)
262
+ history.append({'stage':stage,'answer':copy.deepcopy(answer),'branches':copy.deepcopy(executor.rows)})
263
+ return {'answer':answer,'confidence':confidence,
264
+ 'cost':{k:sum(r['cost'][k] for r in executor.rows) for k in COST_KEYS}}
265
+ estimates,reserve=reservations(planner.calls,'fast')
266
+ stages=[('fast',reserve,lambda r:execute('fast',planner.calls,estimates,r))]
267
+ view_calls=[]
268
+ if self.enable_views and 'views' in self.stage_recipe[task] and task=='boolean' and paraphrase:
269
+ block,n=four_state_block(paraphrase);view_calls=[(block,n,None)]
270
+ elif self.enable_views and 'views' in self.stage_recipe[task] and task in ('single','ordered'):
271
+ options=kwargs['options'];n=len(options)
272
+ row_id=question_id or digest({'task':task,**kwargs})
273
+ form=self.design['single_choice' if task=='single' else 'ordered']
274
+ orders=order_set(row_id,n) if task=='single' else [tuple(range(n))]
275
+ for perm in orders:
276
+ if perm==tuple(range(n)) and form=='R': continue
277
+ block,width=listwise_block(kwargs['question'],[options[i] for i in perm],ordered=task=='ordered',reserved=True)
278
+ view_calls.append((block,width,perm))
279
+ if view_calls:
280
+ calls=[(b,n) for b,n,_ in view_calls];view_est,view_reserve=reservations(calls,'views')
281
+ stages.append(('views',view_reserve,lambda r:execute('views',calls,view_est,r)))
282
+ if self.enable_reasoning and 'reasoning' in self.stage_recipe[task] and modality=='text' and callable(getattr(self.backend,'reason',None)):
283
+ reason_est,reason_reserve=reservations(planner.calls,'reasoning')
284
+ stages.append(('reasoning',reason_reserve,lambda r:execute('reasoning',planner.calls,reason_est,r)))
285
+ result=route(stages,budget)
286
+ confidence=result.get('confidence') or (result['compute']['stages'][-1]['confidence'] if result['compute']['stages'] else None)
287
+ result.update(state_id=key,task=task,strict=strict,contract='solomon-answer-confidence-v2',
288
+ runtime_identity=copy.deepcopy(self.runtime_identity),design_sha256=self.design_sha256,
289
+ modality=modality,confidence=confidence,calibrated=bool(confidence and confidence.get('calibrated')),
290
+ document_prefill={'performed':cold,'tokens':prefix if cold else 0,'outside_question_budget':True},
291
+ reliability_target='whole_vector_exact_match' if task in ('entity','multilabel') else 'returned_decision_correct',
292
+ disagreement=measured,disagreement_available=measured is not None,
293
+ distributions=(candidate or {}).get('probabilities'),
294
+ evidence_sufficiency=self._sufficiency(task,candidate or {},kwargs),
295
+ distribution_change=self._distribution_change(original,candidate) if any(h['stage']=='reasoning' for h in history) else None,
296
+ persistence='immutable_inputs_restart_reprefill')
297
+ # Exploratory callers still get a candidate, never a falsely accepted answer.
298
+ if result['abstained']:
299
+ result['candidate']=candidate
300
+ result['support_status']='unqualified' if confidence is None else confidence['calibration_support']
301
+ else: result['support_status']='in_validated_scope'
302
+ return result
303
+
304
+
305
+ def handler(service):
306
+ base=state_handler(service)
307
+ class Handler(base):
308
+ def do_GET(self):
309
+ if self.path!='/health': return self.reply(404,{'error':'not found'})
310
+ self.reply(200,{'contract':'solomon-answer-confidence-v2','answer_types':list(TASKS),
311
+ 'strict_reliability_default':True,'confidence_modalities':['text'],
312
+ 'image_reliability':'unqualified','artifact_stages':sorted(service.artifacts),
313
+ 'runtime_identity':copy.deepcopy(service.runtime_identity)})
314
+ return Handler
src/solomon/service_checked.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Backend-neutral contract-v3 service; restart replays immutable inputs, not tensors.
2
+
3
+ Engine protocol: identity (mapping or method) -> JSON mapping with fingerprint; prefill(parts) -> state;
4
+ ask(state, block, n, execution='cached'|'full') -> letter_logits + branch_tokens.
5
+ Engine.ask must fork its prefix cache for every branch. One service serializes all
6
+ engine calls. A service instance exclusively owns its engine.
7
+ """
8
+ import copy
9
+ import hashlib
10
+ import json
11
+ import re
12
+ import shutil
13
+ import uuid
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+
18
+ from solomon.service_states import Service as ReadoutService, handler
19
+
20
+
21
+ def _json(value):
22
+ return json.dumps(value, sort_keys=True, separators=(',', ':'), allow_nan=False)
23
+
24
+
25
+ def _identity(engine):
26
+ value = engine.identity() if callable(engine.identity) else engine.identity
27
+ if not isinstance(value, dict) or not isinstance(value.get('fingerprint'), str) or not value['fingerprint']:
28
+ raise ValueError('engine identity requires a nonempty fingerprint')
29
+ return json.loads(_json(value))
30
+
31
+
32
+ def _parts(document):
33
+ if isinstance(document, str):
34
+ document = [{'text': document}]
35
+ if not isinstance(document, list) or not document:
36
+ raise ValueError('document must be text or a nonempty parts list')
37
+ result = []
38
+ for part in document:
39
+ if not isinstance(part, dict) or set(part) not in ({'text'}, {'image'}):
40
+ raise ValueError('each part must contain exactly text or image')
41
+ name, value = next(iter(part.items()))
42
+ if not isinstance(value, str) or not value.strip():
43
+ raise ValueError('document parts must contain nonempty strings')
44
+ result.append({name: value})
45
+ return result
46
+
47
+
48
+ def _digest(parts):
49
+ # JSON framing preserves boundaries; two text parts cannot alias one text part.
50
+ payload = [p if 'text' in p else {'image_sha256': hashlib.sha256(Path(p['image']).read_bytes()).hexdigest()} for p in parts]
51
+ return hashlib.sha256(_json(payload).encode()).hexdigest()
52
+
53
+
54
+ class _CheckedEngine:
55
+ def __init__(self, engine):
56
+ self.backend = engine
57
+
58
+ def identity(self):
59
+ value = self.backend.identity
60
+ return value() if callable(value) else value
61
+
62
+ def prefill(self, document):
63
+ return self.backend.prefill(copy.deepcopy(document))
64
+
65
+ def ask(self, state, block, n, execution='cached'):
66
+ result = self.backend.ask(state, block, n, execution=execution)
67
+ logits = np.asarray(result.get('letter_logits'), dtype=float)
68
+ tokens = result.get('branch_tokens')
69
+ if logits.shape != (n,) or not np.isfinite(logits).all():
70
+ raise ValueError('engine returned invalid letter logits')
71
+ if type(tokens) is not int or tokens < 0:
72
+ raise ValueError('engine returned invalid branch token count')
73
+ return result
74
+
75
+
76
+ class Service(ReadoutService):
77
+ """Shared existing readout logic with CUDA-safe persistence and identity checks."""
78
+ def __init__(self, store, engine, design=None):
79
+ design = copy.deepcopy(design or {'single_choice': 'R', 'ordered': 'R'})
80
+ allowed = {'R', 'S', 'P', 'R+avg2', 'R+avg3', 'R+avgall', 'R+debias'}
81
+ if any(design.get(k) not in allowed for k in ('single_choice', 'ordered')):
82
+ raise ValueError('unsupported readout design')
83
+ if design['ordered'] not in {'R', 'S'}:
84
+ raise ValueError('ordered design must preserve caller level order (R or S)')
85
+ if 'R+debias' in design.values():
86
+ prior = design.get('position_prior', {})
87
+ for n in range(2, 9):
88
+ values = np.asarray(prior.get(str(n+2)), dtype=float)
89
+ if values.shape != (n+2,) or not np.isfinite(values).all():
90
+ raise ValueError('debias design needs finite priors for 2 to 8 options')
91
+ super().__init__(store, _CheckedEngine(engine), design)
92
+ self.runtime_identity = _identity(self.engine)
93
+ self.design_sha256 = hashlib.sha256(_json(self.design).encode()).hexdigest()
94
+
95
+ def _check_runtime(self):
96
+ if _identity(self.engine) != self.runtime_identity:
97
+ self.state = self.state_id = None
98
+ raise ValueError('engine identity changed; create a new service instance')
99
+
100
+ def create(self, document):
101
+ parts = _parts(document)
102
+ with self.lock:
103
+ self._check_runtime()
104
+ key = uuid.uuid4().hex
105
+ pending = self.store / ('.pending-' + key)
106
+ final = self.store / key
107
+ pending.mkdir()
108
+ try:
109
+ saved = []
110
+ for i, part in enumerate(parts):
111
+ if 'text' in part:
112
+ saved.append(dict(part))
113
+ else:
114
+ source = Path(part['image'])
115
+ filename = f'image-{i}{source.suffix}'
116
+ (pending / filename).write_bytes(source.read_bytes())
117
+ saved.append({'image': str((final / filename).resolve())})
118
+ digest_parts = [p if 'text' in p else {'image': str(pending / Path(p['image']).name)} for p in saved]
119
+ record = {'schema': 'cuda-service-inputs-v1', 'state_id': key,
120
+ 'document': saved, 'document_sha256': _digest(digest_parts),
121
+ 'runtime_identity': self.runtime_identity,
122
+ 'persistence': 'immutable_inputs_restart_reprefill'}
123
+ (pending / 'record.json').write_text(_json(record))
124
+ pending.rename(final)
125
+ except BaseException:
126
+ shutil.rmtree(pending, ignore_errors=True)
127
+ raise
128
+ return {'state_id': key, 'contract': 'solomon-answer-contract-v3',
129
+ 'document_sha256': record['document_sha256'],
130
+ 'persistence': record['persistence']}
131
+
132
+ def _warm(self, key):
133
+ if not isinstance(key, str) or re.fullmatch('[0-9a-f]{32}', key) is None:
134
+ raise ValueError('invalid state identifier')
135
+ self._check_runtime()
136
+ root = self.store / key
137
+ record = json.loads((root / 'record.json').read_text())
138
+ if record.get('schema') != 'cuda-service-inputs-v1' or record.get('state_id') != key:
139
+ raise ValueError('invalid saved state record')
140
+ if record.get('runtime_identity') != self.runtime_identity:
141
+ raise ValueError('saved state uses a different runtime identity')
142
+ parts = _parts(record['document'])
143
+ for part in parts:
144
+ if 'image' in part and Path(part['image']).resolve().parent != root.resolve():
145
+ raise ValueError('saved image must stay inside its state directory')
146
+ if _digest(parts) != record.get('document_sha256'):
147
+ raise ValueError('saved document content changed')
148
+ if self.state_id != key:
149
+ # Clear both before prefill: a failed prefill cannot reuse a stale state.
150
+ self.state = self.state_id = None
151
+ self.state = self.engine.prefill(parts)
152
+ self.state_id = key
153
+ return self.state
154
+
155
+ def ask(self, key, task, **kwargs):
156
+ if task not in ('boolean', 'single', 'ordered', 'multilabel', 'entity'):
157
+ raise ValueError('unknown answer type')
158
+ with self.lock:
159
+ result = super().ask(key, task, **kwargs)
160
+ result.update(runtime_identity=copy.deepcopy(self.runtime_identity),
161
+ design_sha256=self.design_sha256,
162
+ persistence='immutable_inputs_restart_reprefill')
163
+ return result
src/solomon/service_evidence.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Optional source-grounded evidence around the existing confidence service."""
2
+ import copy
3
+ from pathlib import Path
4
+ from solomon.evidence import digest,validate_spans,image_pages,validate_pages
5
+ from solomon.retrieval import lexical_select,render_subset,remove
6
+
7
+ CONTRACT='solomon-evidence-v1'
8
+
9
+ def question_units(task,request):
10
+ if task=='entity':return [request['template'].replace('{entity}',e) for e in request['entities']]
11
+ if task=='multilabel':return [request['question']+' Attribute: '+label for label in request['labels']]
12
+ return [request['question']]
13
+
14
+ def prediction(answer):
15
+ if answer is None:return None
16
+ return answer.get('predictions',answer.get('prediction'))
17
+
18
+ class EvidenceService:
19
+ """Inject inference-only selection and a fresh-state decision callback.
20
+
21
+ decide(parts,task,request) returns {answer,cost}; each invocation must prefill
22
+ supplied parts afresh. Evidence results never promote answer qualification.
23
+ selector(text,questions) returns source spans, method and verification only.
24
+ """
25
+ def __init__(self,answers,decide,selector=None,page_selector=None):
26
+ self.answers=answers;self.decide=decide;self.selector=selector or lexical_select
27
+ self.page_selector=page_selector
28
+
29
+ def __getattr__(self,name):return getattr(self.answers,name)
30
+
31
+ def create(self,document):
32
+ result=self.answers.create(document);result['contract']=CONTRACT;return result
33
+
34
+ def ask(self,key,task,*,evidence='none',evidence_max_calls=2,**request):
35
+ if evidence not in ('none','support','sufficiency','removal'):raise ValueError('invalid evidence verification level')
36
+ if type(evidence_max_calls)is not int or not 0<=evidence_max_calls<=512:raise ValueError('invalid evidence call budget')
37
+ with self.answers.lock:
38
+ result=self.answers.ask(key,task,**request);result['contract']=CONTRACT
39
+ if evidence=='none':return result
40
+ state=self.answers._warm(key);parts=copy.deepcopy(state['parts'])
41
+ qs=question_units(task,request)
42
+ needed={'support':0,'sufficiency':1,'removal':2}[evidence]
43
+ if needed>evidence_max_calls:
44
+ result['evidence']={'status':'budget_exhausted','calls':0,'verification':'none'};return result
45
+ answer=result.get('answer') or result.get('candidate')
46
+ baseline=prediction(answer)
47
+ images=[p['image'] for p in parts if 'image' in p]
48
+ text=''.join(p['text'] for p in parts if 'text' in p)
49
+ selector=self.page_selector if images else self.selector
50
+ plan=None
51
+ if selector is not None and hasattr(selector,'plan'):
52
+ plan=(selector.plan(image_pages(images) if images else text,qs,task=task) if getattr(selector,'task_aware',False)
53
+ else selector.plan(image_pages(images) if images else text,qs))
54
+ if type(plan.get('calls'))is not int or plan['calls']<0:raise ValueError('invalid selection call estimate')
55
+ if needed+plan['calls']>evidence_max_calls:
56
+ result['evidence']={'status':'budget_exhausted','calls':0,'required_calls':needed+plan['calls'],'verification':'none'};return result
57
+ if images:
58
+ pages=image_pages(images)
59
+ if self.page_selector is None:
60
+ result['evidence']={'status':'unsupported_page_selector','verification':'none','calls':0,
61
+ 'pages_available':len(pages),'faithfulness_established':False};return result
62
+ selection=selector.execute(plan) if plan is not None else selector(copy.deepcopy(pages),qs)
63
+ chosen=validate_pages(pages,selection['evidence']);chosen_ids={p['page'] for p in chosen}
64
+ subset=[{'image':p['path']} for p in chosen]
65
+ remainder=[];page_number=0
66
+ for part in parts:
67
+ if 'image' in part:
68
+ page_number+=1
69
+ if page_number in chosen_ids:continue
70
+ remainder.append(part)
71
+ references=chosen
72
+ else:
73
+ selection=selector.execute(plan) if plan is not None else selector(text,qs)
74
+ references=validate_spans(text,selection['evidence'])
75
+ short,context_spans=render_subset(text,references)
76
+ subset=[{'text':short}];remainder=[{'text':remove(text,references)}]
77
+ body={'status':'no_support_found' if not references else 'found','references':references,
78
+ 'method':selection.get('method','external_selector'),'verification':selection.get('verification','retrieval_only'),
79
+ 'faithfulness_established':False,'calls':0,'input_tokens':0,'branches':0,
80
+ 'source_text_sha256':digest(text),'answer_qualification_unchanged':True}
81
+ selection_cost=selection.get('cost',{'calls':0,'input_tokens':0,'branches':0})
82
+ if any(type(selection_cost.get(k))is not int or selection_cost[k]<0 for k in ('calls','input_tokens','branches')):
83
+ raise ValueError('invalid selection static cost')
84
+ if selection_cost['calls']!=(plan['calls'] if plan is not None else 0):raise ValueError('selection exceeded declared inference plan')
85
+ body.update(selection_cost);body['selection_calls']=selection_cost['calls']
86
+ if 'units' in selection:body['units']=selection['units']
87
+ for field in ('selection_input_modality','ocr_used','renderer_sha256','relevance_weights_sha256'):
88
+ if field in selection:body[field]=selection[field]
89
+ if not images:body['governing_context_ranges']=[{k:s[k] for k in ('start','end')} for s in context_spans]
90
+ decision_request={k:request[k] for k in ('question','options','labels','template','entities') if k in request}
91
+ for mode,document in ([('evidence_only',subset)] if evidence=='sufficiency' else
92
+ [('evidence_only',subset),('evidence_removed',remainder)] if evidence=='removal' else []):
93
+ if images:validate_pages(pages,references)
94
+ output=self.decide(copy.deepcopy(document),task,copy.deepcopy(decision_request))
95
+ if images:validate_pages(pages,references)
96
+ if not isinstance(output,dict) or not {'answer','cost'}<=set(output):raise ValueError('invalid evidence decision callback')
97
+ cost=output['cost']
98
+ if any(type(cost.get(k))is not int or cost[k]<0 for k in ('input_tokens','branches')):raise ValueError('invalid evidence static cost')
99
+ body['calls']+=1;body['input_tokens']+=cost['input_tokens'];body['branches']+=cost['branches']
100
+ body[mode]={'prediction':prediction(output['answer']),'agrees_with_full':prediction(output['answer'])==baseline}
101
+ if body['calls']>body['selection_calls']:body['verification']='fresh_source_reencoding'
102
+ result['evidence']=body
103
+ return result
104
+
105
+ def handler(service):
106
+ from solomon.service_heads import handler as base_handler
107
+ base=base_handler(service)
108
+ class Handler(base):
109
+ def do_GET(self):
110
+ if self.path!='/health':return self.reply(404,{'error':'not found'})
111
+ return self.reply(200,{'contract':CONTRACT,'answer_types':['boolean','single','ordered','multilabel','entity'],
112
+ 'evidence_levels':['none','support','sufficiency','removal'],
113
+ 'strict_reliability_default':True,'runtime_identity':self.server.service.runtime_identity
114
+ if hasattr(self.server,'service') else service.runtime_identity})
115
+ return Handler
src/solomon/service_heads.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Trained-head fast/views service; unchanged decoder and separate stage confidence.
2
+
3
+ Hidden representations stay inside one locked request. Saved envelopes authorize
4
+ population-specific acceptance; learned correctness alone never does so.
5
+ """
6
+ import copy
7
+ import hashlib
8
+ from pathlib import Path
9
+ import numpy as np
10
+ from solomon.service_answers import Service as ConfidenceService, TASKS
11
+
12
+ CONTRACT = 'solomon-trained-heads-v1'
13
+
14
+
15
+ class _Capture:
16
+ def __init__(self, engine):
17
+ self.engine = engine
18
+ self.rows = []
19
+
20
+ def __getattr__(self, key):
21
+ return getattr(self.engine, key)
22
+
23
+ def ask(self, *args, **kwargs):
24
+ row = self.engine.ask(*args, **kwargs)
25
+ logits = np.asarray(row['letter_logits'], dtype=float)
26
+ p = np.exp(logits - logits.max()); p /= p.sum()
27
+ self.rows.append({'hidden': copy.deepcopy(row['hidden']),
28
+ 'probabilities': p.tolist(), 'head_key': row['head_key']})
29
+ return row
30
+
31
+
32
+ class HeadsService(ConfidenceService):
33
+ def __init__(self, store, engine, design=None, *, artifact=None, views_artifact=None, views_tasks=(), diagnostic_reasoning=False, reasoning_cap=512):
34
+ self.heads_backend = engine
35
+ if type(diagnostic_reasoning) is not bool: raise ValueError('diagnostic_reasoning must be Boolean')
36
+ self.diagnostic_reasoning = diagnostic_reasoning
37
+ self.views_tasks = tuple(views_tasks)
38
+ if len(set(self.views_tasks)) != len(self.views_tasks) or not set(self.views_tasks) <= {'boolean', 'single', 'ordered'}: raise ValueError('invalid selected view tasks')
39
+ if not callable(getattr(engine, 'task_context', None)) or not callable(getattr(engine, 'predict_correctness', None)):
40
+ raise ValueError('trained-head engine required')
41
+ self.capture = _Capture(engine)
42
+ artifacts = {k: v for k, v in [('fast', artifact), ('views', views_artifact)] if v is not None}
43
+ super().__init__(store, self.capture, design, artifacts=artifacts,
44
+ confidence_predictor=self._predict, enable_views=bool(self.views_tasks),
45
+ enable_reasoning=diagnostic_reasoning, reasoning_cap=reasoning_cap,
46
+ stage_recipe={t: ['fast'] + (['views'] if t in self.views_tasks else []) + (['reasoning'] if diagnostic_reasoning else []) for t in TASKS})
47
+
48
+ def expected_identity(self, stage):
49
+ if stage != 'fast' and not (stage == 'reasoning' and self.diagnostic_reasoning) and not (stage == 'views' and self.views_tasks):
50
+ raise ValueError('unavailable trained-head service stage')
51
+ return {**super().expected_identity(stage), 'contract': CONTRACT,
52
+ 'heads_service_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
53
+ 'heads_stages_sha256': hashlib.sha256(Path(__file__).with_name('heads_stages.py').read_bytes()).hexdigest()}
54
+
55
+ def _validate_artifact(self, stage, artifact):
56
+ super()._validate_artifact(stage, artifact)
57
+ if artifact.get('schema') != 'solomon-trained-heads-envelope-v1':
58
+ raise ValueError('new trained-head confidence envelope required')
59
+ selected = artifact.get('trained_head_identity', {})
60
+ runtime = self.runtime_identity
61
+ if (selected.get('weights_sha256') != runtime.get('trained_heads_sha256') or
62
+ selected.get('report_sha256') != runtime.get('trained_heads_report_sha256') or
63
+ selected.get('feature_identity', {}).get('runtime_fingerprint') != runtime.get('base_fingerprint') or
64
+ selected.get('feature_identity', {}).get('adapter_sha256') != runtime.get('adapter_sha256')):
65
+ raise ValueError('confidence envelope trained-head/adapter identity mismatch')
66
+
67
+ def _predict(self, artifact, event, identity):
68
+ from solomon.confidence import calibrate
69
+ cell = artifact.get('tasks', {}).get(event['task'])
70
+ if cell is None:
71
+ return {'calibration_support': 'unsupported_task', 'policy_status': 'unsupported'}
72
+ if event['stage'] == 'views':
73
+ from solomon.head_stages import confidence_features, FEATURE_RECIPE
74
+ from solomon.head_training import predict_correctness
75
+ if cell.get('feature_recipe') != FEATURE_RECIPE: raise ValueError('view correctness feature recipe mismatch')
76
+ primary_count = len(event['history'][0]['branches'])
77
+ prediction = event['answer']['prediction']
78
+ if prediction == 'not_stated': prediction = len(event['request']['options'])
79
+ elif prediction == 'conflicting': prediction = len(event['request']['options']) + 1
80
+ features, _ = confidence_features(self.capture.rows[:primary_count], event['answer']['view_probabilities'], prediction)
81
+ classifier = {k: np.asarray(v, float) if k in ('weights', 'mean', 'scale') else v for k, v in cell['correctness'].items()}
82
+ learned = {'reliability': predict_correctness(classifier, features)}
83
+ else:
84
+ learned = self.heads_backend.predict_correctness(event['task'], self.capture.rows)
85
+ support = cell.get('support', {}); interval = support.get('prefix_tokens', [])
86
+ supported = (event['modality'] == support.get('modality') == 'text' and
87
+ isinstance(support.get('population'), str) and bool(support['population']) and
88
+ support['population'] == event.get('population') and len(interval) == 2 and
89
+ all(type(v) is int for v in interval) and interval[0] <= event['prefix_tokens'] <= interval[1])
90
+ distributions = None
91
+ if cell.get('temperature'):
92
+ branches = event['history'][0]['branches'] if event['stage'] == 'views' else event['branches']
93
+ values = [np.asarray(r['letter_logits'], float) for r in branches]
94
+ if event['task'] in ('single', 'ordered') and len(values) == 2:
95
+ # Joint distribution is exposed separately; frozen S decoder still
96
+ # makes its sufficiency decision first.
97
+ p, q = values; q = q - np.logaddexp.reduce(q)
98
+ values = [np.r_[q[0] + p - np.logaddexp.reduce(p), q[1:]]]
99
+ temperature_identity = {**artifact['trained_head_identity'], 'task': event['task'], 'stage': 'fast'}
100
+ distributions = [calibrate(cell['temperature'], p, temperature_identity).tolist() for p in values]
101
+ return {'reliability': learned['reliability'], 'threshold': cell.get('threshold'),
102
+ 'policy_status': cell.get('status', 'unqualified'),
103
+ 'calibration_support': 'in_validated_scope' if supported else 'outside_declared_population',
104
+ 'calibrated': bool(supported and cell.get('distribution_confirmed', False)),
105
+ 'calibrated_distributions': distributions, 'support_population': support.get('population'),
106
+ 'confidence_source': 'trained-hidden-correctness-head'}
107
+
108
+ def _confidence(self, stage, event):
109
+ if stage == 'reasoning':
110
+ # Base-vocabulary reasoning has different representations and labels.
111
+ # Fast-head correctness must never be applied to this output.
112
+ return {'calibration_support': 'unqualified_reasoning', 'policy_status': 'unqualified',
113
+ 'reliability': None, 'threshold': None, 'calibrated': False,
114
+ 'confidence_source': 'none_pending_reasoning_stage_calibration',
115
+ 'disagreement': None, 'disagreement_available': False}
116
+ result = super()._confidence(stage, event)
117
+ # Raw correctness is useful diagnostically even outside calibrated scope.
118
+ if result.get('reliability') is None and stage == 'fast':
119
+ result['reliability'] = self.heads_backend.predict_correctness(event['task'], self.capture.rows)['reliability']
120
+ result['confidence_source'] = 'trained-hidden-correctness-head'
121
+ if result.get('policy_status') != 'confirmed':
122
+ result['calibrated'] = False
123
+ return result
124
+
125
+ def create(self, document):
126
+ result = super().create(document); result['contract'] = CONTRACT
127
+ return result
128
+
129
+ def ask(self, key, task, **kwargs):
130
+ if task not in TASKS:
131
+ raise ValueError('unknown answering task')
132
+ with self.lock, self.heads_backend.task_context(task):
133
+ self.capture.rows.clear()
134
+ try:
135
+ result = super().ask(key, task, **kwargs)
136
+ result['contract'] = CONTRACT
137
+ return result
138
+ finally:
139
+ self.capture.rows.clear()
140
+
141
+
142
+ def handler(service):
143
+ from solomon.service_answers import handler as base_handler
144
+ base = base_handler(service)
145
+ class Handler(base):
146
+ def do_GET(self):
147
+ if self.path != '/health':
148
+ return self.reply(404, {'error': 'not found'})
149
+ self.reply(200, {'contract': CONTRACT, 'answer_types': list(TASKS),
150
+ 'stage_recipe': service.stage_recipe,
151
+ 'strict_reliability_default': True,
152
+ 'confidence_source': 'trained-hidden-correctness-head',
153
+ 'artifact_stages': sorted(service.artifacts),
154
+ 'runtime_identity': copy.deepcopy(service.runtime_identity)})
155
+ return Handler
src/solomon/service_packages.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Evidence packages (v3) in the answer service: per-unit, source-grounded, page-referenced.
2
+
3
+ Text sources: each question unit (entity / label / boolean / choice) gets an evidence package
4
+ (solomon.evidence_packages.build): its selected spans plus automatically attached governing context,
5
+ all exact source ranges with code-point offsets, roles and reasons, and -- when a renderer page
6
+ map is registered for the source -- rendered page IDs. `sufficiency` re-asks each unit with ONLY
7
+ its package as a fresh document; `removal` re-asks the whole question with every selected
8
+ evidence span removed. Budgets are checked before any model call. Evidence never promotes answer
9
+ qualification and never establishes causal faithfulness.
10
+
11
+ Image sources are delegated unchanged to solomon.service_evidence.EvidenceService (page selector path).
12
+ """
13
+ import copy
14
+ from solomon import evidence_packages as v3
15
+ from solomon.evidence import digest, validate_spans
16
+ from solomon.retrieval import lexical_select, remove
17
+ from solomon.service_evidence import EvidenceService, question_units, prediction
18
+
19
+ CONTRACT = 'solomon-evidence-packages-v3'
20
+ SIZE_CAP = v3.SIZE_CAP
21
+
22
+
23
+ def unit_requests(task, request):
24
+ """(question text, subject, restricted decision request) per unit, in answer-vector order."""
25
+ base = {k: request[k] for k in ('question', 'options', 'labels', 'template', 'entities') if k in request}
26
+ qs = question_units(task, request)
27
+ if task == 'entity':
28
+ return [(q, e, {**base, 'entities': [e]}) for q, e in zip(qs, request['entities'])]
29
+ if task == 'multilabel':
30
+ return [(q, None, {**base, 'labels': [label]}) for q, label in zip(qs, request['labels'])]
31
+ return [(qs[0], None, base)]
32
+
33
+
34
+ class PackageEvidenceService(EvidenceService):
35
+ """page_maps: optional {source_sha256: rendered page map} from source-bound renderer manifests."""
36
+
37
+ def __init__(self, answers, decide, selector=None, page_selector=None, *, page_maps=None, size_cap=SIZE_CAP, package_format='per_unit'):
38
+ super().__init__(answers, decide, selector, page_selector)
39
+ if package_format not in ('per_unit', 'union'):
40
+ raise ValueError('package_format must be per_unit or union')
41
+ self.package_format = package_format
42
+ self.page_maps = dict(page_maps or {})
43
+ if not 0 < size_cap <= 1:
44
+ raise ValueError('invalid package size cap')
45
+ self.size_cap = size_cap
46
+
47
+ def create(self, document):
48
+ result = self.answers.create(document);result['contract'] = CONTRACT;return result
49
+
50
+ def _unit_evidence(self, text, units, selection):
51
+ """Per-unit selected spans. Selectors reporting `units` keep per-unit attribution;
52
+ otherwise every unit receives the selector's (validated) evidence."""
53
+ union = validate_spans(text, selection['evidence'])
54
+ if 'units' not in selection:
55
+ return [union for _ in units]
56
+ by = {u['unit']: u['evidence'] for u in selection['units']}
57
+ if set(by) - set(range(len(units))):
58
+ raise ValueError('selection reports unknown question units')
59
+ out = []
60
+ for i in range(len(units)):
61
+ spans = validate_spans(text, by.get(i, []))
62
+ if any(not any(u['start'] <= s['start'] and s['end'] <= u['end'] for u in union) for s in spans):
63
+ raise ValueError('unit evidence outside the reported selection')
64
+ out.append(spans)
65
+ return out
66
+
67
+ def ask(self, key, task, *, evidence='none', evidence_max_calls=2, **request):
68
+ if evidence not in ('none', 'support', 'sufficiency', 'removal'):
69
+ raise ValueError('invalid evidence verification level')
70
+ if type(evidence_max_calls) is not int or not 0 <= evidence_max_calls <= 512:
71
+ raise ValueError('invalid evidence call budget')
72
+ with self.answers.lock:
73
+ state = self.answers._warm(key)
74
+ if any('image' in p for p in state['parts']):
75
+ result = super().ask(key, task, evidence=evidence, evidence_max_calls=evidence_max_calls, **request)
76
+ result['contract'] = CONTRACT
77
+ if evidence != 'none' and isinstance(result.get('evidence'), dict):
78
+ result['evidence']['package_format'] = 'pages_only'
79
+ return result
80
+ result = self.answers.ask(key, task, **request);result['contract'] = CONTRACT
81
+ if evidence == 'none':
82
+ return result
83
+ parts = copy.deepcopy(state['parts']);text = ''.join(p['text'] for p in parts if 'text' in p)
84
+ units = unit_requests(task, request);qs = [u[0] for u in units]
85
+ only = len(units) if self.package_format == 'per_unit' else 1
86
+ needed = {'support': 0, 'sufficiency': only, 'removal': only + 1}[evidence]
87
+ selector = self.selector or lexical_select;plan = None;planned = 0
88
+ if hasattr(selector, 'plan'):
89
+ plan = (selector.plan(text, qs, task=task) if getattr(selector, 'task_aware', False) else selector.plan(text, qs))
90
+ if type(plan.get('calls')) is not int or plan['calls'] < 0:
91
+ raise ValueError('invalid selection call estimate')
92
+ planned = plan['calls']
93
+ if needed + planned > evidence_max_calls:
94
+ result['evidence'] = {'status': 'budget_exhausted', 'calls': 0, 'required_calls': needed + planned, 'verification': 'none'}
95
+ return result
96
+ selection = selector.execute(plan) if plan is not None else selector(text, qs)
97
+ cost = selection.get('cost', {'calls': 0, 'input_tokens': 0, 'branches': 0})
98
+ if any(type(cost.get(k)) is not int or cost[k] < 0 for k in ('calls', 'input_tokens', 'branches')):
99
+ raise ValueError('invalid selection static cost')
100
+ if cost['calls'] != planned:
101
+ raise ValueError('selection exceeded declared inference plan')
102
+ per_unit = self._unit_evidence(text, units, selection)
103
+ st = v3.Structure(text);page_map = self.page_maps.get(digest(text))
104
+ packages = []
105
+ for i, ((q, subject, _), spans) in enumerate(zip(units, per_unit)):
106
+ p = v3.build(text, q, spans, subject=subject, structure=st, cap=self.size_cap)
107
+ if page_map is not None:
108
+ p = v3.with_pages(p, text, page_map)
109
+ packages.append({'unit': i, 'question': q, 'subject': subject, 'no_support_found': p['no_support_found'],
110
+ 'spans': p['spans'], 'evidence_ranges': p['evidence_ranges'], 'context_reasons': p['context_reasons'],
111
+ 'rendered_characters': p['rendered_characters'], 'covered_characters': p['covered_characters'],
112
+ 'source_fraction': p['source_fraction'], 'within_size_cap': p['within_size_cap'], 'trimmed_for_cap': p['trimmed_for_cap'],
113
+ **({'pages': p['pages']} if page_map is not None else {}), '_text': p['text']})
114
+ union_refs = []
115
+ for s in sorted({(s['start'], s['end']) for spans in per_unit for s in spans}):
116
+ if union_refs and s[0] < union_refs[-1][1]:
117
+ union_refs[-1] = (union_refs[-1][0], max(s[1], union_refs[-1][1]))
118
+ else:
119
+ union_refs.append(s)
120
+ refs = [{'start': a, 'end': b, 'text': text[a:b], 'source_sha256': digest(text)} for a, b in union_refs]
121
+ body = {'status': 'no_support_found' if not refs else 'found', 'references': refs,
122
+ 'packages': [{k: v for k, v in p.items() if k != '_text'} for p in packages],
123
+ 'package_format': self.package_format, 'package_schema': v3.SCHEMA, 'size_cap_source_fraction': self.size_cap,
124
+ 'method': selection.get('method', 'external_selector'), 'verification': selection.get('verification', 'retrieval_only'),
125
+ 'faithfulness_established': False, 'calls': 0, 'input_tokens': 0, 'branches': 0,
126
+ 'selection_calls': cost['calls'], 'source_text_sha256': digest(text), 'answer_qualification_unchanged': True,
127
+ **({'page_map_registered': True} if page_map is not None else {'page_map_registered': False})}
128
+ body['calls'] += cost['calls'];body['input_tokens'] += cost['input_tokens'];body['branches'] += cost['branches']
129
+ for field in ('relevance_weights_sha256', 'dependency_rule'):
130
+ if field in selection:
131
+ body[field] = selection[field]
132
+ baseline = prediction(result.get('answer') or result.get('candidate'))
133
+
134
+ def call(document, req):
135
+ output = self.decide(copy.deepcopy(document), task, copy.deepcopy(req))
136
+ if not isinstance(output, dict) or not {'answer', 'cost'} <= set(output):
137
+ raise ValueError('invalid evidence decision callback')
138
+ c = output['cost']
139
+ if any(type(c.get(k)) is not int or c[k] < 0 for k in ('input_tokens', 'branches')):
140
+ raise ValueError('invalid evidence static cost')
141
+ body['calls'] += 1;body['input_tokens'] += c['input_tokens'];body['branches'] += c['branches']
142
+ return prediction(output['answer'])
143
+ if evidence in ('sufficiency', 'removal') and self.package_format == 'union':
144
+ un = v3.union(text, [{'spans': p['spans']} for p in packages])
145
+ decision = {k: request[k] for k in ('question', 'options', 'labels', 'template', 'entities') if k in request}
146
+ assembled = call([{'text': un['text']}], decision)
147
+ body['union_package'] = {'spans': [{k: v for k, v in s.items() if k != 'pages'} for s in un['spans']],
148
+ 'source_fraction': un['source_fraction'], 'rendered_characters': un['rendered_characters']}
149
+ body['evidence_only'] = {'prediction': assembled, 'agrees_with_full': assembled == baseline,
150
+ 'input': 'union of the question\'s unit packages, one fresh prefill'}
151
+ elif evidence in ('sufficiency', 'removal'):
152
+ predictions = [call([{'text': p['_text']}], req) for p, (_, _, req) in zip(packages, units)]
153
+ if task in ('entity', 'multilabel'):
154
+ assembled = [x for pr in predictions for x in (pr if isinstance(pr, list) else [pr])]
155
+ else:
156
+ assembled = predictions[0]
157
+ body['evidence_only'] = {'prediction': assembled, 'agrees_with_full': assembled == baseline,
158
+ 'per_unit': [{'unit': i, 'prediction': pr} for i, pr in enumerate(predictions)],
159
+ 'input': 'per-unit evidence package (selected spans + governing context), fresh prefill per unit'}
160
+ if evidence == 'removal':
161
+ decision = {k: request[k] for k in ('question', 'options', 'labels', 'template', 'entities') if k in request}
162
+ removed = call([{'text': remove(text, refs) if refs else text}], decision)
163
+ body['evidence_removed'] = {'prediction': removed, 'agrees_with_full': removed == baseline,
164
+ 'input': 'source with every selected evidence span removed (context kept)'}
165
+ if body['calls'] > body['selection_calls']:
166
+ body['verification'] = 'fresh_source_reencoding'
167
+ result['evidence'] = body
168
+ return result
169
+
170
+
171
+ def handler(service):
172
+ from solomon.service_evidence import handler as base_handler
173
+ base = base_handler(service)
174
+
175
+ class Handler(base):
176
+ def do_GET(self):
177
+ if self.path != '/health':
178
+ return self.reply(404, {'error': 'not found'})
179
+ return self.reply(200, {'contract': CONTRACT, 'answer_types': ['boolean', 'single', 'ordered', 'multilabel', 'entity'],
180
+ 'evidence_levels': ['none', 'support', 'sufficiency', 'removal'], 'evidence_package': v3.SCHEMA,
181
+ 'package_format': self.package_format, 'strict_reliability_default': True,
182
+ 'runtime_identity': self.server.service.runtime_identity if hasattr(self.server, 'service') else service.runtime_identity})
183
+ return Handler
184
+
185
+
186
+ def service(store, engine, design, *, artifact=None, views_artifact=None, views_tasks=(), selector=None, page_selector=None,
187
+ page_maps=None, size_cap=SIZE_CAP, package_format='per_unit'):
188
+ """Serving constructor mirroring solomon.serving.service, with v3 evidence packages."""
189
+ from pathlib import Path
190
+ from solomon.serving import ConfidenceHeadsService, FreshDecider
191
+ answers = ConfidenceHeadsService(store, engine, design, artifact=artifact, views_artifact=views_artifact, views_tasks=views_tasks)
192
+ return PackageEvidenceService(answers, FreshDecider(engine, design, Path(store)/'.evidence-readout'), selector, page_selector,
193
+ page_maps=page_maps, size_cap=size_cap, package_format=package_format)
src/solomon/service_states.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Local contract-v3 prototype: task-neutral text/image states and five answer types.
2
+
3
+ State records persist immutable input copies, not GPU tensors. Restart lazily re-prefills
4
+ those inputs. Full tensor persistence belongs to a later phase. No calibration claim is made.
5
+ """
6
+ import argparse
7
+ import json
8
+ import threading
9
+ import uuid
10
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
11
+ from pathlib import Path
12
+
13
+ import numpy as np
14
+
15
+ from solomon.engine_contract import (ART, ContractEngine, Ledger, as_parts, document_key, dump, identity,
16
+ four_state_block, label_block, listwise_block, option_block, sufficiency_block)
17
+ from solomon import readout
18
+
19
+
20
+ class Service:
21
+ def __init__(self, store, engine, design=None):
22
+ self.store = Path(store)
23
+ self.store.mkdir(parents=True, exist_ok=True)
24
+ self.engine = engine
25
+ self.design = design or {'single_choice': 'R', 'ordered': 'R'}
26
+ self.lock = threading.RLock()
27
+ self.state = None
28
+ self.state_id = None
29
+
30
+ def create(self, document):
31
+ with self.lock:
32
+ key = uuid.uuid4().hex
33
+ dest = self.store / key
34
+ dest.mkdir()
35
+ parts = []
36
+ for i, part in enumerate(as_parts(document)):
37
+ if 'text' in part:
38
+ if not isinstance(part['text'], str):
39
+ raise ValueError('text parts must contain strings')
40
+ parts.append(part)
41
+ else:
42
+ source = Path(part['image'])
43
+ target = dest / f'image-{i}{source.suffix}'
44
+ target.write_bytes(source.read_bytes())
45
+ parts.append({'image': str(target.resolve())})
46
+ record = {'state_id': key, 'document': parts, 'document_sha256': document_key(parts),
47
+ 'fingerprint': identity(self.engine)['fingerprint']}
48
+ dump(dest / 'record.json', record)
49
+ return {'state_id': key, 'contract': 'solomon-answer-contract-v3', 'document_sha256': record['document_sha256']}
50
+
51
+ def _warm(self, key):
52
+ if len(key) != 32 or any(c not in '0123456789abcdef' for c in key):
53
+ raise ValueError('invalid state identifier')
54
+ record = json.loads((self.store / key / 'record.json').read_text())
55
+ if record['fingerprint'] != identity(self.engine)['fingerprint']:
56
+ raise ValueError('saved state uses a different document encoder')
57
+ if record['document_sha256'] != document_key(record['document']):
58
+ raise ValueError('saved document content changed')
59
+ if self.state_id != key:
60
+ self.state = None
61
+ self.engine.mx.clear_cache()
62
+ self.state = self.engine.prefill(record['document'])
63
+ self.state_id = key
64
+ return self.state
65
+
66
+ def ask(self, key, task, question=None, options=None, labels=None, template=None, entities=None, execution='cached'):
67
+ if task not in ('boolean', 'single', 'ordered', 'multilabel', 'entity'):
68
+ raise ValueError('unknown answer type')
69
+ if execution not in ('cached', 'full'):
70
+ raise ValueError('execution must be cached or full')
71
+ if task == 'entity':
72
+ if not isinstance(template, str) or template.count('{entity}') != 1:
73
+ raise ValueError('template must contain exactly one {entity} placeholder')
74
+ values = entities
75
+ elif task == 'multilabel':
76
+ values = labels
77
+ elif task in ('single', 'ordered'):
78
+ values = options
79
+ else:
80
+ values = None
81
+ if task != 'entity' and (not isinstance(question, str) or not question.strip()):
82
+ raise ValueError('question must be a nonempty string')
83
+ if values is not None and (not isinstance(values, list) or not values or
84
+ any(not isinstance(v, str) or not v.strip() for v in values) or len(set(values)) != len(values)):
85
+ raise ValueError('options, labels and entities must be distinct nonempty strings')
86
+ if task in ('single', 'ordered') and (values is None or not 2 <= len(values) <= 8):
87
+ raise ValueError('provide 2 to 8 options')
88
+ if task in ('entity', 'multilabel') and (values is None or len(values) > 64):
89
+ raise ValueError('provide 1 to 64 entities or labels')
90
+ with self.lock:
91
+ state = self._warm(key)
92
+ records = []
93
+ def score(block):
94
+ result = self.engine.ask(state, block[0], block[1], execution=execution)
95
+ records.append(result)
96
+ return readout.softmax(result['letter_logits'])
97
+ if task == 'boolean':
98
+ p = score(four_state_block(question))
99
+ answer = {'prediction': int(p.argmax()), 'probabilities': p.tolist()}
100
+ elif task in ('multilabel', 'entity'):
101
+ probs = [score(four_state_block(template.replace('{entity}', value)) if task == 'entity'
102
+ else label_block(question, value)) for value in values]
103
+ answer = {'predictions': [int(p.argmax()) for p in probs], 'probabilities': [p.tolist() for p in probs],
104
+ 'entities' if task == 'entity' else 'labels': values}
105
+ else:
106
+ chosen = self.design['single_choice' if task == 'single' else 'ordered']
107
+ if chosen == 'P':
108
+ scores = {f'live|P|{i}': {'letter_logits': np.log(np.maximum(score(option_block(question, o)), 1e-300))}
109
+ for i, o in enumerate(options)}
110
+ prediction = readout.predict_per_option(scores, {'id': 'live', 'input': {'options': options}})
111
+ answer = {'prediction': prediction, 'option_probabilities': [readout.softmax(scores[f'live|P|{i}']['letter_logits']).tolist() for i in range(len(options))]}
112
+ else:
113
+ form = 'S' if chosen == 'S' else 'R'
114
+ average = {'R+avg2': 2, 'R+avg3': 3, 'R+avgall': 'all'}.get(chosen)
115
+ n = len(options)
116
+ k = n if average == 'all' else min(n, average or 1)
117
+ rotations = readout.rotations_of(tuple(range(n)))
118
+ picks = list(dict.fromkeys(rotations[round(j*n/k) % n] for j in range(k)))
119
+ logs = []
120
+ for perm in picks:
121
+ p = score(listwise_block(question, [options[i] for i in perm], ordered=task == 'ordered', reserved=form == 'R'))
122
+ lp = np.log(np.maximum(p, 1e-300))
123
+ if chosen == 'R+debias':
124
+ lp -= np.asarray(self.design['position_prior'][str(n+2)])
125
+ mapped = lp.copy()
126
+ for pos, i in enumerate(perm):
127
+ mapped[i] = lp[pos]
128
+ logs.append(mapped)
129
+ p = readout.softmax(np.mean(logs, axis=0))
130
+ prediction = readout.decode(np.log(np.maximum(p, 1e-300)), n)
131
+ if form == 'S':
132
+ suff = int(score(sufficiency_block(question, options)).argmax())
133
+ prediction = int(p.argmax()) if suff == 0 else ('not_stated' if suff == 1 else 'conflicting')
134
+ answer = {'prediction': prediction, 'probabilities': p.tolist()}
135
+ if task == 'ordered':
136
+ answer['cumulative_threshold_probabilities'] = [float(p[i:n].sum() / p[:n].sum()) for i in range(1, n)]
137
+ answer['selected_option'] = options[answer['prediction']] if isinstance(answer['prediction'], int) else None
138
+ return {'state_id': key, 'task': task, 'calibrated': False, 'execution': execution,
139
+ 'branch_tokens': sum(r['branch_tokens'] for r in records), 'branches': len(records), **answer}
140
+
141
+
142
+ def handler(service):
143
+ class Handler(BaseHTTPRequestHandler):
144
+ def do_GET(self):
145
+ if self.path != '/health':
146
+ return self.reply(404, {'error': 'not found'})
147
+ self.reply(200, {'contract': 'solomon-answer-contract-v3', 'experimental': True,
148
+ 'answer_types': ['boolean', 'single', 'ordered', 'multilabel', 'entity']})
149
+ def reply(self, status, data):
150
+ raw = json.dumps(data).encode()
151
+ self.send_response(status)
152
+ self.send_header('Content-Type', 'application/json')
153
+ self.send_header('Content-Length', str(len(raw)))
154
+ self.end_headers()
155
+ self.wfile.write(raw)
156
+ def do_POST(self):
157
+ try:
158
+ if self.headers.get('Origin'):
159
+ return self.reply(403, {'error': 'cross-origin requests unsupported'})
160
+ length = int(self.headers.get('Content-Length', '0'))
161
+ if not 0 < length <= 8_000_000:
162
+ raise ValueError('request body must be 1 to 8000000 bytes')
163
+ body = json.loads(self.rfile.read(length))
164
+ path = self.path.strip('/').split('/')
165
+ if path == ['states']:
166
+ return self.reply(201, service.create(body['document']))
167
+ if len(path) == 3 and path[0] == 'states' and path[2] == 'ask':
168
+ return self.reply(200, service.ask(path[1], **body))
169
+ self.reply(404, {'error': 'not found'})
170
+ except (ValueError, KeyError, TypeError) as e:
171
+ self.reply(400, {'error': str(e)})
172
+ except FileNotFoundError:
173
+ self.reply(404, {'error': 'state or input file not found'})
174
+ return Handler
175
+
176
+
177
+ def main():
178
+ parser = argparse.ArgumentParser()
179
+ parser.add_argument('--port', type=int, default=8767)
180
+ parser.add_argument('--adapter', type=Path)
181
+ parser.add_argument('--placement', default='question', choices=['question', 'full'])
182
+ parser.add_argument('--design', type=Path, default=ART / 'design-freeze.json')
183
+ parser.add_argument('--store', type=Path, default=ART / 'service/documents')
184
+ args = parser.parse_args()
185
+ design = json.loads(args.design.read_text()) if args.design.exists() else None
186
+ engine = ContractEngine('float32', Ledger(args.store.parent / 'ledger.json'), args.adapter, args.placement)
187
+ service = Service(args.store, engine, design)
188
+ server = ThreadingHTTPServer(('127.0.0.1', args.port), handler(service))
189
+ print(f'Contract v3 ready on 127.0.0.1:{args.port}', flush=True)
190
+ try:
191
+ server.serve_forever()
192
+ finally:
193
+ server.server_close()
194
+
195
+
196
+ if __name__ == '__main__':
197
+ main()
src/solomon/serving.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Preserve five-task trained-head confidence/routing with optional evidence."""
2
+ import hashlib,json
3
+ from pathlib import Path
4
+ import numpy as np
5
+ from solomon.engine import SolomonEngine,sha
6
+ from solomon.engine_reasoning import ReasoningEngine
7
+ from solomon.service_heads import HeadsService
8
+ from solomon.service_answers import Service as ConfidenceService
9
+ from solomon.service_evidence import EvidenceService,CONTRACT
10
+
11
+ class ServiceEngine(SolomonEngine,ReasoningEngine):
12
+ def __init__(self,*args,correctness_report_sha256=None,**kwargs):
13
+ super().__init__(*args,**kwargs)
14
+ self.identity.update(trained_heads_report_sha256=correctness_report_sha256,serving_sha256=sha(__file__))
15
+ self.identity.pop('fingerprint',None)
16
+ self.identity['fingerprint']=hashlib.sha256(json.dumps(self.identity,sort_keys=True).encode()).hexdigest()
17
+
18
+ def estimate(self,state,block,n,stage='fast',max_new_tokens=512):
19
+ if not any('image' in p for p in state['parts']):
20
+ return ReasoningEngine.estimate(self,state,block,n,stage=stage,max_new_tokens=max_new_tokens)
21
+ if stage!='fast':raise ValueError('image reasoning is unqualified')
22
+ with self._lock,self.torch.inference_mode():
23
+ ids,_,_,_=self._encode(state['parts'],self._render(state['parts'],block),state['features'])
24
+ p=state['prefix_tokens']
25
+ if not self.torch.equal(ids[:,:p],state['prefix_ids']):raise ValueError('image estimate prefix mismatch')
26
+ return {'input_tokens':int(ids.shape[1])-p,'generated_tokens':0,'branches':1,
27
+ 'full_prompt_tokens':int(ids.shape[1]),'reused_prefix_tokens':p}
28
+
29
+ class ConfidenceHeadsService(HeadsService):
30
+ def expected_identity(self,stage):
31
+ return {**super().expected_identity(stage),'contract':CONTRACT,'serving_sha256':sha(__file__)}
32
+
33
+ def _validate_artifact(self,stage,artifact):
34
+ ConfidenceService._validate_artifact(self,stage,artifact)
35
+ if artifact.get('schema')!='solomon-heads-envelope-v1':raise ValueError('the evidence layer confidence envelope required')
36
+ selected=artifact.get('trained_head_identity',{});runtime=self.runtime_identity
37
+ if (selected.get('weights_sha256')!=runtime.get('trained_heads_sha256') or
38
+ selected.get('report_sha256')!=runtime.get('trained_heads_report_sha256') or
39
+ selected.get('feature_identity',{}).get('runtime_fingerprint')!=runtime.get('base_fingerprint') or
40
+ selected.get('feature_identity',{}).get('adapter_sha256')!=runtime.get('adapter_sha256')):
41
+ raise ValueError('the evidence layer correctness/head/backbone identity mismatch')
42
+
43
+ class FreshDecider:
44
+ def __init__(self,engine,design,store):self.engine=engine;self.design=design;self.store=store
45
+ def __call__(self,parts,task,request):
46
+ from solomon.service_states import Service as Readout
47
+ engine=self.engine
48
+ class Capture:
49
+ def __init__(self):self.records=[]
50
+ def ask(self,*args,**kwargs):
51
+ result=engine.ask(*args,**kwargs);self.records.append(result);return result
52
+ capture=Capture();state=engine.prefill(parts or [{'text':''}])
53
+ class Fixed(Readout):
54
+ def _warm(self,key):return state
55
+ readout=Fixed(self.store,capture,self.design)
56
+ with engine.task_context(task):answer=readout.ask('fresh-evidence',task,**request)
57
+ return {'answer':answer,'cost':{'input_tokens':state['prefix_tokens']+sum(r['branch_tokens'] for r in capture.records),
58
+ 'branches':len(capture.records),'prefill_tokens':state['prefix_tokens']}}
59
+
60
+ def service(store,engine,design,*,artifact=None,views_artifact=None,views_tasks=(),selector=None,page_selector=None):
61
+ answers=ConfidenceHeadsService(store,engine,design,artifact=artifact,views_artifact=views_artifact,views_tasks=views_tasks)
62
+ return EvidenceService(answers,FreshDecider(engine,design,Path(store)/'.evidence-readout'),selector,page_selector)