SourceHat commited on
Commit
e7ed103
·
0 Parent(s):

Release SourceHat RLCD 1.0.0 BF16

Browse files
.gitattributes ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
2
+ tokenizer.json 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 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.
NOTICE ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ SourceHat RLCD
2
+ SourceHat adaptation and standalone inference wrapper: Copyright 2026 MCP Capital LLC.
3
+
4
+ Based on Cloudflare/Clef, an Apache-2.0 typed-decision model built on Qwen.
5
+ Clef revision: 0b331204bb13fbd2ca93a64df1956f5b55478ce5
6
+ The included upstream license retains Copyright 2026 Alibaba Cloud.
7
+ The compiler and joint-head inference components in clef_runtime.py are derived from
8
+ Cloudflare/Clef joint_schema_model.py at that revision. SourceHat adds text LoRA,
9
+ a trained joint head, strict text-only request validation, canonical IDs, FP32
10
+ head/lexical-feature boundaries, integrity checks, and the standalone wrapper.
11
+ No Cloudflare or Alibaba endorsement is implied.
12
+
13
+ Training-source attribution: Banking77 (PolyAI), CC BY 4.0; CLINC-OOS
14
+ (Larson et al.), CC BY 3.0. Dataset records are not distributed. Pinned source
15
+ references are included in the model card and aggregate results.
README.md ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ base_model: Cloudflare/clef
4
+ base_model_relation: finetune
5
+ language: [en]
6
+ tags: [rlcd, typed-decision, classification, safetensors, custom-code]
7
+ ---
8
+
9
+ # SourceHat RLCD
10
+
11
+ SourceHat RLCD returns typed categorical, binary, and ordinal decisions from
12
+ a shared Clef/Qwen-derived backbone. This edition contains the complete backbone
13
+ with all 496 trained text updates mathematically folded into its dense weights,
14
+ plus the FP32 joint decision head, in one `model.safetensors` file.
15
+
16
+ There are no adapter files, runtime LoRA branches, PEFT dependency, or separate
17
+ base-model downloads. Tokenizer, configuration, and the inference wrapper are included.
18
+
19
+ ## Dense BF16 Deployment Check
20
+
21
+ > Private review draft, not an all-gates-passed or publication-ready declaration.
22
+
23
+ These measurements describe the genuinely merged BF16 weights in this edition, not the earlier runtime-LoRA composition. Bold values are best within each matched population; ties are bold for both models.
24
+
25
+ | Population / model | Correct fields | Correct objects | Response coverage | Field NLL | Field Brier |
26
+ | --- | ---: | ---: | ---: | ---: | ---: |
27
+ | Historical: unmerged reference | **410/439** | **230/256** | **100%** | 0.151181 | 0.082997 |
28
+ | Historical: dense BF16 | 409/439 | 229/256 | **100%** | **0.149168** | **0.080889** |
29
+ | Fresh: unmerged reference | 305/326 | 111/128 | **100%** | 0.145430 | 0.077869 |
30
+ | Fresh: dense BF16 | **306/326** | **112/128** | **100%** | **0.142819** | **0.076039** |
31
+
32
+ Both models have 100% response and probability-scoring coverage on both populations. These are bounded release checks, not the campaign's sealed final evaluation or a production-domain guarantee. The reference is the trained, unmerged model, not original Clef.
33
+
34
+ The separate numerical-fidelity check does not pass: four reload probes preserve all top-1 choices, but their maximum candidate-probability change is 0.055960, against the unchanged 0.020000 tolerance. Passing population-quality checks does not override this check. Over the complete historical and fresh populations, maximum probability changes are 0.106855 and 0.090278. The smaller four-probe value is not the global maximum.
35
+
36
+ Candidate-order and opaque-ID checks each cover 32 paired cases, with maximum logit differences 0 and 0. This tests unchanged descriptions and semantics, not arbitrary paraphrases.
37
+
38
+ Peak PyTorch-reserved memory is 53.13 GiB on one 64-GiB NVIDIA CMP 170HX. Mean warm request time is 2.551 seconds across 144 newly executed requests; cached predictions and model loading are excluded. This is not a validated single-16-GiB deployment.
39
+
40
+ ## Historical Training-Checkpoint Results
41
+
42
+ All models below scored the same 256 cases and 439 fields with 100% response coverage.
43
+ These are historical training-checkpoint results. The dense edition's separate
44
+ measurements and unresolved numerical-fidelity check are reported above.
45
+
46
+ | Model | Correct fields | Correct complete objects | Field NLL | Field Brier |
47
+ | --- | ---: | ---: | ---: | ---: |
48
+ | Original full Clef | 395/439 (90.0%) | 216/256 (84.4%) | 0.2519 | 0.1268 |
49
+ | Trained head only | 403/439 (91.8%) | 223/256 (87.1%) | 0.2041 | 0.1070 |
50
+ | RLCD trained checkpoint | **410/439 (93.4%)** | **230/256 (89.8%)** | **0.1512** | **0.0830** |
51
+
52
+ The population contains 160 executable synthetic cases, 48 Banking77 cases,
53
+ and 48 CLINC-OOS cases with restricted candidate lists. Training uses seed 126.
54
+ The [aggregate supplement](evaluation/rlcd_evaluation_data.json) distinguishes
55
+ historical measurements from the current package's verification status.
56
+
57
+ ## Contract and Runtime
58
+
59
+ The [decision contract](decision_contract.json) accepts 1-4 text-only fields:
60
+ categorical choices with 2-16 candidates, binary propositions with true then
61
+ false, and ordered scales with 2-14 levels. The compiled limit is 2048 tokens;
62
+ oversized requests are rejected, not truncated. Caller IDs are not model features.
63
+
64
+ The model proposes supplied choices and raw field distributions. It does not
65
+ execute actions or independently estimate object correctness, safety, or workflow
66
+ success. Supply applicable policies and meaningful fallback choices.
67
+
68
+ ```bash
69
+ hf download SourceHat-Labs/RLCD-27B --local-dir ./sourcehat-rlcd
70
+ cd sourcehat-rlcd
71
+ python -m pip install -r requirements.txt
72
+ CUDA_VISIBLE_DEVICES=2 python inference.py --request example_request.json --device cuda:0
73
+ ```
74
+
75
+ Select the physical GPU appropriate to your machine. Use the included typed-head
76
+ loader, not a generic chat-generation loader. BF16 backbone storage and the FP32
77
+ head total 55.23 GB. The measured dense runtime and quality checks are reported
78
+ above, including the unresolved numerical-fidelity check; this is not a
79
+ single-16-GiB runtime claim.
80
+
81
+ ## License, Provenance, and Scope
82
+
83
+ The exact base/tokenizer is `Cloudflare/clef` revision
84
+ `0b331204bb13fbd2ca93a64df1956f5b55478ce5`. Training used supervised CE, Brier,
85
+ ordinal RPS, and a reference KL term, not policy-gradient RL. The package is
86
+ Apache-2.0; see [LICENSE](LICENSE) and [NOTICE](NOTICE) for attribution.
87
+ Training-source references: [Banking77](https://huggingface.co/datasets/PolyAI/banking77),
88
+ CC BY 4.0; [CLINC-OOS](https://huggingface.co/datasets/clinc/clinc_oos), CC BY 3.0.
89
+ No training records, scripts, private prompts, logs, or intermediate checkpoints
90
+ are included. This is a research model, not a safety or production-risk certificate.
91
+
92
+ ## Packaging Identity
93
+
94
+ Version 1.0.0 uses the public typed-decision-v1 contract. CPU checks prove that
95
+ the renamed wrapper preserves native compilation and fixed-logit responses.
96
+ The BF16 and INT8 containers have branding-only header changes; tensor bytes
97
+ are unchanged. EXL3 weights are byte-identical. Historical source hashes
98
+ identify the original measured containers, not a newly executed quantization.
99
+ The earlier offline CLI checks exercised the original wrappers; no new
100
+ neural execution or evaluation was performed for this packaging migration.
101
+ All model repositories and website candidates remain private/review-only.
102
+
103
+ See the [SourceHat RLCD article](https://sourcehat.com/research/sourcehat-rlcd/).
backbone_config.json ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen3_5ForConditionalGeneration"
4
+ ],
5
+ "dtype": "bfloat16",
6
+ "image_token_id": 248056,
7
+ "language_model_only": false,
8
+ "model_type": "qwen3_5",
9
+ "text_config": {
10
+ "attention_bias": false,
11
+ "attention_dropout": 0.0,
12
+ "attn_output_gate": true,
13
+ "bos_token_id": 248044,
14
+ "dtype": "bfloat16",
15
+ "eos_token_id": 248044,
16
+ "full_attention_interval": 4,
17
+ "head_dim": 256,
18
+ "hidden_act": "silu",
19
+ "hidden_size": 5120,
20
+ "initializer_range": 0.02,
21
+ "intermediate_size": 17408,
22
+ "layer_types": [
23
+ "linear_attention",
24
+ "linear_attention",
25
+ "linear_attention",
26
+ "full_attention",
27
+ "linear_attention",
28
+ "linear_attention",
29
+ "linear_attention",
30
+ "full_attention",
31
+ "linear_attention",
32
+ "linear_attention",
33
+ "linear_attention",
34
+ "full_attention",
35
+ "linear_attention",
36
+ "linear_attention",
37
+ "linear_attention",
38
+ "full_attention",
39
+ "linear_attention",
40
+ "linear_attention",
41
+ "linear_attention",
42
+ "full_attention",
43
+ "linear_attention",
44
+ "linear_attention",
45
+ "linear_attention",
46
+ "full_attention",
47
+ "linear_attention",
48
+ "linear_attention",
49
+ "linear_attention",
50
+ "full_attention",
51
+ "linear_attention",
52
+ "linear_attention",
53
+ "linear_attention",
54
+ "full_attention",
55
+ "linear_attention",
56
+ "linear_attention",
57
+ "linear_attention",
58
+ "full_attention",
59
+ "linear_attention",
60
+ "linear_attention",
61
+ "linear_attention",
62
+ "full_attention",
63
+ "linear_attention",
64
+ "linear_attention",
65
+ "linear_attention",
66
+ "full_attention",
67
+ "linear_attention",
68
+ "linear_attention",
69
+ "linear_attention",
70
+ "full_attention",
71
+ "linear_attention",
72
+ "linear_attention",
73
+ "linear_attention",
74
+ "full_attention",
75
+ "linear_attention",
76
+ "linear_attention",
77
+ "linear_attention",
78
+ "full_attention",
79
+ "linear_attention",
80
+ "linear_attention",
81
+ "linear_attention",
82
+ "full_attention",
83
+ "linear_attention",
84
+ "linear_attention",
85
+ "linear_attention",
86
+ "full_attention"
87
+ ],
88
+ "linear_conv_kernel_dim": 4,
89
+ "linear_key_head_dim": 128,
90
+ "linear_num_key_heads": 16,
91
+ "linear_num_value_heads": 48,
92
+ "linear_value_head_dim": 128,
93
+ "mamba_ssm_dtype": "float32",
94
+ "max_position_embeddings": 262144,
95
+ "model_type": "qwen3_5_text",
96
+ "mtp_num_hidden_layers": 0,
97
+ "mtp_use_dedicated_embeddings": false,
98
+ "num_attention_heads": 24,
99
+ "num_hidden_layers": 64,
100
+ "num_key_value_heads": 4,
101
+ "output_gate_type": "swish",
102
+ "pad_token_id": null,
103
+ "partial_rotary_factor": 0.25,
104
+ "rms_norm_eps": 1e-06,
105
+ "rope_parameters": {
106
+ "mrope_interleaved": true,
107
+ "mrope_section": [
108
+ 11,
109
+ 11,
110
+ 10
111
+ ],
112
+ "partial_rotary_factor": 0.25,
113
+ "rope_theta": 10000000,
114
+ "rope_type": "default"
115
+ },
116
+ "tie_word_embeddings": false,
117
+ "use_cache": true,
118
+ "vocab_size": 248320
119
+ },
120
+ "tie_word_embeddings": false,
121
+ "transformers_version": "5.10.2",
122
+ "use_cache": false,
123
+ "video_token_id": 248057,
124
+ "vision_config": {
125
+ "deepstack_visual_indexes": [],
126
+ "depth": 27,
127
+ "dtype": "bfloat16",
128
+ "hidden_act": "gelu_pytorch_tanh",
129
+ "hidden_size": 1152,
130
+ "in_channels": 3,
131
+ "initializer_range": 0.02,
132
+ "intermediate_size": 4304,
133
+ "model_type": "qwen3_5_vision",
134
+ "num_heads": 16,
135
+ "num_position_embeddings": 2304,
136
+ "out_hidden_size": 5120,
137
+ "patch_size": 16,
138
+ "spatial_merge_size": 2,
139
+ "temporal_patch_size": 2
140
+ },
141
+ "vision_end_token_id": 248054,
142
+ "vision_start_token_id": 248053
143
+ }
clef_runtime.py ADDED
@@ -0,0 +1,496 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference components from Cloudflare/Clef at 0b331204bb13fbd2ca93a64df1956f5b55478ce5.
2
+ # Distributed under Apache-2.0; see LICENSE and NOTICE.
3
+
4
+ """Clef: a multimodal Qwen backbone with a joint schema head for typed decisions.
5
+
6
+ A record provides a ``state`` (any JSON value), optional ``images`` and ``videos``,
7
+ and ``questions``. Each question has a ``type`` (``noul``, ``choice``, or ``score``),
8
+ ``instructions``, and, for ``choice`` and ``score``, ``criteria`` describing the
9
+ allowed options. The model returns one logit per allowed option for every question.
10
+ ``systemone`` answers a Jev/SystemOne ``/v1/systemone`` request body with the same
11
+ response body.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import math
18
+ from dataclasses import dataclass
19
+ from dataclasses import field as dataclass_field
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ import torch
24
+ import torch.nn.functional as functional
25
+
26
+
27
+ SYSTEM_PROMPT = (
28
+ "Read the complete state and schema. Decide every field jointly. Each answer "
29
+ "must be exactly one of that field's allowed options."
30
+ )
31
+ IMAGE_PLACEHOLDER = "<|vision_start|><|image_pad|><|vision_end|>"
32
+ VIDEO_PLACEHOLDER = "<|vision_start|><|video_pad|><|vision_end|>"
33
+ MEDIA_BATCH_KEYS = ("pixel_values", "image_grid_thw", "pixel_values_videos", "video_grid_thw")
34
+ MEDIA_TOKEN_KEYS = ("mm_token_type_ids",)
35
+ QUESTION_TYPES = {"noul": 0, "choice": 1, "score": 2}
36
+
37
+
38
+ def render(value: Any) -> str:
39
+ if isinstance(value, str):
40
+ return value
41
+ return json.dumps(
42
+ value,
43
+ ensure_ascii=False,
44
+ separators=(",", ":"),
45
+ sort_keys=True,
46
+ )
47
+
48
+
49
+ def question_options(question: dict[str, Any]) -> list[tuple[str, Any]]:
50
+ question_type = str(question["type"])
51
+ if question_type == "noul":
52
+ criteria = {
53
+ "true": "The proposition is true or the answer is yes.",
54
+ "false": "The proposition is false or the answer is no.",
55
+ }
56
+ criteria.update(question.get("criteria") or {})
57
+ return [(key, criteria[key]) for key in ("true", "false")]
58
+ if question_type == "choice":
59
+ return sorted((str(key), value) for key, value in question["criteria"].items())
60
+ return [(str(index), value) for index, value in enumerate(question["criteria"])]
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class EncodedQuestion:
65
+ question_id: str
66
+ question_type: int
67
+ question_span: tuple[int, int]
68
+ option_spans: tuple[tuple[int, int], ...]
69
+ option_ids: tuple[str, ...]
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class EncodedRecord:
74
+ input_ids: tuple[int, ...]
75
+ questions: tuple[EncodedQuestion, ...]
76
+ record_id: str
77
+ media: dict[str, Any] | None = dataclass_field(default=None, compare=False, repr=False)
78
+
79
+
80
+ def _tokens(tokenizer: Any, text: str) -> list[int]:
81
+ return tokenizer(text, add_special_tokens=False).input_ids
82
+
83
+
84
+ def _encode_media(processor: Any, record: dict[str, Any]) -> tuple[list[int], dict[str, Any] | None]:
85
+ images = list(record.get("images") or [])
86
+ videos = list(record.get("videos") or [])
87
+ if not images and not videos:
88
+ return [], None
89
+ if processor is None:
90
+ raise ValueError("records with images or videos require a processor")
91
+ text = IMAGE_PLACEHOLDER * len(images) + VIDEO_PLACEHOLDER * len(videos) + "\n"
92
+ encoded = processor(
93
+ text=[text],
94
+ images=images or None,
95
+ videos=videos or None,
96
+ return_tensors="pt",
97
+ **(record.get("media_kwargs") or {}),
98
+ )
99
+ media = {key: encoded[key] for key in MEDIA_BATCH_KEYS if key in encoded}
100
+ for key in MEDIA_TOKEN_KEYS:
101
+ if key in encoded:
102
+ media[key] = encoded[key][0].tolist()
103
+ return encoded["input_ids"][0].tolist(), media
104
+
105
+
106
+ def encode_record(
107
+ tokenizer: Any,
108
+ record: dict[str, Any],
109
+ max_length: int = 16384,
110
+ max_state_tokens: int | None = None,
111
+ processor: Any | None = None,
112
+ ) -> EncodedRecord:
113
+ schema_ids = _tokens(tokenizer, "\n\nSCHEMA FIELDS:\n")
114
+ questions: list[EncodedQuestion] = []
115
+ for question_index, (question_id, question) in enumerate(record["questions"].items()):
116
+ schema_ids.extend(
117
+ _tokens(
118
+ tokenizer,
119
+ f"\nFIELD {question_index + 1}\nID: {question_id}\nTYPE: {question['type']}\nINSTRUCTION: ",
120
+ )
121
+ )
122
+ question_start = len(schema_ids)
123
+ instructions = question.get("instructions")
124
+ if instructions is None or instructions == "":
125
+ instructions = str(question_id)
126
+ schema_ids.extend(_tokens(tokenizer, render(instructions)))
127
+ question_end = len(schema_ids)
128
+ schema_ids.extend(_tokens(tokenizer, "\nALLOWED OPTIONS:\n"))
129
+
130
+ option_spans: list[tuple[int, int]] = []
131
+ option_ids: list[str] = []
132
+ for option_index, (option_id, description) in enumerate(question_options(question)):
133
+ schema_ids.extend(_tokens(tokenizer, f"OPTION {option_index + 1}: "))
134
+ option_start = len(schema_ids)
135
+ semantics = {"option_id": option_id}
136
+ if description is not None:
137
+ semantics["description"] = description
138
+ schema_ids.extend(_tokens(tokenizer, render(semantics)))
139
+ option_spans.append((option_start, len(schema_ids)))
140
+ option_ids.append(option_id)
141
+ schema_ids.extend(_tokens(tokenizer, "\n"))
142
+ schema_ids.extend(_tokens(tokenizer, "END FIELD\n"))
143
+ questions.append(
144
+ EncodedQuestion(
145
+ question_id=str(question_id),
146
+ question_type=QUESTION_TYPES[str(question["type"])],
147
+ question_span=(question_start, question_end),
148
+ option_spans=tuple(option_spans),
149
+ option_ids=tuple(option_ids),
150
+ )
151
+ )
152
+
153
+ prefix_ids = _tokens(
154
+ tokenizer,
155
+ f"<|im_start|>system\n{SYSTEM_PROMPT}<|im_end|>\n<|im_start|>user\nSTATE:\n",
156
+ )
157
+ suffix_ids = _tokens(
158
+ tokenizer,
159
+ "\n<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\nJOINT SCHEMA DECISIONS:",
160
+ )
161
+ media_ids, media = _encode_media(processor, record)
162
+ if media is not None:
163
+ media["token_offset"] = len(prefix_ids)
164
+ prefix_ids = prefix_ids + media_ids
165
+ state_ids = _tokens(tokenizer, render(record["state"]))
166
+ if max_state_tokens is not None:
167
+ state_ids = state_ids[:max_state_tokens]
168
+ fixed_length = len(prefix_ids) + len(schema_ids) + len(suffix_ids)
169
+ if fixed_length > max_length:
170
+ raise ValueError(
171
+ f"schema requires {fixed_length} tokens before state; maximum is {max_length}"
172
+ )
173
+ state_ids = state_ids[: max_length - fixed_length]
174
+ schema_offset = len(prefix_ids) + len(state_ids)
175
+ shifted_questions = tuple(
176
+ EncodedQuestion(
177
+ question_id=question.question_id,
178
+ question_type=question.question_type,
179
+ question_span=(
180
+ question.question_span[0] + schema_offset,
181
+ question.question_span[1] + schema_offset,
182
+ ),
183
+ option_spans=tuple(
184
+ (start + schema_offset, end + schema_offset)
185
+ for start, end in question.option_spans
186
+ ),
187
+ option_ids=question.option_ids,
188
+ )
189
+ for question in questions
190
+ )
191
+ input_ids = tuple(prefix_ids + state_ids + schema_ids + suffix_ids)
192
+ if not input_ids or not shifted_questions:
193
+ raise ValueError("record produced no model input or questions")
194
+ return EncodedRecord(
195
+ input_ids=input_ids,
196
+ questions=shifted_questions,
197
+ record_id=str(record.get("id", "unknown")),
198
+ media=media,
199
+ )
200
+
201
+
202
+ def collate_records(
203
+ records: list[EncodedRecord],
204
+ pad_token_id: int,
205
+ device: torch.device,
206
+ ) -> dict[str, Any]:
207
+ maximum_length = max(len(record.input_ids) for record in records)
208
+ input_ids = torch.full(
209
+ (len(records), maximum_length),
210
+ pad_token_id,
211
+ dtype=torch.long,
212
+ device=device,
213
+ )
214
+ attention_mask = torch.zeros(
215
+ (len(records), maximum_length),
216
+ dtype=torch.long,
217
+ device=device,
218
+ )
219
+ for index, record in enumerate(records):
220
+ length = len(record.input_ids)
221
+ input_ids[index, :length] = torch.tensor(record.input_ids, device=device)
222
+ attention_mask[index, :length] = 1
223
+ media: dict[str, torch.Tensor] = {}
224
+ for key in MEDIA_BATCH_KEYS:
225
+ values = [record.media[key] for record in records if record.media and key in record.media]
226
+ if values:
227
+ media[key] = torch.cat(values, dim=0).to(device)
228
+ for key in MEDIA_TOKEN_KEYS:
229
+ if any(record.media and key in record.media for record in records):
230
+ token_values = torch.zeros((len(records), maximum_length), dtype=torch.long, device=device)
231
+ for index, record in enumerate(records):
232
+ if record.media and key in record.media:
233
+ offset = record.media["token_offset"]
234
+ values = torch.tensor(record.media[key], dtype=torch.long, device=device)
235
+ token_values[index, offset : offset + len(values)] = values
236
+ media[key] = token_values
237
+ return {
238
+ "input_ids": input_ids,
239
+ "attention_mask": attention_mask,
240
+ "records": records,
241
+ "media": media,
242
+ }
243
+
244
+
245
+ class EvidenceRoutingLayer(torch.nn.Module):
246
+ def __init__(
247
+ self,
248
+ width: int,
249
+ heads: int,
250
+ feedforward: int,
251
+ dropout: float = 0.0,
252
+ ) -> None:
253
+ super().__init__()
254
+ self.query_norm = torch.nn.LayerNorm(width)
255
+ self.memory_norm = torch.nn.LayerNorm(width)
256
+ self.attention = torch.nn.MultiheadAttention(
257
+ width,
258
+ heads,
259
+ dropout=dropout,
260
+ batch_first=True,
261
+ )
262
+ self.attention_dropout = torch.nn.Dropout(dropout)
263
+ self.feedforward_norm = torch.nn.LayerNorm(width)
264
+ self.feedforward = torch.nn.Sequential(
265
+ torch.nn.Linear(width, feedforward),
266
+ torch.nn.GELU(),
267
+ torch.nn.Dropout(dropout),
268
+ torch.nn.Linear(feedforward, width),
269
+ torch.nn.Dropout(dropout),
270
+ )
271
+
272
+ def forward(self, queries: torch.Tensor, memory: torch.Tensor) -> torch.Tensor:
273
+ normalized_queries = self.query_norm(queries)
274
+ routed, _ = self.attention(
275
+ normalized_queries,
276
+ self.memory_norm(memory),
277
+ self.memory_norm(memory),
278
+ need_weights=False,
279
+ )
280
+ queries = queries + self.attention_dropout(routed)
281
+ return queries + self.feedforward(self.feedforward_norm(queries))
282
+
283
+
284
+ class JointSchemaHead(torch.nn.Module):
285
+ def __init__(
286
+ self,
287
+ hidden_size: int,
288
+ width: int,
289
+ routing_layers: int,
290
+ layers: int,
291
+ heads: int,
292
+ feedforward: int,
293
+ dropout: float = 0.0,
294
+ ) -> None:
295
+ super().__init__()
296
+ self.hidden_norm = torch.nn.LayerNorm(hidden_size)
297
+ self.memory_projection = torch.nn.Linear(hidden_size, width, bias=False)
298
+ self.question_projection = torch.nn.Linear(hidden_size, width, bias=False)
299
+ self.option_question_projection = torch.nn.Linear(hidden_size, width, bias=False)
300
+ self.global_projection = torch.nn.Linear(hidden_size, width, bias=False)
301
+ self.option_context_projection = torch.nn.Linear(hidden_size, width, bias=False)
302
+ self.option_lexical_projection = torch.nn.Linear(hidden_size, width, bias=False)
303
+ self.type_embedding = torch.nn.Embedding(3, width)
304
+ self.evidence_layers = torch.nn.ModuleList(
305
+ [
306
+ EvidenceRoutingLayer(
307
+ width=width,
308
+ heads=heads,
309
+ feedforward=feedforward,
310
+ dropout=dropout,
311
+ )
312
+ for _ in range(routing_layers)
313
+ ]
314
+ )
315
+ self.option_summary_norm = torch.nn.LayerNorm(width)
316
+ self.layers = torch.nn.ModuleList(
317
+ [
318
+ torch.nn.TransformerDecoderLayer(
319
+ d_model=width,
320
+ nhead=heads,
321
+ dim_feedforward=feedforward,
322
+ dropout=dropout,
323
+ activation="gelu",
324
+ batch_first=True,
325
+ norm_first=True,
326
+ )
327
+ for _ in range(layers)
328
+ ]
329
+ )
330
+ self.field_norm = torch.nn.LayerNorm(width)
331
+ self.option_norm = torch.nn.LayerNorm(width)
332
+ self.residual_scorer = torch.nn.Sequential(
333
+ torch.nn.Linear(width * 4, width),
334
+ torch.nn.GELU(),
335
+ torch.nn.Dropout(dropout),
336
+ torch.nn.Linear(width, 1),
337
+ )
338
+ self.prior_logit_scale = torch.nn.Parameter(torch.zeros(()))
339
+ self.joint_logit_scale = torch.nn.Parameter(torch.zeros(()))
340
+ self.residual_gate = torch.nn.Parameter(torch.zeros(()))
341
+
342
+ @staticmethod
343
+ def _mean_span(values: torch.Tensor, span: tuple[int, int]) -> torch.Tensor:
344
+ start, end = span
345
+ return values[start:end].mean(dim=0)
346
+
347
+ def forward(
348
+ self,
349
+ hidden_states: torch.Tensor,
350
+ input_ids: torch.Tensor,
351
+ attention_mask: torch.Tensor,
352
+ records: list[EncodedRecord],
353
+ output_embedding_weight: torch.Tensor,
354
+ ) -> list[list[torch.Tensor]]:
355
+ results: list[list[torch.Tensor]] = []
356
+ normalized_hidden = self.hidden_norm(hidden_states)
357
+ for batch_index, record in enumerate(records):
358
+ sequence_length = int(attention_mask[batch_index].sum().item())
359
+ sequence_hidden = normalized_hidden[batch_index, :sequence_length]
360
+ memory = self.memory_projection(sequence_hidden).unsqueeze(0)
361
+ global_vector = sequence_hidden[-1]
362
+ question_vectors = torch.stack(
363
+ [
364
+ self._mean_span(sequence_hidden, question.question_span)
365
+ for question in record.questions
366
+ ]
367
+ )
368
+ type_ids = torch.tensor(
369
+ [question.question_type for question in record.questions],
370
+ device=hidden_states.device,
371
+ )
372
+ option_contexts: list[torch.Tensor] = []
373
+ lexical_options: list[torch.Tensor] = []
374
+ option_counts = []
375
+ for question in record.questions:
376
+ context_vectors = torch.stack(
377
+ [
378
+ self._mean_span(sequence_hidden, span)
379
+ for span in question.option_spans
380
+ ]
381
+ )
382
+ lexical_vectors = []
383
+ for start, end in question.option_spans:
384
+ token_ids = input_ids[batch_index, start:end]
385
+ lexical_vectors.append(output_embedding_weight[token_ids].mean(dim=0))
386
+ lexical = torch.stack(lexical_vectors)
387
+ option_contexts.append(context_vectors)
388
+ lexical_options.append(lexical)
389
+ option_counts.append(len(question.option_spans))
390
+
391
+ option_queries = []
392
+ for question_index, (context_vectors, lexical) in enumerate(
393
+ zip(option_contexts, lexical_options)
394
+ ):
395
+ option_queries.append(
396
+ self.option_context_projection(context_vectors)
397
+ + self.option_lexical_projection(lexical)
398
+ + self.option_question_projection(
399
+ question_vectors[question_index]
400
+ ).unsqueeze(0)
401
+ )
402
+ routed_options = torch.cat(option_queries, dim=0).unsqueeze(0)
403
+ for layer in self.evidence_layers:
404
+ routed_options = layer(routed_options, memory)
405
+ routed_options = routed_options[0]
406
+ split_options = list(torch.split(routed_options, option_counts, dim=0))
407
+
408
+ base_fields = self.question_projection(question_vectors)
409
+ option_summaries = []
410
+ for field, options in zip(base_fields, split_options):
411
+ routing_weights = torch.softmax(
412
+ torch.matmul(options, field) / math.sqrt(options.shape[-1]),
413
+ dim=0,
414
+ )
415
+ option_summaries.append(
416
+ torch.sum(routing_weights.unsqueeze(-1) * options, dim=0)
417
+ )
418
+ fields = (
419
+ base_fields
420
+ + self.option_summary_norm(torch.stack(option_summaries))
421
+ + self.global_projection(global_vector).unsqueeze(0)
422
+ + self.type_embedding(type_ids)
423
+ )
424
+ fields = fields.unsqueeze(0)
425
+ for layer in self.layers:
426
+ fields = layer(fields, memory)
427
+ fields = self.field_norm(fields[0])
428
+
429
+ record_logits: list[torch.Tensor] = []
430
+ for field, question, lexical, routed in zip(
431
+ fields,
432
+ record.questions,
433
+ lexical_options,
434
+ split_options,
435
+ ):
436
+ anchor = functional.normalize(
437
+ question_vectors[len(record_logits)] + global_vector,
438
+ dim=-1,
439
+ )
440
+ lexical_anchor = functional.normalize(lexical, dim=-1)
441
+ prior_scale = self.prior_logit_scale.clamp(max=math.log(100.0)).exp()
442
+ prior = prior_scale * torch.matmul(lexical_anchor, anchor)
443
+ options = self.option_norm(routed)
444
+ repeated_field = field.unsqueeze(0).expand_as(options)
445
+ cosine = functional.cosine_similarity(repeated_field, options, dim=-1)
446
+ features = torch.cat(
447
+ [
448
+ repeated_field,
449
+ options,
450
+ repeated_field * options,
451
+ torch.abs(repeated_field - options),
452
+ ],
453
+ dim=-1,
454
+ )
455
+ residual = self.residual_scorer(features).squeeze(-1)
456
+ joint_scale = self.joint_logit_scale.clamp(max=math.log(100.0)).exp()
457
+ joint = joint_scale * cosine + residual
458
+ record_logits.append(
459
+ prior + torch.sigmoid(self.residual_gate) * joint
460
+ )
461
+ results.append(record_logits)
462
+ return results
463
+
464
+
465
+ class ClefModel(torch.nn.Module):
466
+ def __init__(self, language_model: Any, head: JointSchemaHead) -> None:
467
+ super().__init__()
468
+ self.language_model = language_model
469
+ self.head = head
470
+
471
+ def forward(self, batch: dict[str, Any]) -> list[list[torch.Tensor]]:
472
+ base_model = (
473
+ self.language_model.get_base_model()
474
+ if hasattr(self.language_model, "get_base_model")
475
+ else self.language_model
476
+ )
477
+ media = batch.get("media") or {}
478
+ text_model = base_model.model
479
+ if not media and hasattr(text_model, "language_model"):
480
+ text_model = text_model.language_model
481
+ outputs = text_model(
482
+ input_ids=batch["input_ids"],
483
+ attention_mask=batch["attention_mask"],
484
+ use_cache=False,
485
+ return_dict=True,
486
+ **media,
487
+ )
488
+ return self.head(
489
+ outputs.last_hidden_state,
490
+ batch["input_ids"],
491
+ batch["attention_mask"],
492
+ batch["records"],
493
+ base_model.get_output_embeddings().weight,
494
+ )
495
+
496
+
config.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "adapter_merged": true,
3
+ "architectures": [
4
+ "SourceHatRLCD"
5
+ ],
6
+ "artifact_kind": "merged_typed_decision_model",
7
+ "backbone_config": "backbone_config.json",
8
+ "backbone_dtype": "bfloat16",
9
+ "base_model_name_or_path": "Cloudflare/clef",
10
+ "decision_contract_version": "typed-decision-v1",
11
+ "head_dtype": "float32",
12
+ "inference_entrypoint": "inference.py",
13
+ "maximum_categorical_candidates": 16,
14
+ "maximum_compiled_tokens": 2048,
15
+ "maximum_fields": 4,
16
+ "maximum_ordinal_levels": 14,
17
+ "merged_text_matrices": 496,
18
+ "model_name": "SourceHat RLCD",
19
+ "model_type": "sourcehat_rlcd",
20
+ "revision": "0b331204bb13fbd2ca93a64df1956f5b55478ce5",
21
+ "runtime_adapter_branches": 0,
22
+ "standalone_loader_required": true,
23
+ "tokenizer_revision": "0b331204bb13fbd2ca93a64df1956f5b55478ce5",
24
+ "weights": "model.safetensors"
25
+ }
decision_contract.json ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "action_policy": "fieldwise proposal only; no commit/set/abstain policy or external action is applied",
3
+ "expected_scores": "ordinal expected zero-based rank; retains caller-specified order",
4
+ "field": {
5
+ "field_type": {
6
+ "boolean": "noul: exactly two candidates, true first and false second",
7
+ "enum": "choice: 2-16 unordered described candidates",
8
+ "ordinal": "score: 2-14 candidates in ascending order"
9
+ },
10
+ "required": [
11
+ "id",
12
+ "field_type",
13
+ "description",
14
+ "candidates"
15
+ ]
16
+ },
17
+ "limits": {
18
+ "aggregate_text_characters": 32768,
19
+ "compiled_tokens": 2048,
20
+ "evidence_items": 32,
21
+ "request_bytes": 1048576
22
+ },
23
+ "ordering": "categorical candidates and fields canonicalized by semantics; binary and ordinal candidate positions preserved; caller IDs never encoded",
24
+ "probabilities": {
25
+ "p_action_success": null,
26
+ "p_field_correct": "raw probability assigned to the selected supplied candidate, not a calibrated guarantee",
27
+ "p_object_correct": null,
28
+ "p_recoverable": null,
29
+ "p_safe": null,
30
+ "p_workflow_success": null
31
+ },
32
+ "request": {
33
+ "required": [
34
+ "state",
35
+ "schema"
36
+ ],
37
+ "schema": {
38
+ "constraints": "optional text instructions",
39
+ "dependencies": "optional source_field/target_field/description objects",
40
+ "fields": "1-4 required typed fields",
41
+ "version": "typed-decision-v1"
42
+ },
43
+ "state": {
44
+ "context": "text",
45
+ "evidence": "optional list of text"
46
+ }
47
+ },
48
+ "version": "typed-decision-v1"
49
+ }
evaluation/rlcd_evaluation_data.json ADDED
The diff for this file is too large to render. See raw diff
 
example_request.json ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": {
3
+ "fields": [
4
+ {
5
+ "candidates": [
6
+ {
7
+ "description": "Billing team",
8
+ "id": "billing"
9
+ },
10
+ {
11
+ "description": "Technical team",
12
+ "id": "technical"
13
+ }
14
+ ],
15
+ "description": "Route invoice-charge issues to Billing; route service failures to Technical.",
16
+ "field_type": "enum",
17
+ "id": "queue"
18
+ },
19
+ {
20
+ "candidates": [
21
+ {
22
+ "description": "Customer verification is complete",
23
+ "id": "yes"
24
+ },
25
+ {
26
+ "description": "Customer verification is not complete",
27
+ "id": "no"
28
+ }
29
+ ],
30
+ "description": "Is customer verification complete? Use the explicit evidence.",
31
+ "field_type": "boolean",
32
+ "id": "verified"
33
+ },
34
+ {
35
+ "candidates": [
36
+ {
37
+ "description": "Low severity: billing issue and normal service",
38
+ "id": "low"
39
+ },
40
+ {
41
+ "description": "Medium severity: degraded service",
42
+ "id": "medium"
43
+ },
44
+ {
45
+ "description": "High severity: unavailable service",
46
+ "id": "high"
47
+ }
48
+ ],
49
+ "description": "Choose severity in the supplied order: low for a billing-only issue with normal service; medium for degraded service; high for unavailable service.",
50
+ "field_type": "ordinal",
51
+ "id": "severity"
52
+ }
53
+ ],
54
+ "version": "typed-decision-v1"
55
+ },
56
+ "state": {
57
+ "context": "A verified customer reports a duplicate invoice charge. Service is operating normally.",
58
+ "evidence": [
59
+ "Duplicate invoice charge confirmed.",
60
+ "Customer verification completed."
61
+ ]
62
+ }
63
+ }
inference.py ADDED
@@ -0,0 +1,424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Standalone dense-merged RLCD inference. No adapters or private imports."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ from dataclasses import dataclass
8
+ import hashlib
9
+ import importlib.util
10
+ import json
11
+ import math
12
+ import os
13
+ from pathlib import Path
14
+ import re
15
+ import sys
16
+ from typing import Any
17
+
18
+ BASE_MODEL = "Cloudflare/clef"
19
+ BASE_REVISION = "0b331204bb13fbd2ca93a64df1956f5b55478ce5"
20
+ SCHEMA_VERSION = "typed-decision-v1"
21
+ MAX_LENGTH = 2048
22
+ MAX_FIELDS = 4
23
+ MAX_CANDIDATES = 16
24
+ MAX_REQUEST_BYTES = 1_048_576
25
+ MAX_TOTAL_TEXT = 32768
26
+ TYPE_NAMES = {"enum": "choice", "boolean": "noul", "ordinal": "score"}
27
+
28
+
29
+ def sha256_file(path: Path) -> str:
30
+ digest = hashlib.sha256()
31
+ with path.open("rb") as handle:
32
+ for block in iter(lambda: handle.read(1024 * 1024), b""):
33
+ digest.update(block)
34
+ return digest.hexdigest()
35
+
36
+
37
+ def _pairs(pairs):
38
+ value = {}
39
+ for key, item in pairs:
40
+ if key in value:
41
+ raise ValueError("duplicate JSON object key")
42
+ value[key] = item
43
+ return value
44
+
45
+
46
+ def read_json(path: Path, *, limit=MAX_REQUEST_BYTES):
47
+ if path.is_symlink() or not path.is_file() or path.stat().st_size > limit:
48
+ raise ValueError("expected a regular JSON file within the documented size limit")
49
+ return json.loads(path.read_text(), object_pairs_hook=_pairs,
50
+ parse_constant=lambda _: (_ for _ in ()).throw(ValueError("nonfinite JSON number")))
51
+
52
+
53
+ def _keys(value, required, optional=()):
54
+ if not isinstance(value, dict) or not set(required) <= value.keys() or set(value) - set(required) - set(optional):
55
+ raise ValueError("object keys do not match the decision contract")
56
+
57
+
58
+ def _text(value, *, maximum=16384, empty=False):
59
+ if (not isinstance(value, str) or len(value) > maximum or (not empty and not value.strip())
60
+ or re.search(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]", value)
61
+ or re.search(r"<\|[^\n]*?\|>", value)):
62
+ raise ValueError("invalid text, control character, or model special token")
63
+ return value
64
+
65
+
66
+ @dataclass
67
+ class PreparedRequest:
68
+ native: dict[str, Any]
69
+ fields: list[dict[str, Any]]
70
+ candidate_ids: dict[str, list[str]]
71
+ canonical_fields: dict[str, str]
72
+
73
+
74
+ def prepare_request(request: dict[str, Any]) -> PreparedRequest:
75
+ _keys(request, ("state", "schema"))
76
+ state, schema = request["state"], request["schema"]
77
+ _keys(state, ("context",), ("evidence",))
78
+ context = _text(state["context"], empty=True)
79
+ evidence = state.get("evidence", [])
80
+ if not isinstance(evidence, list) or len(evidence) > 32:
81
+ raise ValueError("evidence must contain at most 32 text items")
82
+ evidence = [_text(item, maximum=4096) for item in evidence]
83
+ _keys(schema, ("version", "fields"), ("dependencies", "constraints"))
84
+ if schema["version"] != SCHEMA_VERSION:
85
+ raise ValueError("unsupported schema version")
86
+ fields = schema["fields"]
87
+ if not isinstance(fields, list) or not 1 <= len(fields) <= MAX_FIELDS:
88
+ raise ValueError("supply one to four fields")
89
+ descriptions, identifiers, checked = set(), set(), []
90
+ text_size = len(context) + sum(map(len, evidence))
91
+ for field in fields:
92
+ _keys(field, ("id", "field_type", "description", "candidates"), ("required",))
93
+ fid = _text(field["id"], maximum=128)
94
+ kind = field["field_type"]
95
+ description = _text(field["description"])
96
+ if fid in identifiers or kind not in TYPE_NAMES or (description, kind) in descriptions:
97
+ raise ValueError("field IDs and semantic descriptions must be distinct; field type is invalid")
98
+ if field.get("required", True) is not True:
99
+ raise ValueError("all released fields are required")
100
+ identifiers.add(fid)
101
+ descriptions.add((description, kind))
102
+ candidates = field["candidates"]
103
+ limit = 14 if kind == "ordinal" else MAX_CANDIDATES
104
+ if not isinstance(candidates, list) or not 2 <= len(candidates) <= limit or kind == "boolean" and len(candidates) != 2:
105
+ raise ValueError("candidate count is outside the released envelope")
106
+ ids, meanings, values = set(), set(), []
107
+ for candidate in candidates:
108
+ _keys(candidate, ("id", "description"))
109
+ cid = _text(candidate["id"], maximum=128)
110
+ meaning = _text(candidate["description"], maximum=2048)
111
+ if cid in ids or meaning in meanings:
112
+ raise ValueError("candidate IDs and descriptions must be distinct within a field")
113
+ ids.add(cid)
114
+ meanings.add(meaning)
115
+ values.append({"id": cid, "description": meaning})
116
+ text_size += len(meaning)
117
+ text_size += len(description)
118
+ checked.append({"id": fid, "field_type": kind, "description": description, "candidates": values})
119
+ dependencies = schema.get("dependencies", [])
120
+ constraints = schema.get("constraints", [])
121
+ if not isinstance(dependencies, list) or len(dependencies) > 16 or not isinstance(constraints, list) or len(constraints) > 16:
122
+ raise ValueError("too many dependencies or constraints")
123
+ dependencies = [dict(item) if isinstance(item, dict) else item for item in dependencies]
124
+ for dependency in dependencies:
125
+ _keys(dependency, ("source_field", "target_field", "description"))
126
+ if dependency["source_field"] not in identifiers or dependency["target_field"] not in identifiers:
127
+ raise ValueError("dependency refers to an unknown field")
128
+ text_size += len(_text(dependency["description"], maximum=4096))
129
+ constraints = [_text(item, maximum=4096) for item in constraints]
130
+ text_size += sum(map(len, constraints))
131
+ if text_size > MAX_TOTAL_TEXT:
132
+ raise ValueError("aggregate request text exceeds 32768 characters")
133
+ checked.sort(key=lambda field: (field["description"], field["field_type"]))
134
+ field_ids = {field["id"]: f"f{i:03d}" for i, field in enumerate(checked)}
135
+ dependencies.sort(key=lambda item: (field_ids[item["source_field"]], field_ids[item["target_field"]], item["description"]))
136
+ native_questions, candidate_ids = {}, {}
137
+ for field in checked:
138
+ fid, kind = field["id"], field["field_type"]
139
+ candidates = sorted(field["candidates"], key=lambda c: c["description"]) if kind == "enum" else field["candidates"]
140
+ candidate_ids[fid] = [candidate["id"] for candidate in candidates]
141
+ criteria: Any = {f"c{i:03d}": candidate["description"] for i, candidate in enumerate(candidates)}
142
+ if kind == "ordinal":
143
+ criteria = [candidate["description"] for candidate in candidates]
144
+ elif kind == "boolean":
145
+ criteria = dict(zip(("true", "false"), (candidate["description"] for candidate in candidates)))
146
+ instructions = field["description"]
147
+ related = [item["description"] for item in dependencies if fid in (item["source_field"], item["target_field"])]
148
+ if related:
149
+ instructions += " Dependencies: " + " ".join(related)
150
+ if constraints:
151
+ instructions += " Constraints: " + " ".join(constraints)
152
+ native_questions[field_ids[fid]] = {"type": TYPE_NAMES[kind], "instructions": instructions, "criteria": criteria}
153
+ return PreparedRequest({"state": {"context": context, "evidence": evidence}, "questions": native_questions},
154
+ checked, candidate_ids, field_ids)
155
+
156
+
157
+ def compile_request(runtime, tokenizer, prepared: PreparedRequest):
158
+ encoded = runtime.encode_record(tokenizer, prepared.native, max_length=10_000_000)
159
+ if len(encoded.input_ids) > MAX_LENGTH:
160
+ raise ValueError(f"compiled input contains {len(encoded.input_ids)} tokens; limit is {MAX_LENGTH}; truncation is forbidden")
161
+ if encoded.media is not None:
162
+ raise ValueError("the released interface is text-only")
163
+ return encoded
164
+
165
+
166
+ def verify_bundle(bundle: Path, *, strict=False):
167
+ bundle = bundle.resolve(strict=True)
168
+ manifest = read_json(bundle / "release_manifest.json", limit=4 * MAX_REQUEST_BYTES)
169
+ if (manifest.get("format") != "sourcehat-rlcd-release-v1" or manifest.get("base_model") != BASE_MODEL
170
+ or manifest.get("base_revision") != BASE_REVISION):
171
+ raise ValueError("release manifest does not match this loader")
172
+ files = manifest.get("files", {})
173
+ if not files or len(files) > 40:
174
+ raise ValueError("invalid release file inventory")
175
+ actual = {str(path.relative_to(bundle)) for path in bundle.rglob("*") if path.is_file()}
176
+ if strict and actual != set(files) | {"release_manifest.json"}:
177
+ raise ValueError("release has missing or unexpected files")
178
+ for name, entry in files.items():
179
+ relative = Path(name)
180
+ if relative.is_absolute() or ".." in relative.parts:
181
+ raise ValueError("invalid manifest file path")
182
+ path = bundle / relative
183
+ if (any((bundle / Path(*relative.parts[:i])).is_symlink() for i in range(1, len(relative.parts) + 1))
184
+ or not path.is_file() or path.stat().st_size != entry["bytes"] or sha256_file(path) != entry["sha256"]):
185
+ raise ValueError("release file hash or regular-file check failed")
186
+ return manifest
187
+
188
+
189
+ def _runtime(bundle):
190
+ path = bundle / "clef_runtime.py"
191
+ name = "sourcehat_rlcd_runtime_" + sha256_file(path)[:16]
192
+ if name not in sys.modules:
193
+ spec = importlib.util.spec_from_file_location(name, path)
194
+ module = importlib.util.module_from_spec(spec)
195
+ sys.modules[name] = module
196
+ spec.loader.exec_module(module)
197
+ return sys.modules[name]
198
+
199
+
200
+ class DecisionModel:
201
+ def __init__(self, bundle=None, *, base_model_path=None, local_files_only=False, device="cuda:0"):
202
+ sys.dont_write_bytecode = True
203
+ self.bundle = Path(bundle or Path(__file__).resolve().parent).resolve(strict=True)
204
+ self.manifest = verify_bundle(self.bundle)
205
+ self.int8 = self.manifest.get("artifact_kind") == "int8_typed_decision_model"
206
+ config = read_json(self.bundle / "config.json")
207
+ if (self.manifest.get("artifact_kind") not in {"merged_typed_decision_model", "int8_typed_decision_model"}
208
+ or config.get("adapter_merged") is not True or self.manifest.get("base_files")
209
+ or any(k in config for k in ("text_adaptation", "adaptation_dtype", "adapter_dtype"))):
210
+ raise ValueError("this loader requires a fully dense-merged, self-contained model")
211
+ if base_model_path is not None:
212
+ raise ValueError("do not supply a separate base model")
213
+ self.merged = True
214
+ self.base_path = self.bundle
215
+ self.device = device
216
+ self.local_files_only = local_files_only
217
+ self.model = None
218
+ self.runtime = _runtime(self.bundle)
219
+ from transformers import AutoTokenizer
220
+ self.tokenizer = AutoTokenizer.from_pretrained(self.base_path, local_files_only=True, trust_remote_code=False)
221
+
222
+ def compile(self, request):
223
+ prepared = prepare_request(request)
224
+ return prepared, compile_request(self.runtime, self.tokenizer, prepared)
225
+
226
+ def load(self):
227
+ if self.model is not None:
228
+ return
229
+ import torch
230
+ from transformers import Qwen3_5Config, Qwen3_5ForConditionalGeneration
231
+ visible = os.environ.get("CUDA_VISIBLE_DEVICES", "")
232
+ if not visible or len(visible.split(",")) != 1 or self.device != "cuda:0" or torch.cuda.device_count() != 1:
233
+ raise ValueError("select exactly one physical GPU using CUDA_VISIBLE_DEVICES and use cuda:0")
234
+ int8 = getattr(self, "int8", False)
235
+ total_memory = torch.cuda.get_device_properties(0).total_memory
236
+ minimum_gib = 32 if int8 else 60
237
+ if total_memory < minimum_gib * 2**30:
238
+ raise ValueError(f"this runtime requires a GPU with at least {minimum_gib} GiB VRAM; see measured requirements in README")
239
+ memory_ceiling = min(total_memory - 2 * 2**30, 40 * 2**30) if int8 else 60 * 2**30
240
+ torch.cuda.set_per_process_memory_fraction(memory_ceiling / total_memory, 0)
241
+ torch.set_num_threads(4)
242
+ config = read_json(self.bundle / "joint_head_config.json")
243
+ expected_config = {"hidden_size": 5120, "width": 1024, "routing_layers": 2,
244
+ "layers": 4, "heads": 16, "feedforward": 4096}
245
+ if config != expected_config:
246
+ raise ValueError("joint-head architecture differs from this release")
247
+ class SelectedFloatRows:
248
+ def __init__(self, values):
249
+ self.values = values
250
+ def __getitem__(self, indices):
251
+ return self.values[indices].float()
252
+
253
+ class FloatBoundary(torch.nn.Module):
254
+ def __init__(self, inner):
255
+ super().__init__()
256
+ self.inner = inner
257
+ def forward(self, hidden, ids, mask, records, output_weights):
258
+ return self.inner(hidden.float(), ids, mask, records, SelectedFloatRows(output_weights))
259
+
260
+ if self.merged:
261
+ from accelerate import init_empty_weights, load_checkpoint_and_dispatch
262
+ backbone_config = Qwen3_5Config.from_dict(read_json(self.bundle / "backbone_config.json"))
263
+ backbone_config.use_cache = False
264
+ backbone_config._attn_implementation = "sdpa"
265
+ with init_empty_weights():
266
+ backbone = Qwen3_5ForConditionalGeneration(backbone_config)
267
+ # RoPE buffers are initialized in FP32 and must not be rounded by a blanket model.to(dtype).
268
+ for parameter in backbone.parameters():
269
+ parameter.data = parameter.data.to(dtype=torch.bfloat16)
270
+ if int8:
271
+ install_int8_layers(backbone, self.bundle)
272
+ head = self.runtime.JointSchemaHead(**config).float()
273
+ model = self.runtime.ClefModel(backbone, FloatBoundary(head))
274
+ if int8:
275
+ from safetensors import safe_open
276
+ quantization = read_json(self.bundle / "quantization_config.json")
277
+ expected_keys = set(model.state_dict()) | {name + ".SCB" for name in quantization["modules"]}
278
+ with safe_open(self.bundle / "model.safetensors", framework="pt", device="cpu") as weights:
279
+ if set(weights.keys()) != expected_keys:
280
+ raise ValueError("INT8 checkpoint inventory differs from the complete model architecture")
281
+ if int8:
282
+ self.model = load_int8_checkpoint(model, self.bundle, self.device).eval()
283
+ else:
284
+ self.model = load_checkpoint_and_dispatch(model, str(self.bundle / "model.safetensors"),
285
+ device_map={"": 0}, strict=True).eval()
286
+ if int8:
287
+ for name in quantization["modules"]:
288
+ layer = self.model.get_submodule(name)
289
+ if layer.weight.dtype != torch.int8 or layer.weight.SCB is None or not torch.isfinite(layer.weight.SCB).all():
290
+ raise ValueError("an INT8 weight or row scale was not restored correctly")
291
+ if any(buffer.dtype != torch.float32 for name, buffer in backbone.named_buffers() if name.endswith("inv_freq")):
292
+ raise ValueError("positional-frequency buffers must retain their original FP32 precision")
293
+ if any("lora_" in name or ".base_layer." in name for name, _ in self.model.named_parameters()):
294
+ raise ValueError("a dense model must not construct runtime adapter branches")
295
+ for parameter in self.model.parameters():
296
+ parameter.requires_grad_(False)
297
+
298
+ def predict_logits(self, request):
299
+ prepared, encoded = self.compile(request)
300
+ self.load()
301
+ import torch
302
+ batch = self.runtime.collate_records([encoded], self.tokenizer.pad_token_id, torch.device(self.device))
303
+ with torch.no_grad():
304
+ logits = [value.detach().float().cpu() for value in self.model(batch)[0]]
305
+ if len(logits) != len(prepared.fields) or any(not torch.isfinite(value).all() for value in logits):
306
+ raise ValueError("invalid model output")
307
+ return prepared, encoded, logits
308
+
309
+ def predict(self, request, *, include_logits=False):
310
+ prepared, encoded, logits = self.predict_logits(request)
311
+ return format_response(prepared, encoded, logits, include_logits=include_logits)
312
+
313
+
314
+ def install_int8_layers(backbone, bundle):
315
+ import torch
316
+ import bitsandbytes as bnb
317
+ quantization = read_json(bundle / "quantization_config.json")
318
+ if (quantization.get("format") != "sourcehat-rlcd-bnb-int8-dense-v1"
319
+ or quantization.get("bitsandbytes_version") != "0.50.2"
320
+ or quantization.get("threshold") != 6.0
321
+ or quantization.get("has_fp16_weights") is not False):
322
+ raise ValueError("unsupported INT8 quantization configuration")
323
+ names = quantization.get("modules", [])
324
+ expected = {"language_model." + name for name, layer in backbone.named_modules()
325
+ if isinstance(layer, torch.nn.Linear) and re.fullmatch(
326
+ r"model\.language_model\.layers\.\d+\.(?:linear_attn|self_attn|mlp)\.[a-z0-9_]+", name)}
327
+ if len(names) != 496 or len(set(names)) != 496 or set(names) != expected:
328
+ raise ValueError("quantization must cover exactly the 496 merged text linear layers")
329
+ for name in names:
330
+ relative = name.removeprefix("language_model.")
331
+ original = backbone.get_submodule(relative)
332
+ if not isinstance(original, torch.nn.Linear):
333
+ raise ValueError("INT8 target is not a text linear layer")
334
+ parent_name, leaf = relative.rsplit(".", 1)
335
+ layer = bnb.nn.Linear8bitLt(original.in_features, original.out_features,
336
+ bias=original.bias is not None, has_fp16_weights=False, threshold=6.0)
337
+ layer.weight = bnb.nn.Int8Params(torch.empty_like(original.weight, dtype=torch.int8),
338
+ requires_grad=False, has_fp16_weights=False)
339
+ if original.bias is not None:
340
+ layer.bias = torch.nn.Parameter(torch.empty_like(original.bias), requires_grad=False)
341
+ setattr(backbone.get_submodule(parent_name), leaf, layer)
342
+
343
+
344
+ def load_int8_checkpoint(model, bundle, device):
345
+ import torch
346
+ from accelerate.utils.modeling import set_module_tensor_to_device
347
+ from safetensors import safe_open
348
+ keys = set(model.state_dict())
349
+ quantization = read_json(bundle / "quantization_config.json")
350
+ scales = {name + ".SCB" for name in quantization["modules"]}
351
+ # Avoid a second GPU-sized state dict while materializing bitsandbytes parameters.
352
+ with safe_open(bundle / "model.safetensors", framework="pt", device="cpu") as tensors:
353
+ if set(tensors.keys()) != keys | scales:
354
+ raise ValueError("INT8 tensor inventory differs from the complete model")
355
+ for name in sorted(keys):
356
+ value = tensors.get_tensor(name)
357
+ scb_name = name.removesuffix(".weight") + ".SCB" if name.endswith(".weight") else None
358
+ statistics = tensors.get_tensor(scb_name) if scb_name in scales else None
359
+ if statistics is not None and value.dtype != torch.int8:
360
+ raise ValueError("a quantized text matrix must retain its INT8 storage")
361
+ set_module_tensor_to_device(model, name, device, value=value, fp16_statistics=statistics)
362
+ del value, statistics
363
+ for name, value in list(model.named_buffers()):
364
+ if value.is_meta:
365
+ raise ValueError("an uninitialized model buffer remains after INT8 loading")
366
+ if str(value.device) != device:
367
+ set_module_tensor_to_device(model, name, device, value=value)
368
+ if any(value.is_meta or str(value.device) != device for value in model.parameters()):
369
+ raise ValueError("INT8 loading must materialize all model parameters on the selected GPU")
370
+ return model
371
+
372
+
373
+ def format_response(prepared, encoded, logits, *, include_logits=False):
374
+ distributions, proposal, p_field_correct, scores, saved_logits = {}, {}, {}, {}, {}
375
+ for field, values in zip(prepared.fields, logits):
376
+ numbers = values.tolist() if hasattr(values, "tolist") else list(values)
377
+ ids = prepared.candidate_ids[field["id"]]
378
+ if len(numbers) != len(ids) or not all(math.isfinite(value) for value in numbers):
379
+ raise ValueError("finite logits must match all supplied candidates")
380
+ weights = [math.exp(value - max(numbers)) for value in numbers]
381
+ probabilities = [value / sum(weights) for value in weights]
382
+ fid = field["id"]
383
+ distributions[fid] = dict(zip(ids, probabilities))
384
+ index = max(range(len(ids)), key=probabilities.__getitem__)
385
+ proposal[fid] = ids[index]
386
+ p_field_correct[fid] = probabilities[index]
387
+ saved_logits[fid] = dict(zip(ids, numbers))
388
+ if field["field_type"] == "ordinal":
389
+ scores[fid] = sum(index * value for index, value in enumerate(probabilities))
390
+ result = {"format": "sourcehat-rlcd", "schema_version": SCHEMA_VERSION,
391
+ "proposal": proposal, "field_distributions": distributions, "p_field_correct": p_field_correct,
392
+ "expected_scores": scores, "p_object_correct": None, "p_action_success": None,
393
+ "p_safe": None, "p_workflow_success": None, "p_recoverable": None,
394
+ "metadata": {"base_model": BASE_MODEL, "base_revision": BASE_REVISION,
395
+ "compiled_tokens": len(encoded.input_ids), "reasoning": "disabled",
396
+ "field_probabilities": "unscaled model distributions", "action_policy": "not applied"}}
397
+ if include_logits:
398
+ result["field_logits"] = saved_logits
399
+ return result
400
+
401
+
402
+ def main():
403
+ parser = argparse.ArgumentParser(description=__doc__)
404
+ parser.add_argument("--request", type=Path, required=True)
405
+ parser.add_argument("--bundle", type=Path, default=Path(__file__).resolve().parent)
406
+ parser.add_argument("--base-model-path", type=Path)
407
+ parser.add_argument("--local-files-only", action="store_true")
408
+ parser.add_argument("--device", default="cuda:0", choices=("cuda:0",))
409
+ parser.add_argument("--include-logits", action="store_true")
410
+ args = parser.parse_args()
411
+ try:
412
+ request = read_json(args.request)
413
+ prepare_request(request)
414
+ model = DecisionModel(args.bundle, base_model_path=args.base_model_path,
415
+ local_files_only=args.local_files_only, device=args.device)
416
+ print(json.dumps(model.predict(request, include_logits=args.include_logits), allow_nan=False))
417
+ except (ValueError, OSError, RuntimeError, TypeError, KeyError) as exc:
418
+ print(json.dumps({"error": {"type": type(exc).__name__, "message": str(exc)}}, allow_nan=False), file=sys.stderr)
419
+ return 2
420
+ return 0
421
+
422
+
423
+ if __name__ == "__main__":
424
+ raise SystemExit(main())
joint_head_config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "hidden_size": 5120,
3
+ "width": 1024,
4
+ "routing_layers": 2,
5
+ "layers": 4,
6
+ "heads": 16,
7
+ "feedforward": 4096
8
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:30fbbf0b8374a509d0fec2bec0650237b4b4f0a4c5b7d31a5dfb61d4983f8ee5
3
+ size 55225866352
release_manifest.json ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "artifact_kind": "merged_typed_decision_model",
3
+ "base_files": {},
4
+ "base_model": "Cloudflare/clef",
5
+ "base_revision": "0b331204bb13fbd2ca93a64df1956f5b55478ce5",
6
+ "compute": "BF16 merged backbone; FP32 joint head",
7
+ "contract": "typed-decision-v1",
8
+ "files": {
9
+ ".gitattributes": {
10
+ "bytes": 101,
11
+ "sha256": "a0e948ca693c63e0b5139f66bd709003cbcf8bc764acb1ee687a552885c8fe2c"
12
+ },
13
+ "LICENSE": {
14
+ "bytes": 11343,
15
+ "sha256": "50cbab8a892c5f2993b8c7351a99182507472def3b1374558308605d99b86b32"
16
+ },
17
+ "NOTICE": {
18
+ "bytes": 892,
19
+ "sha256": "558d4c46d457d008cf62348d15cb14bbb4447be86415a1a3b28e92b9f2893979"
20
+ },
21
+ "README.md": {
22
+ "bytes": 6095,
23
+ "sha256": "f522962f138b8005c17a5fd9f1423ea781ba7d71d78edaf9e51fffc0b6b87379"
24
+ },
25
+ "backbone_config.json": {
26
+ "bytes": 3710,
27
+ "sha256": "d5543dd1b7b97e2196110cc36a27c10639880b3f21ee061ebc53b60498d74380"
28
+ },
29
+ "clef_runtime.py": {
30
+ "bytes": 19475,
31
+ "sha256": "ed227789c6dd19733ae1798f092c8f44566d8cc36d018fa22db48e0e73b64ee8"
32
+ },
33
+ "config.json": {
34
+ "bytes": 831,
35
+ "sha256": "d5ec4a78b3f8ea3bc37d295b90e03f008377eb5d340f74f88a34a0b274bfab0f"
36
+ },
37
+ "decision_contract.json": {
38
+ "bytes": 1547,
39
+ "sha256": "6e781b78ac2b7aaab7ebe386755dcd54f9cfbe27d36aac6e9d47886042f3800a"
40
+ },
41
+ "evaluation/rlcd_evaluation_data.json": {
42
+ "bytes": 1377989,
43
+ "sha256": "548431759e396f98831912dd3c98a780fff9ee029dcafb38b9ad5d585abbc2e3"
44
+ },
45
+ "example_request.json": {
46
+ "bytes": 1780,
47
+ "sha256": "81ab0b5bbfd7b5d39c57ef0155a1328f802bf053c6d96de6f247a8e0a1eae682"
48
+ },
49
+ "inference.py": {
50
+ "bytes": 22904,
51
+ "sha256": "a4d4e4157bdd597e340a38bc30e74499d58223db614e4b6bbfc53bd31541be64"
52
+ },
53
+ "joint_head_config.json": {
54
+ "bytes": 119,
55
+ "sha256": "890be585d75b981201eb96a35f98a9967afe37bc8d220cfdea2e72d56507534f"
56
+ },
57
+ "model.safetensors": {
58
+ "bytes": 55225866352,
59
+ "sha256": "30fbbf0b8374a509d0fec2bec0650237b4b4f0a4c5b7d31a5dfb61d4983f8ee5"
60
+ },
61
+ "requirements.txt": {
62
+ "bytes": 98,
63
+ "sha256": "e116ca583e70f42ad75233b8c141eaeedcd8e8e0d757516ba640a0f3d6f25c1d"
64
+ },
65
+ "tokenizer.json": {
66
+ "bytes": 19989325,
67
+ "sha256": "06b9509352d2af50381ab2247e083b80d32d5c0aba91c272ca9ff729b6a0e523"
68
+ },
69
+ "tokenizer_config.json": {
70
+ "bytes": 1075,
71
+ "sha256": "91a08f825d370d085d692e04cf117cdd7faad7bf18e996f1e6031b6dab03db72"
72
+ }
73
+ },
74
+ "format": "sourcehat-rlcd-release-v1",
75
+ "inference_identity": "a467220815c89fcd0a845e120cae727343abc10a4c6b707d5ed70a24342fc608",
76
+ "model_id": "SourceHat-Labs/RLCD-27B",
77
+ "release_version": "1.0.0",
78
+ "tokenizer_revision": "0b331204bb13fbd2ca93a64df1956f5b55478ce5"
79
+ }
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ torch==2.14.0
2
+ transformers==5.17.0
3
+ accelerate==1.15.0
4
+ safetensors==0.8.0
5
+ huggingface_hub>=1.32,<3
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:06b9509352d2af50381ab2247e083b80d32d5c0aba91c272ca9ff729b6a0e523
3
+ size 19989325
tokenizer_config.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "audio_bos_token": "<|audio_start|>",
4
+ "audio_eos_token": "<|audio_end|>",
5
+ "audio_token": "<|audio_pad|>",
6
+ "backend": "tokenizers",
7
+ "bos_token": null,
8
+ "clean_up_tokenization_spaces": false,
9
+ "eos_token": "<|im_end|>",
10
+ "errors": "replace",
11
+ "image_token": "<|image_pad|>",
12
+ "model_max_length": 262144,
13
+ "model_specific_special_tokens": {
14
+ "audio_bos_token": "<|audio_start|>",
15
+ "audio_eos_token": "<|audio_end|>",
16
+ "audio_token": "<|audio_pad|>",
17
+ "image_token": "<|image_pad|>",
18
+ "video_token": "<|video_pad|>",
19
+ "vision_bos_token": "<|vision_start|>",
20
+ "vision_eos_token": "<|vision_end|>"
21
+ },
22
+ "pad_token": "<|endoftext|>",
23
+ "pretokenize_regex": "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
24
+ "split_special_tokens": false,
25
+ "tokenizer_class": "Qwen2Tokenizer",
26
+ "unk_token": null,
27
+ "video_token": "<|video_pad|>",
28
+ "vision_bos_token": "<|vision_start|>",
29
+ "vision_eos_token": "<|vision_end|>"
30
+ }