nhnk commited on
Commit
08bd580
·
verified ·
1 Parent(s): 2f5d5ce

Release frozen FactCascade utility router checkpoint and loading code

Browse files

Original trained parameters exported to portable JSON; exact serialization/synthetic prediction parity; no dataset examples or verifier weights.

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 [yyyy] [name of copyright owner]
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.
MODEL_MANIFEST.json ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "FACTCASCADE_PUBLIC_ROUTER_MANIFEST_V1",
3
+ "model": "FactCascade",
4
+ "license": "Apache-2.0",
5
+ "checkpoint": "router.json",
6
+ "feature_count": 31,
7
+ "tree_count": 100,
8
+ "trained_parameters_included": true,
9
+ "pickle_or_verifier_weights_included": false,
10
+ "dataset_examples_or_gold_included": false,
11
+ "members_exclude_manifest_itself": true,
12
+ "file_count_including_manifest": 22,
13
+ "files": [
14
+ {
15
+ "path": "LICENSE",
16
+ "bytes": 11358,
17
+ "C_E_direct_byte_equal": true
18
+ },
19
+ {
20
+ "path": "NOTICE",
21
+ "bytes": 218,
22
+ "C_E_direct_byte_equal": true
23
+ },
24
+ {
25
+ "path": "README.md",
26
+ "bytes": 4248,
27
+ "C_E_direct_byte_equal": true
28
+ },
29
+ {
30
+ "path": "VALIDATION.json",
31
+ "bytes": 738,
32
+ "C_E_direct_byte_equal": true
33
+ },
34
+ {
35
+ "path": "config.json",
36
+ "bytes": 2929,
37
+ "C_E_direct_byte_equal": true
38
+ },
39
+ {
40
+ "path": "example.py",
41
+ "bytes": 385,
42
+ "C_E_direct_byte_equal": true
43
+ },
44
+ {
45
+ "path": "factcascade/__init__.py",
46
+ "bytes": 192,
47
+ "C_E_direct_byte_equal": true
48
+ },
49
+ {
50
+ "path": "factcascade/_frozen_numpy.py",
51
+ "bytes": 7178,
52
+ "C_E_direct_byte_equal": true
53
+ },
54
+ {
55
+ "path": "factcascade/adapters/__init__.py",
56
+ "bytes": 343,
57
+ "C_E_direct_byte_equal": true
58
+ },
59
+ {
60
+ "path": "factcascade/adapters/aggrefact.py",
61
+ "bytes": 202,
62
+ "C_E_direct_byte_equal": true
63
+ },
64
+ {
65
+ "path": "factcascade/adapters/begin.py",
66
+ "bytes": 182,
67
+ "C_E_direct_byte_equal": true
68
+ },
69
+ {
70
+ "path": "factcascade/adapters/check_covid.py",
71
+ "bytes": 195,
72
+ "C_E_direct_byte_equal": true
73
+ },
74
+ {
75
+ "path": "factcascade/adapters/hover.py",
76
+ "bytes": 387,
77
+ "C_E_direct_byte_equal": true
78
+ },
79
+ {
80
+ "path": "factcascade/features.py",
81
+ "bytes": 11300,
82
+ "C_E_direct_byte_equal": true
83
+ },
84
+ {
85
+ "path": "factcascade/metrics.py",
86
+ "bytes": 1790,
87
+ "C_E_direct_byte_equal": true
88
+ },
89
+ {
90
+ "path": "factcascade/quota.py",
91
+ "bytes": 438,
92
+ "C_E_direct_byte_equal": true
93
+ },
94
+ {
95
+ "path": "factcascade/rank_fusion.py",
96
+ "bytes": 1011,
97
+ "C_E_direct_byte_equal": true
98
+ },
99
+ {
100
+ "path": "factcascade/routing.py",
101
+ "bytes": 2845,
102
+ "C_E_direct_byte_equal": true
103
+ },
104
+ {
105
+ "path": "factcascade/utility_model.py",
106
+ "bytes": 3886,
107
+ "C_E_direct_byte_equal": true
108
+ },
109
+ {
110
+ "path": "requirements.txt",
111
+ "bytes": 14,
112
+ "C_E_direct_byte_equal": true
113
+ },
114
+ {
115
+ "path": "router.json",
116
+ "bytes": 140644,
117
+ "C_E_direct_byte_equal": true
118
+ }
119
+ ],
120
+ "validation": "VALIDATION.json"
121
+ }
NOTICE ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ FactCascade frozen utility router and accompanying own code are released under Apache-2.0.
2
+ Verifier weights are not included. Upstream verifier models and any datasets remain subject to their own licenses and notices.
README.md ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ tags:
6
+ - factuality-verification
7
+ - routing
8
+ - cascading
9
+ - gradient-boosting
10
+ - numpy
11
+ - factcascade
12
+ ---
13
+
14
+ # FactCascade: Utility-Guided Routing for Selective Factuality Verification
15
+
16
+ This repository provides the **trained frozen utility-router checkpoint** and the code/configuration needed to load it. It is a small NumPy histogram gradient booster (31 features, 100 trees, maximum depth 2), not a verifier language model. All learned tree splits/leaf values, histogram thresholds and train-only imputation/scaling parameters are in `router.json`.
17
+
18
+ The router estimates the expected signed change in correctness when a Bespoke decision replaces a cheap-verifier fallback. The frozen FactCascade allocation combines equal-weight empirical midranks of this estimate and the raw FT5/DeBERTa score gap, then selects a half-up quota of `920/3337` per component, with stable row-key ties. `config.json` gives the exact feature order, thresholds, quota and pinned verifier revisions.
19
+
20
+ ## Load the existing trained checkpoint
21
+
22
+ Download the repository files, install `numpy==1.26.4`, and run:
23
+
24
+ ```python
25
+ import numpy as np
26
+ from factcascade.utility_model import UtilityModel
27
+
28
+ model = UtilityModel.load("router.json")
29
+ # X must contain the exact ordered 31 frozen features; zeros only illustrate shape.
30
+ X = np.zeros((1, 31), dtype=np.float64)
31
+ utility = model.predict(X)
32
+ ```
33
+
34
+ `example.py` runs this loading example. No fitting is needed. The JSON loader validates the schema, finite preprocessing parameters, feature order and tree structure. There is no executable pickle checkpoint in this public repository. This custom NumPy router does not use Transformers `AutoModel`.
35
+
36
+ For full selective verification, callers must produce the canonical features from the frozen verifier scores and evidence geometry, combine utility/disagreement ranks within the intended component, and apply the saved replacement policy. A feature vector from a different adapter, chunking rule or score convention is not interchangeable. Included API/adapters explain the expected record fields; this lightweight release does not execute the three verifier models.
37
+
38
+ ## Training and evaluation scope
39
+
40
+ The saved router was trained on 3,337 DEV rows in 1,397 natural groups. Its target is per-row signed correctness change under unweighted squared loss; this surrogate does not directly optimize component-macro balanced accuracy. The final fusion policy was selected after observing DEV and external results. Results on exposed cohorts must be treated as retrospective; this release makes no claim that fusion is optimal or generally superior to disagreement or predicted-correctness routing.
41
+
42
+ This checkpoint is the original frozen full-DEV utility model. It is distinct from later diagnostic OOF/source-heldout fits and from the separate saved FCE predicted-correctness heads. Those baseline heads and verifier weights are not included.
43
+
44
+ ## Serialization validation
45
+
46
+ `VALIDATION.json` records exact parameter-structure and CPU prediction parity with the original frozen checkpoint. Validation includes 1,024 synthetic rows, NaN/infinity imputation and every learned split boundary, plus equal fusion scores and selected synthetic routes. No training, real labels, new quality benchmark or GPU inference was performed. This verifies faithful export; it is not an additional generalization experiment.
47
+
48
+ ## Verifier dependencies and license
49
+
50
+ FactCascade requires scores from [MiniCheck-Flan-T5-Large](https://huggingface.co/lytang/MiniCheck-Flan-T5-Large), [MiniCheck-DeBERTa-v3-Large](https://huggingface.co/lytang/MiniCheck-DeBERTa-v3-Large) and [Bespoke-MiniCheck-7B](https://huggingface.co/bespokelabs/Bespoke-MiniCheck-7B); exact revisions are in `config.json`. Obtain those models separately and follow their licenses. In particular, the pinned Bespoke model card specifies CC BY-NC 4.0. The Apache-2.0 license here covers the FactCascade router checkpoint and own code, and does not relicense upstream verifier models or datasets.
51
+
52
+ Only model parameters, own code, frozen configuration and aggregate validation metadata are released. No claim/evidence text, labels, dataset rows, saved example scores, private paths or credentials are included.
VALIDATION.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "FACTCASCADE_PUBLIC_ROUTER_VALIDATION_V1",
3
+ "original_checkpoint_bytes": 48351,
4
+ "original_checkpoint_source_durable_equal": true,
5
+ "parameter_structure_exact": true,
6
+ "feature_order_exact": true,
7
+ "features": 31,
8
+ "trees": 100,
9
+ "synthetic_prediction_rows": 3997,
10
+ "learned_split_boundaries_exercised": 2973,
11
+ "prediction_exact": true,
12
+ "rank_fusion_exact": true,
13
+ "synthetic_routes_exact": true,
14
+ "NaN_positive_negative_infinity_imputation_checked": true,
15
+ "new_fits": 0,
16
+ "verifier_inference": 0,
17
+ "real_dataset_gold_reads": 0,
18
+ "new_benchmark_or_runtime": 0,
19
+ "cryptographic_hashes": 0,
20
+ "scope": "Checkpoint serialization and synthetic CPU prediction parity only; not a fresh generalization study."
21
+ }
config.json ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "FACTCASCADE_HF_ROUTER_CONFIG_V1",
3
+ "name": "FactCascade",
4
+ "checkpoint": "router.json",
5
+ "feature_count": 31,
6
+ "feature_order": [
7
+ "ft5_score",
8
+ "ft5_abs_distance_to_calibrated_threshold",
9
+ "b192_score",
10
+ "ft5_b192_delta",
11
+ "ft5_b192_disagreement",
12
+ "table_or_mixed_indicator",
13
+ "ft5_margin_x_table",
14
+ "ft5_full_score",
15
+ "selected_full_score_delta",
16
+ "selected_full_disagreement",
17
+ "log_ft5_selected_chunks",
18
+ "log_ft5_full_chunks",
19
+ "log_claim_word_count",
20
+ "log_selected_evidence_words",
21
+ "log_full_evidence_words",
22
+ "log_selected_source_count",
23
+ "selected_source_coverage_ratio",
24
+ "ft5_selected_margin_to_050",
25
+ "ft5_selected_margin_to_0763",
26
+ "ft5_full_minus_selected",
27
+ "b192_minus_ft5_selected",
28
+ "b192_ft5_decision_disagreement",
29
+ "full_only_support_signal",
30
+ "b192_disagreement_x_table_or_mixed",
31
+ "selected_full_discrepancy_x_evidence_length_ratio",
32
+ "claim_negation_proxy_count",
33
+ "claim_comparator_quantifier_count",
34
+ "claim_numeral_unit_count",
35
+ "claim_titlecase_entity_proxy_count",
36
+ "claim_selected_number_overlap_ratio",
37
+ "claim_entity_selected_minus_full_overlap"
38
+ ],
39
+ "learner": {
40
+ "max_depth": 2,
41
+ "max_iter": 100,
42
+ "learning_rate": 0.05,
43
+ "min_samples_leaf": 30,
44
+ "max_bins": 255,
45
+ "random_state": 0
46
+ },
47
+ "training_target": "unweighted signed replacement utility: correctness(Bespoke)-correctness(fallback)",
48
+ "training_rows": 3337,
49
+ "training_groups": 1397,
50
+ "policy": {
51
+ "utility_weight": 0.5,
52
+ "disagreement_weight": 0.5,
53
+ "rank": "empirical midrank within evaluation component",
54
+ "disagreement": "abs(FT5_selected_score-B192_score)",
55
+ "quota_numerator": 920,
56
+ "quota_denominator": 3337,
57
+ "quota_rounding": "integer half-up per component",
58
+ "ties": "ascending existing row key"
59
+ },
60
+ "thresholds": {
61
+ "FT5_fallback": {
62
+ "operator": ">",
63
+ "value": 0.763
64
+ },
65
+ "FT5_standalone": {
66
+ "operator": ">",
67
+ "value": 0.5
68
+ },
69
+ "B192": {
70
+ "operator": ">=",
71
+ "value": 0.398
72
+ },
73
+ "Bespoke": {
74
+ "operator": ">",
75
+ "value": 0.5
76
+ }
77
+ },
78
+ "training_metric_alignment": "Per-row squared-loss surrogate; does not directly optimize component-macro balanced accuracy",
79
+ "selection_role": "Final fusion chosen after observed DEV and external results; retrospective for those exposed cohorts",
80
+ "verifier_dependencies": [
81
+ {
82
+ "repo": "lytang/MiniCheck-Flan-T5-Large",
83
+ "revision": "a496016e7b493686ed6e1c52250b9b9d39b0dcb2"
84
+ },
85
+ {
86
+ "repo": "lytang/MiniCheck-DeBERTa-v3-Large",
87
+ "revision": "2f2d01a54fa022a7ffadb76260e1ea8bc88c82bb"
88
+ },
89
+ {
90
+ "repo": "bespokelabs/Bespoke-MiniCheck-7B",
91
+ "revision": "17b48556b0a54218e8fc2f0dbf0c50fa65a0cfba"
92
+ }
93
+ ],
94
+ "verifier_weights_included": false,
95
+ "requires_native_verifier_input_geometry_for_full_pipeline": true
96
+ }
example.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ """Load the trained router; X is the canonical ordered 31-feature matrix."""
2
+ from pathlib import Path
3
+ import numpy as np
4
+ from factcascade.utility_model import UtilityModel
5
+
6
+ root=Path(__file__).parent
7
+ model=UtilityModel.load(root / "router.json")
8
+ # Replace this synthetic vector with the frozen feature implementation output.
9
+ X=np.zeros((1,31),dtype=np.float64)
10
+ print(model.predict(X))
factcascade/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """FactCascade frozen routing primitives; no verifier inference on import."""
2
+ from .routing import route_batch, apply_replacement
3
+ from .utility_model import UtilityModel
4
+ __version__ = "0.1.0"
factcascade/_frozen_numpy.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Exact NumPy learner and preprocessing from the tested cached replay."""
2
+ from __future__ import annotations
3
+ from typing import Any
4
+ import numpy as np
5
+
6
+ class PerformanceError(ValueError):
7
+ """A fail-closed data or algorithm contract violation."""
8
+
9
+ def _impute_and_scale(train_x: np.ndarray, test_x: np.ndarray, *, scale: bool) -> tuple[np.ndarray, np.ndarray, dict[str, np.ndarray]]:
10
+ train_x = np.asarray(train_x, dtype=np.float64)
11
+ test_x = np.asarray(test_x, dtype=np.float64)
12
+ if train_x.ndim != 2 or test_x.ndim != 2 or train_x.shape[1] != test_x.shape[1] or not len(train_x):
13
+ raise PerformanceError("TRAIN_TEST_FEATURE_SHAPE_INVALID")
14
+ medians = np.zeros(train_x.shape[1], dtype=np.float64)
15
+ for column in range(train_x.shape[1]):
16
+ finite = train_x[np.isfinite(train_x[:, column]), column]
17
+ medians[column] = float(np.median(finite)) if len(finite) else 0.0
18
+ train = np.where(np.isfinite(train_x), train_x, medians[None, :])
19
+ test = np.where(np.isfinite(test_x), test_x, medians[None, :])
20
+ means = train.mean(axis=0) if scale else np.zeros(train.shape[1], dtype=np.float64)
21
+ stds = train.std(axis=0) if scale else np.ones(train.shape[1], dtype=np.float64)
22
+ stds[stds < 1e-12] = 1.0
23
+ train = (train - means[None, :]) / stds[None, :]
24
+ test = (test - means[None, :]) / stds[None, :]
25
+ if not np.isfinite(train).all() or not np.isfinite(test).all():
26
+ raise PerformanceError("TRAIN_ONLY_FEATURE_TRANSFORM_NONFINITE")
27
+ return train, test, {"medians": medians, "means": means, "scales": stds}
28
+
29
+ class _HistogramTreeRegressor:
30
+ """Small deterministic squared-loss histogram gradient booster using NumPy."""
31
+
32
+ engine = "d0403ck_b_numpy_histogram_gbr_v1"
33
+
34
+ def __init__(self, *, max_depth: int, max_iter: int, learning_rate: float,
35
+ min_samples_leaf: int, random_state: int = 0, max_bins: int = 255):
36
+ self.max_depth = int(max_depth)
37
+ self.max_iter = int(max_iter)
38
+ self.learning_rate = float(learning_rate)
39
+ self.min_samples_leaf = int(min_samples_leaf)
40
+ self.random_state = int(random_state)
41
+ self.max_bins = int(max_bins)
42
+ self.thresholds: list[np.ndarray] = []
43
+ self.trees: list[Any] = []
44
+ self.initial_value = 0.0
45
+
46
+ def _bin_matrix(self, x: np.ndarray) -> np.ndarray:
47
+ return np.column_stack([
48
+ np.searchsorted(self.thresholds[column], x[:, column], side="right").astype(np.int16)
49
+ for column in range(x.shape[1])
50
+ ])
51
+
52
+ def _build_tree(self, bins: np.ndarray, residual: np.ndarray, indices: np.ndarray, depth: int) -> Any:
53
+ value = float(residual[indices].mean()) if len(indices) else 0.0
54
+ if depth >= self.max_depth or len(indices) < 2 * self.min_samples_leaf:
55
+ return {"value": value}
56
+ best_gain = 0.0
57
+ best: tuple[int, int] | None = None
58
+ for feature in range(bins.shape[1]):
59
+ bin_values = bins[indices, feature]
60
+ bin_count = int(self.thresholds[feature].size + 1)
61
+ counts = np.bincount(bin_values, minlength=bin_count).astype(np.int64)
62
+ sums = np.bincount(bin_values, weights=residual[indices], minlength=bin_count)
63
+ left_count = np.cumsum(counts)[:-1]
64
+ if not len(left_count):
65
+ continue
66
+ right_count = len(indices) - left_count
67
+ valid = (left_count >= self.min_samples_leaf) & (right_count >= self.min_samples_leaf)
68
+ if not np.any(valid):
69
+ continue
70
+ left_sum = np.cumsum(sums)[:-1]
71
+ total_sum = float(sums.sum())
72
+ gain = np.zeros(len(left_count), dtype=np.float64)
73
+ gain[valid] = (
74
+ (left_sum[valid] ** 2) / left_count[valid]
75
+ + ((total_sum - left_sum[valid]) ** 2) / right_count[valid]
76
+ )
77
+ threshold_bin = int(np.argmax(gain))
78
+ candidate_gain = float(gain[threshold_bin])
79
+ if candidate_gain > best_gain + 1e-12:
80
+ best_gain = candidate_gain
81
+ best = (feature, threshold_bin)
82
+ if best is None:
83
+ return {"value": value}
84
+ feature, threshold_bin = best
85
+ left_mask = bins[indices, feature] <= threshold_bin
86
+ left = indices[left_mask]
87
+ right = indices[~left_mask]
88
+ if len(left) < self.min_samples_leaf or len(right) < self.min_samples_leaf:
89
+ return {"value": value}
90
+ return {
91
+ "feature": feature,
92
+ "threshold_bin": threshold_bin,
93
+ "left": self._build_tree(bins, residual, left, depth + 1),
94
+ "right": self._build_tree(bins, residual, right, depth + 1),
95
+ }
96
+
97
+ def _predict_tree(self, bins: np.ndarray, tree: Any) -> np.ndarray:
98
+ output = np.zeros(len(bins), dtype=np.float64)
99
+
100
+ def apply(node: Any, indices: np.ndarray) -> None:
101
+ if not len(indices):
102
+ return
103
+ if "value" in node:
104
+ output[indices] = float(node["value"])
105
+ return
106
+ feature = int(node["feature"])
107
+ left_mask = bins[indices, feature] <= int(node["threshold_bin"])
108
+ apply(node["left"], indices[left_mask])
109
+ apply(node["right"], indices[~left_mask])
110
+
111
+ apply(tree, np.arange(len(bins), dtype=np.int64))
112
+ return output
113
+
114
+ def fit(self, x: np.ndarray, y: np.ndarray) -> "_HistogramTreeRegressor":
115
+ x = np.asarray(x, dtype=np.float64)
116
+ y = np.asarray(y, dtype=np.float64)
117
+ if x.ndim != 2 or y.shape != (len(x),) or not len(x) or not np.isfinite(x).all() or not np.isfinite(y).all():
118
+ raise PerformanceError("GBT_TRAINING_ARRAY_INVALID")
119
+ self.thresholds = []
120
+ for column in range(x.shape[1]):
121
+ unique = np.unique(x[:, column])
122
+ if len(unique) <= self.max_bins:
123
+ cuts = (unique[:-1] + unique[1:]) / 2.0
124
+ else:
125
+ quantiles = np.linspace(0.0, 1.0, self.max_bins + 1)[1:-1]
126
+ cuts = np.unique(np.quantile(x[:, column], quantiles))
127
+ self.thresholds.append(np.asarray(cuts, dtype=np.float64))
128
+ bins = self._bin_matrix(x)
129
+ self.initial_value = float(y.mean())
130
+ prediction = np.full(len(y), self.initial_value, dtype=np.float64)
131
+ self.trees = []
132
+ all_indices = np.arange(len(y), dtype=np.int64)
133
+ for _ in range(self.max_iter):
134
+ residual = y - prediction
135
+ tree = self._build_tree(bins, residual, all_indices, 0)
136
+ self.trees.append(tree)
137
+ prediction += self.learning_rate * self._predict_tree(bins, tree)
138
+ return self
139
+
140
+ def predict(self, x: np.ndarray) -> np.ndarray:
141
+ x = np.asarray(x, dtype=np.float64)
142
+ if x.ndim != 2 or x.shape[1] != len(self.thresholds) or not np.isfinite(x).all():
143
+ raise PerformanceError("GBT_PREDICTION_ARRAY_INVALID")
144
+ bins = self._bin_matrix(x)
145
+ prediction = np.full(len(x), self.initial_value, dtype=np.float64)
146
+ for tree in self.trees:
147
+ prediction += self.learning_rate * self._predict_tree(bins, tree)
148
+ return prediction
factcascade/adapters/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ """Numeric-cache adapters; no downloads or reconstruction of raw cohorts."""
2
+ import csv,json
3
+ from pathlib import Path
4
+ def csv_rows(path,expected_rows):
5
+ with Path(path).open(encoding="utf-8",newline="") as f: rows=list(csv.DictReader(f))
6
+ if len(rows)!=expected_rows: raise ValueError("FROZEN_COHORT_ROW_COUNT_MISMATCH")
7
+ return rows
factcascade/adapters/aggrefact.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """retrospective; original provider join required for labels/components."""
2
+ from . import csv_rows
3
+ ROWS=29320
4
+ DEFAULT_CACHE="aggrefact_own_outputs.csv"
5
+ def load_cached(path): return csv_rows(path,ROWS)
factcascade/adapters/begin.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """post-freeze binary adaptation; equal3corpus macro BA."""
2
+ from . import csv_rows
3
+ ROWS=2000
4
+ DEFAULT_CACHE="begin_eval_numeric.csv"
5
+ def load_cached(path): return csv_rows(path,ROWS)
factcascade/adapters/check_covid.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """post-freeze binary full-abstract adaptation;49abstract groups."""
2
+ from . import csv_rows
3
+ ROWS=151
4
+ DEFAULT_CACHE="checkcovid_eval_numeric.csv"
5
+ def load_cached(path): return csv_rows(path,ROWS)
factcascade/adapters/hover.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """4000 balanced oracle-evidence claims;1592families;not retrieval-task scores."""
2
+ from pathlib import Path
3
+ import numpy as np
4
+ def load_cached(path):
5
+ with np.load(Path(path),allow_pickle=False) as z: arrays={k:z[k] for k in z.files}
6
+ if not any(v.ndim and v.shape[0]==4000 for v in arrays.values()):
7
+ raise ValueError("FROZEN_HOVER_CARDINALITY_MISMATCH")
8
+ return arrays
factcascade/features.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Frozen 31-slot schema over supplied text and verifier observations.
2
+
3
+ This does not reconstruct benchmark packets or run inference. The caller must
4
+ supply the same segmentation/chunk counts and evidence-unit coverage.
5
+ """
6
+ from __future__ import annotations
7
+ from typing import Any, Mapping
8
+ import math, re
9
+ import numpy as np
10
+ FT5_THRESHOLD=0.763
11
+ FEATURE_NAMES=['ft5_score', 'ft5_abs_distance_to_calibrated_threshold', 'b192_score', 'ft5_b192_delta', 'ft5_b192_disagreement', 'table_or_mixed_indicator', 'ft5_margin_x_table', 'ft5_full_score', 'selected_full_score_delta', 'selected_full_disagreement', 'log_ft5_selected_chunks', 'log_ft5_full_chunks', 'log_claim_word_count', 'log_selected_evidence_words', 'log_full_evidence_words', 'log_selected_source_count', 'selected_source_coverage_ratio', 'ft5_selected_margin_to_050', 'ft5_selected_margin_to_0763', 'ft5_full_minus_selected', 'b192_minus_ft5_selected', 'b192_ft5_decision_disagreement', 'full_only_support_signal', 'b192_disagreement_x_table_or_mixed', 'selected_full_discrepancy_x_evidence_length_ratio', 'claim_negation_proxy_count', 'claim_comparator_quantifier_count', 'claim_numeral_unit_count', 'claim_titlecase_entity_proxy_count', 'claim_selected_number_overlap_ratio', 'claim_entity_selected_minus_full_overlap']
12
+ F5_NAMES=('ft5_selected_margin_to_050', 'ft5_selected_margin_to_0763', 'ft5_full_minus_selected', 'b192_minus_ft5_selected', 'b192_ft5_decision_disagreement', 'full_only_support_signal', 'b192_disagreement_x_table_or_mixed', 'selected_full_discrepancy_x_evidence_length_ratio')
13
+ F2_NAMES=('claim_negation_proxy_count', 'claim_comparator_quantifier_count', 'claim_numeral_unit_count', 'claim_titlecase_entity_proxy_count', 'claim_selected_number_overlap_ratio', 'claim_entity_selected_minus_full_overlap')
14
+ def _finite_number(value: Any) -> float | None:
15
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
16
+ return None
17
+ value = float(value)
18
+ return value if math.isfinite(value) else None
19
+
20
+ def _text(value: Any) -> str | None:
21
+ return value if isinstance(value, str) else None
22
+
23
+ def _tokens(value: str) -> list[str]:
24
+ return [token.casefold() for token in re.findall(r"[A-Za-z0-9]+(?:['’][A-Za-z0-9]+)?", value)]
25
+
26
+ def _content_terms(value: str) -> set[str]:
27
+ stop = {"a", "an", "the", "and", "or", "of", "to", "in", "on", "for", "by", "with", "is", "are", "was", "were", "be", "as", "at", "from"}
28
+ return {token for token in _tokens(value) if len(token) > 1 and token not in stop}
29
+
30
+ def _numbers(value: str) -> set[str]:
31
+ return {
32
+ re.sub(r",(?=\d{3}(?:\D|$))", "", match.casefold())
33
+ for match in re.findall(r"(?<![A-Za-z])[-+]?\d[\d,]*(?:\.\d+)?%?(?![A-Za-z])", value)
34
+ }
35
+
36
+ def _entities(value: str) -> set[str]:
37
+ # Deterministic surface proxy only; no NER model or external lookup.
38
+ matches = re.findall(r"\b[A-Z][a-z]{2,}(?:\s+[A-Z][a-z]{2,})*\b", value)
39
+ return {" ".join(_tokens(match)) for match in matches}
40
+
41
+ def _overlap(left: set[str], right: set[str]) -> float:
42
+ return len(left & right) / len(left) if left else 0.0
43
+
44
+ class RouterFitError(ValueError):
45
+ pass
46
+
47
+ def _base_features(input_row: Mapping[str, Any], selected: Mapping[str, Any], full: Mapping[str, Any], b192: Mapping[str, Any], selected_geometry: Mapping[str, Any], full_geometry: Mapping[str, Any]) -> np.ndarray:
48
+ ft5 = float(selected["score"])
49
+ ft5_full = float(full["score"])
50
+ b192_score = float(b192["score"])
51
+ if not all(math.isfinite(value) and 0.0 <= value <= 1.0 for value in (ft5, ft5_full, b192_score)):
52
+ raise RouterFitError("CHEAP_MODEL_SCORE_INVALID")
53
+ table = float(input_row.get("modality") == "TABLE_OR_MIXED")
54
+ ft5_calibrated = ft5 > FT5_THRESHOLD
55
+ b192_prediction = b192.get("prediction")
56
+ selected_prediction = selected.get("prediction")
57
+ full_prediction = full.get("prediction")
58
+ if not all(isinstance(value, bool) for value in (b192_prediction, selected_prediction, full_prediction)):
59
+ raise RouterFitError("CHEAP_MODEL_PREDICTION_INVALID")
60
+ selected_full_delta = ft5_full - ft5
61
+ ft5_full_disagreement = int((ft5 > FT5_THRESHOLD) != (ft5_full > FT5_THRESHOLD))
62
+ features = [
63
+ ft5,
64
+ abs(ft5 - FT5_THRESHOLD),
65
+ b192_score,
66
+ ft5 - b192_score,
67
+ float(ft5_calibrated != b192_prediction),
68
+ table,
69
+ abs(ft5 - FT5_THRESHOLD) * table,
70
+ ft5_full,
71
+ selected_full_delta,
72
+ float(ft5_full_disagreement),
73
+ math.log1p(int(selected_geometry["chunk_count"])),
74
+ math.log1p(int(full_geometry["chunk_count"])),
75
+ math.log1p(len(str(input_row.get("claim", "")).split())),
76
+ math.log1p(len(str(input_row.get("selected_context", "")).split())),
77
+ math.log1p(len(str(input_row.get("full_fixed_evidence_packet", "")).split())),
78
+ math.log1p(int(input_row.get("selected_source_count", 0))),
79
+ float(input_row.get("selected_source_coverage_ratio", 0.0)),
80
+ ]
81
+ if len(features) != 17 or not np.isfinite(np.asarray(features, dtype=np.float64)).all():
82
+ raise RouterFitError("A2_FEATURE_VECTOR_INVALID")
83
+ return np.asarray(features, dtype=np.float64)
84
+
85
+ def _extra_features(input_row: Mapping[str, Any], pair_row: Mapping[str, Any]) -> tuple[dict[str, float], dict[str, bool]]:
86
+ values: dict[str, float] = {}
87
+ available: dict[str, bool] = {}
88
+ cheap = pair_row.get("cheap_model_features")
89
+ cheap = cheap if isinstance(cheap, dict) else {}
90
+ ft5 = _finite_number(cheap.get("ft5_score"))
91
+ full = _finite_number(cheap.get("ft5_full_score"))
92
+ b192 = _finite_number(cheap.get("b192_score"))
93
+ full_words = _finite_number(cheap.get("full_document_word_count"))
94
+ selected_words = _finite_number(cheap.get("selected_document_word_count"))
95
+ table = float(str(input_row.get("modality", pair_row.get("modality", ""))) == "TABLE_OR_MIXED")
96
+ f5_raw: dict[str, float | None] = {
97
+ F5_NAMES[0]: abs(ft5 - 0.5) if ft5 is not None else None,
98
+ F5_NAMES[1]: abs(ft5 - FT5_THRESHOLD) if ft5 is not None else None,
99
+ F5_NAMES[2]: full - ft5 if full is not None and ft5 is not None else None,
100
+ F5_NAMES[3]: b192 - ft5 if b192 is not None and ft5 is not None else None,
101
+ F5_NAMES[4]: float(bool(cheap.get("ft5_b192_disagreement"))) if isinstance(cheap.get("ft5_b192_disagreement"), (bool, int)) else None,
102
+ F5_NAMES[5]: float(full > FT5_THRESHOLD and ft5 <= FT5_THRESHOLD) if full is not None and ft5 is not None else None,
103
+ F5_NAMES[6]: float(bool(cheap.get("ft5_b192_disagreement"))) * table if isinstance(cheap.get("ft5_b192_disagreement"), (bool, int)) else None,
104
+ F5_NAMES[7]: abs(full - ft5) * math.log1p(max(0.0, full_words)) / max(1.0, math.log1p(max(0.0, selected_words)))
105
+ if full is not None and ft5 is not None and full_words is not None and selected_words is not None else None,
106
+ }
107
+ for key, value in f5_raw.items():
108
+ available[key] = value is not None
109
+ values[key] = float(value) if value is not None else float("nan")
110
+
111
+ claim = _text(input_row.get("claim")) or _text(input_row.get("claim_text"))
112
+ selected = _text(input_row.get("selected_context"))
113
+ full_text = _text(input_row.get("full_fixed_evidence_packet"))
114
+ text_ready = claim is not None and selected is not None and full_text is not None
115
+ if text_ready:
116
+ claim_terms = _content_terms(claim)
117
+ selected_terms = _content_terms(selected)
118
+ full_terms = _content_terms(full_text)
119
+ claim_entities = _entities(claim)
120
+ selected_entities = _entities(selected)
121
+ full_entities = _entities(full_text)
122
+ claim_nums = _numbers(claim)
123
+ selected_nums = _numbers(selected)
124
+ negation_matches = list(re.finditer(
125
+ r"\b(?:no|not|never|neither|nor|without|cannot|can't|doesn't|don't|didn't|isn't|aren't|wasn't|weren't)\b",
126
+ claim, flags=re.IGNORECASE,
127
+ ))
128
+ negation_scope_terms = 0
129
+ for match in negation_matches:
130
+ # Count at most five content terms in the next punctuation-bounded scope window.
131
+ scope = re.split(r"[.!?;:]", claim[match.end():], maxsplit=1)[0]
132
+ negation_scope_terms += len(_content_terms(" ".join(_tokens(scope)[:5])))
133
+ comparators = re.findall(r"\b(?:more|less|greater|fewer|higher|lower|at least|at most|exactly|only|all|every|each|most|least|equal(?:s)?|between|than|over|under)\b", claim, flags=re.IGNORECASE)
134
+ numeric_units = re.findall(r"(?<![A-Za-z])[-+]?\d[\d,]*(?:\.\d+)?\s*(?:%|percent|km|miles?|meters?|kg|grams?|years?|months?|days?|hours?|million|billion)?", claim, flags=re.IGNORECASE)
135
+ f2 = {
136
+ F2_NAMES[0]: float(len(negation_matches) + negation_scope_terms),
137
+ F2_NAMES[1]: float(len(comparators)),
138
+ F2_NAMES[2]: float(len(numeric_units)),
139
+ F2_NAMES[3]: float(min(20, len(claim_entities))),
140
+ F2_NAMES[4]: _overlap(claim_nums, selected_nums),
141
+ F2_NAMES[5]: _overlap(claim_entities, selected_entities) - _overlap(claim_entities, full_entities),
142
+ }
143
+ else:
144
+ f2 = {name: None for name in F2_NAMES}
145
+ for key, value in f2.items():
146
+ available[key] = value is not None
147
+ values[key] = float(value) if value is not None else float("nan")
148
+
149
+ return values, available
150
+
151
+ def build_features(*,claim,selected_evidence,full_evidence,selected_ft5_score,full_ft5_score,deberta_score,
152
+ selected_chunks,full_chunks,selected_source_count=1,source_coverage=1.0,
153
+ table_or_mixed=False,adapter="external"):
154
+ if adapter not in ("dev","external"): raise ValueError("UNKNOWN_FEATURE_ADAPTER")
155
+ if any(not isinstance(x,str) for x in (claim,selected_evidence,full_evidence)):
156
+ raise ValueError("SUPPLIED_TEXT_REQUIRED")
157
+ if any(type(x) is not int or x<0 for x in (selected_chunks,full_chunks,selected_source_count)):
158
+ raise ValueError("NONNEGATIVE_COUNTS_REQUIRED")
159
+ if not isinstance(source_coverage,(int,float)) or not math.isfinite(source_coverage) or not 0<=source_coverage<=1:
160
+ raise ValueError("SOURCE_COVERAGE_INVALID")
161
+ if type(table_or_mixed) is not bool: raise ValueError("MODALITY_FLAG_INVALID")
162
+ s,f,d=map(float,(selected_ft5_score,full_ft5_score,deberta_score))
163
+ inp=dict(claim=claim,selected_context=selected_evidence,full_fixed_evidence_packet=full_evidence,
164
+ modality="TABLE_OR_MIXED" if table_or_mixed else "TEXT",selected_source_count=selected_source_count,
165
+ selected_source_coverage_ratio=source_coverage)
166
+ base=_base_features(inp,dict(score=s,prediction=s>0.5),dict(score=f,prediction=f>0.5),
167
+ dict(score=d,prediction=d>=0.398),dict(chunk_count=selected_chunks),dict(chunk_count=full_chunks))
168
+ delta_a=float((s>(0.763 if adapter=="dev" else 0.5))!=(d>=0.398))
169
+ cheap=dict(ft5_score=s,ft5_full_score=f,b192_score=d,ft5_b192_disagreement=int(delta_a),
170
+ selected_document_word_count=len(selected_evidence.split()),full_document_word_count=len(full_evidence.split()))
171
+ values,_=_extra_features(inp,dict(cheap_model_features=cheap))
172
+ x=np.asarray(list(base)+[values[n] for n in FEATURE_NAMES[17:]],dtype=float)
173
+ if x.shape!=(31,) or not np.isfinite(x).all(): raise ValueError("FEATURE_VECTOR_INVALID")
174
+ return x
factcascade/metrics.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pooled and macro metrics are distinct; values are fractions, not percent."""
2
+ import numpy as np
3
+ def binary_metrics(labels,predictions,weights=None):
4
+ y,p=[np.asarray(v) for v in (labels,predictions)]
5
+ if y.dtype!=np.bool_ or p.dtype!=np.bool_ or y.ndim!=1 or y.shape!=p.shape or not len(y):
6
+ raise ValueError("BOOLEAN_NONEMPTY_PAIRED_ARRAYS_REQUIRED")
7
+ w=np.ones(len(y)) if weights is None else np.asarray(weights,dtype=float)
8
+ if w.shape!=y.shape or not np.isfinite(w).all() or np.any(w<=0): raise ValueError("POSITIVE_WEIGHTS_REQUIRED")
9
+ sr=float(w[y&p].sum()/w[y].sum()) if y.any() else None
10
+ nr=float(w[(~y)&(~p)].sum()/w[~y].sum()) if (~y).any() else None
11
+ return dict(balanced_accuracy=(sr+nr)/2 if sr is not None and nr is not None else None,
12
+ supported_recall=sr,false_supported_rate=1-nr if nr is not None else None,
13
+ ordinary_accuracy=float((y==p).mean()),weighted_accuracy=float(w[y==p].sum()/w.sum()),
14
+ correct=int((y==p).sum()),rows=len(y))
15
+
16
+ def macro_balanced_accuracy(labels,predictions,strata,weights=None,single_class_accuracy=False):
17
+ y,p=[np.asarray(v) for v in (labels,predictions)]
18
+ binary_metrics(y,p,weights)
19
+ if len(strata)!=len(y): raise ValueError("STRATUM_LENGTH_MISMATCH")
20
+ w=np.ones(len(y)) if weights is None else np.asarray(weights,dtype=float)
21
+ groups={}
22
+ for i,s in enumerate(strata): groups.setdefault(s,[]).append(i)
23
+ values=[]
24
+ for ix in groups.values():
25
+ m=binary_metrics(y[ix],p[ix],w[ix]);score=m["balanced_accuracy"]
26
+ if score is None:
27
+ if not single_class_accuracy: raise ValueError("SINGLE_CLASS_STRATUM_BA_UNDEFINED")
28
+ score=m["weighted_accuracy"]
29
+ values.append(score)
30
+ return float(np.mean(values))
factcascade/quota.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ """Exact rational half-up quota, including large integer batch sizes."""
2
+ def half_up_quota(size, numerator=920, denominator=3337):
3
+ if any(type(x) is not int for x in (size,numerator,denominator)):
4
+ raise ValueError("INTEGER_QUOTA_ARGUMENTS_REQUIRED")
5
+ if size<0 or denominator<=0 or not 0<=numerator<=denominator:
6
+ raise ValueError("QUOTA_ARGUMENT_INVALID")
7
+ return (2*numerator*size+denominator)//(2*denominator)
factcascade/rank_fusion.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Frozen normalized average midranks and equal-weight fusion."""
2
+ import numpy as np
3
+
4
+ def require(condition,code):
5
+ if not condition: raise ValueError(code)
6
+
7
+ def midrank(values):
8
+ """Empirical ranks; equal values share their middle rank, including constants."""
9
+ values = np.asarray(values, float)
10
+ require(values.ndim == 1 and len(values) and np.isfinite(values).all(), "RANK_INPUT_INVALID")
11
+ if len(values) == 1:
12
+ return np.asarray([0.5])
13
+ _, inverse, counts = np.unique(values, return_inverse=True, return_counts=True)
14
+ left = np.cumsum(counts) - counts
15
+ return ((left + (counts - 1) / 2) / (len(values) - 1))[inverse]
16
+
17
+ def fusion_score(utility, selected_ft5, deberta):
18
+ utility, selected_ft5, deberta = [np.asarray(x,dtype=float) for x in (utility,selected_ft5,deberta)]
19
+ if utility.shape != selected_ft5.shape or utility.shape != deberta.shape:
20
+ raise ValueError("SCORE_LENGTH_MISMATCH")
21
+ return 0.5*midrank(utility)+0.5*midrank(np.abs(selected_ft5-deberta))
factcascade/routing.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Allocation operates within declared batches and never reads evaluation labels."""
2
+ from dataclasses import dataclass
3
+ import numpy as np
4
+ from .rank_fusion import fusion_score
5
+ from .quota import half_up_quota
6
+
7
+ @dataclass(frozen=True)
8
+ class RoutingResult:
9
+ route_mask: np.ndarray
10
+ route_scores: np.ndarray
11
+ predicted_utility: np.ndarray
12
+
13
+ def decisions(scores, verifier="fallback"):
14
+ x=np.asarray(scores,dtype=float)
15
+ if x.ndim!=1 or not np.isfinite(x).all() or np.any((x<0)|(x>1)):
16
+ raise ValueError("VERIFIER_SCORE_INVALID")
17
+ if verifier=="fallback": return x>0.763
18
+ if verifier in ("ft5","bespoke"): return x>0.5
19
+ if verifier=="deberta": return x>=0.398
20
+ raise ValueError("UNKNOWN_VERIFIER")
21
+
22
+ def route_batch(*,selected_ft5_scores,deberta_scores,batch_ids,utility_scores=None,features=None,utility_model=None,row_keys=None):
23
+ s,d=[np.asarray(x,dtype=float) for x in (selected_ft5_scores,deberta_scores)]
24
+ decisions(s);decisions(d,"deberta")
25
+ n=len(s)
26
+ if n==0 or d.shape!=s.shape or len(batch_ids)!=n: raise ValueError("BATCH_INPUT_INVALID")
27
+ if any(not isinstance(x,str) or not x for x in batch_ids): raise ValueError("BATCH_IDS_MUST_BE_NONEMPTY_STRINGS")
28
+ if utility_scores is None:
29
+ if features is None or utility_model is None: raise ValueError("UTILITY_SCORES_OR_FEATURES_AND_MODEL_REQUIRED")
30
+ u=np.asarray(utility_model.predict(features),dtype=float)
31
+ else:
32
+ if features is not None or utility_model is not None: raise ValueError("UTILITY_INPUT_AMBIGUOUS")
33
+ u=np.asarray(utility_scores,dtype=float)
34
+ if u.shape!=s.shape or not np.isfinite(u).all(): raise ValueError("UTILITY_ARRAY_INVALID")
35
+ keys=list(row_keys) if row_keys is not None else [f"{i:020d}" for i in range(n)]
36
+ if len(keys)!=n or len(set(keys))!=n or any(not isinstance(k,str) or not k for k in keys):
37
+ raise ValueError("ROW_KEYS_MUST_BE_UNIQUE_NONEMPTY_STRINGS")
38
+ batches={}
39
+ for i,b in enumerate(batch_ids): batches.setdefault(b,[]).append(i)
40
+ mask=np.zeros(n,dtype=bool);scores=np.zeros(n,dtype=float)
41
+ for indices in batches.values():
42
+ ix=np.asarray(indices);scores[ix]=fusion_score(u[ix],s[ix],d[ix])
43
+ order=sorted(indices,key=lambda i:(-float(scores[i]),keys[i]))
44
+ mask[order[:half_up_quota(len(indices))]]=True
45
+ return RoutingResult(mask,scores,u)
46
+
47
+ def apply_replacement(selected_ft5_scores,bespoke_scores,route_mask):
48
+ fallback=decisions(selected_ft5_scores);r=np.asarray(route_mask)
49
+ b=np.asarray(bespoke_scores,dtype=float)
50
+ if r.dtype!=np.bool_ or r.shape!=fallback.shape or b.shape!=fallback.shape:
51
+ raise ValueError("REPLACEMENT_ARRAY_INVALID")
52
+ # Unrouted expensive scores may be absent/NaN: no all-row Bespoke call is required.
53
+ final=fallback.copy();final[r]=decisions(b[r],"bespoke")
54
+ return final
factcascade/utility_model.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Frozen NumPy regression recipe; checkpoints are JSON, never executable pickle."""
2
+ import json
3
+ from pathlib import Path
4
+ import numpy as np
5
+ from .features import FEATURE_NAMES
6
+ from ._frozen_numpy import _HistogramTreeRegressor, _impute_and_scale
7
+
8
+ CONFIG=dict(max_depth=2,max_iter=100,learning_rate=0.05,min_samples_leaf=30,max_bins=255,random_state=0)
9
+ class UtilityModel:
10
+ def fit(self,features,fallback,bespoke,labels):
11
+ x=np.asarray(features,dtype=float)
12
+ if x.ndim!=2 or x.shape[1]!=31: raise ValueError("EXACT_31_FEATURES_REQUIRED")
13
+ a,b,y=[np.asarray(v) for v in (fallback,bespoke,labels)]
14
+ if any(v.dtype!=np.bool_ or v.shape!=(len(x),) for v in (a,b,y)):
15
+ raise ValueError("BOOLEAN_PAIRED_LABELS_REQUIRED")
16
+ target=(b==y).astype(float)-(a==y).astype(float)
17
+ train,_,self.transform=_impute_and_scale(x,x,scale=True)
18
+ self.model=_HistogramTreeRegressor(**CONFIG).fit(train,target)
19
+ return self
20
+ def predict(self,features):
21
+ if not hasattr(self,"model"): raise ValueError("MODEL_NOT_FITTED")
22
+ x=np.asarray(features,dtype=float)
23
+ if x.ndim!=2 or x.shape[1]!=31: raise ValueError("EXACT_31_FEATURES_REQUIRED")
24
+ t=self.transform
25
+ filled=np.where(np.isfinite(x),x,t["medians"][None,:])
26
+ return self.model.predict((filled-t["means"][None,:])/t["scales"][None,:])
27
+ def to_dict(self):
28
+ if not hasattr(self,"model"): raise ValueError("MODEL_NOT_FITTED")
29
+ state=vars(self.model).copy();state["thresholds"]=[v.tolist() for v in state["thresholds"]]
30
+ return dict(schema="FACTCASCADE_UTILITY_JSON_V1",feature_order=FEATURE_NAMES,
31
+ config=CONFIG,transform={k:v.tolist() for k,v in self.transform.items()},model=state)
32
+ @classmethod
33
+ def from_dict(cls,data):
34
+ if data.get("schema")!="FACTCASCADE_UTILITY_JSON_V1" or data.get("feature_order")!=FEATURE_NAMES or data.get("config")!=CONFIG:
35
+ raise ValueError("CHECKPOINT_SCHEMA_OR_CONFIG_MISMATCH")
36
+ result=cls();result.transform={k:np.asarray(data["transform"][k],dtype=float) for k in ["medians","means","scales"]}
37
+ if any(v.shape!=(31,) or not np.isfinite(v).all() for v in result.transform.values()) or np.any(result.transform["scales"]<=0):
38
+ raise ValueError("CHECKPOINT_TRANSFORM_INVALID")
39
+ model=data["model"]
40
+ if any(model[k]!=v for k,v in CONFIG.items()) or len(model["thresholds"])!=31 or len(model["trees"])!=100:
41
+ raise ValueError("CHECKPOINT_MODEL_INVALID")
42
+ result.model=_HistogramTreeRegressor(**CONFIG)
43
+ result.model.initial_value=float(model["initial_value"])
44
+ if not np.isfinite(result.model.initial_value): raise ValueError("CHECKPOINT_NONFINITE")
45
+ result.model.thresholds=[np.asarray(v,dtype=float) for v in model["thresholds"]]
46
+ if any(v.ndim!=1 or not np.isfinite(v).all() or np.any(np.diff(v)<=0) for v in result.model.thresholds):
47
+ raise ValueError("CHECKPOINT_THRESHOLDS_INVALID")
48
+ def tree(node,depth=0):
49
+ if set(node)=={"value"} and np.isfinite(node["value"]): return
50
+ if set(node)!={"feature","threshold_bin","left","right"} or depth>=2:
51
+ raise ValueError("CHECKPOINT_TREE_INVALID")
52
+ f,t=node["feature"],node["threshold_bin"]
53
+ if type(f) is not int or not 0<=f<31 or type(t) is not int or not 0<=t<len(result.model.thresholds[f]):
54
+ raise ValueError("CHECKPOINT_SPLIT_INVALID")
55
+ tree(node["left"],depth+1);tree(node["right"],depth+1)
56
+ for n in model["trees"]: tree(n)
57
+ result.model.trees=model["trees"]
58
+ return result
59
+ @classmethod
60
+ def load(cls,path): return cls.from_dict(json.loads(Path(path).read_bytes()))
61
+ def save(self,path): Path(path).write_text(json.dumps(self.to_dict(),allow_nan=False)+"\n",encoding="utf-8")
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ numpy==1.26.4
router.json ADDED
The diff for this file is too large to render. See raw diff