alexwengg commited on
Commit
deaf348
·
verified ·
1 Parent(s): 864534c

Vela 3.0 (vela3-fast) Core ML: decision backbone + span_sets adapter, runtime, verification

Browse files
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ base_model: vllm-sr/vela3-fast
4
+ tags:
5
+ - coreml
6
+ - decision-making
7
+ - on-device
8
+ - system-one
9
+ - pii-detection
10
+ - hallucination-detection
11
+ - zero-shot-classification
12
+ ---
13
+
14
+ # Vela 3.0 (vela3-fast, 0.4B) · Core ML
15
+
16
+ [vllm-sr/vela3-fast](https://huggingface.co/vllm-sr/vela3-fast) (vLLM Semantic Router × KR Labs, Vela 3.0 family) converted to
17
+ Core ML for Apple silicon: **decisions** (choice / yes-no over options you name) and **text spans** (17 types of personal
18
+ information, words of an answer its context does not support) from one UltraBERT-380M encoder, on device.
19
+
20
+ | | |
21
+ |---|---|
22
+ | Source | `vllm-sr/vela3-fast` @ `9e338f39` |
23
+ | `Vela3Decision.mlpackage` | decision backbone, fp16, 726 MB: functions `L128`, `L256`, `L512`, `L1024` (encoder tokens) |
24
+ | `Vela3SpanSets.mlpackage` | backbone + the release's `span_sets` adapter (LoRA merged), fp16, 725 MB: functions `L512`, `L1024` |
25
+ | Host side | `heads_decision.safetensors`, `heads_span_sets.safetensors` (fp32 readout heads), `tokenizer.json`, `config.json`, `vela3_config.json` (the release's thresholds) |
26
+ | Runtime | `vela3_coreml.py` (Python: coremltools, tokenizers, torch for the small heads, no PyTorch weights) + `upstream/` (the release's own rendering, span decoder and thresholds, unmodified) |
27
+ | Requires | macOS 15+ / iOS 18+ |
28
+
29
+ ```python
30
+ from vela3_coreml import Vela3CoreML
31
+ m = Vela3CoreML(".") # GPU by default
32
+ m.decide("My card was charged twice and I need this fixed today.",
33
+ {"intent": {"type": "choice", "instructions": "What does the customer want?",
34
+ "criteria": {"refund": "Money back for the duplicate charge", "cancel": "Cancel the order"}},
35
+ "urgent": {"type": "noul", "instructions": "The customer needs a fast response."}})
36
+ m.pii("Hi, I'm Dana Whitfield (dana@example.com, 312-555-0110).") # [{label, start, end, text, score}, ...]
37
+ m.unsupported(context="Adults may take up to 4 g of paracetamol in 24 hours.",
38
+ answer="Adults may take up to 6 g of paracetamol in 24 hours.") # -> "6 g"
39
+ ```
40
+
41
+ ## Fidelity
42
+
43
+ Against the fp32 PyTorch release on the same inputs (`reports/verify.txt`):
44
+
45
+ - **Decisions:** typed-decisions TEST, all 1,200 choice and yes/no questions: **0 answers differ**, max probability difference 0.0026.
46
+ - **Personal information:** 25 varied passages (support tickets, clinic notes, HR reports, bank chats; 183 spans): **identical span sets**.
47
+ - **Unsupported claims:** identical spans on every context / answer pair tested.
48
+
49
+ On a 20,000-word synthetic case file with 2,971 planted values, the Core ML model catches 99.5 % (2,956), with 30 other flags.
50
+
51
+ ## Speed (MacBook Pro M5 Pro, GPU)
52
+
53
+ | Encoder function | Decision | Span sets |
54
+ |---|---:|---:|
55
+ | L128 | 6.7 ms | |
56
+ | L256 | 9.5 ms | |
57
+ | L512 | 17.6 ms | 18.7 ms |
58
+ | L1024 | 37.6 ms | 37.5 ms |
59
+
60
+ One encoder pass answers one question. The question (options, or the 17 PII label descriptions, ~250 tokens) counts toward
61
+ the length, so a PII pass over a paragraph usually lands in `L512`: about 0.5 ms per word end to end. The Neural Engine is
62
+ not used: it was slower at every length and drifted further from the fp32 answers (15 / 1,200 decisions flipped).
63
+
64
+ ## Scope and limits
65
+
66
+ - Covered: decisions on the decision backbone, and the two label sets of the `span_sets` adapter (17 PII types, `unsupported`).
67
+ The release's other adapters (open-label NER, relations, evidence, router signals, domain, fact-check, feedback) are not
68
+ converted; each retrains every layer, so each would be its own encoder package.
69
+ - The release's `score` question type is not part of the decision backbone and is not supported (as upstream).
70
+ - Inputs are limited to 1,024 tokens per encoder pass. Longer decision inputs raise `Unsupported`; longer span inputs are
71
+ windowed at 1,024 tokens (the release uses 8,192), so long-document spans can differ.
72
+
73
+ ## Files and licences
74
+
75
+ Apache-2.0, as the source release (`LICENSE`). `upstream/` is the release's own code, unmodified. The conversion: a
76
+ fixed-length export of the encoder (local layers' 128-token sliding window as a band mask, the two RoPE bases precomputed, fp16-safe
77
+ masks), the adapter's LoRA merged into plain weights, heads kept in fp32 on the host. `conversion/` holds the export, packaging
78
+ and verification scripts.
Vela3Decision.mlpackage/Data/com.apple.CoreML/model.mlmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3983ec2a96ba8403cf48feaefc9f16cf73645d80e25ceb054718c4ee7f44fdb4
3
+ size 1539769
Vela3Decision.mlpackage/Data/com.apple.CoreML/weights/weight.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:af7431750cca9421b75d9ef1420a29b7ce4e6cdbe61e9029c81f8129ca344eff
3
+ size 759866432
Vela3Decision.mlpackage/Manifest.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fileFormatVersion": "1.0.0",
3
+ "itemInfoEntries": {
4
+ "667A5EF2-2D81-4829-A14C-68CAAE3B6125": {
5
+ "author": "com.apple.CoreML",
6
+ "description": "CoreML Model Weights",
7
+ "name": "weights",
8
+ "path": "com.apple.CoreML/weights"
9
+ },
10
+ "EDCC2594-218B-456E-B6EF-CD16E0AEF80A": {
11
+ "author": "com.apple.CoreML",
12
+ "description": "CoreML Model Specification",
13
+ "name": "model.mlmodel",
14
+ "path": "com.apple.CoreML/model.mlmodel"
15
+ }
16
+ },
17
+ "rootModelIdentifier": "EDCC2594-218B-456E-B6EF-CD16E0AEF80A"
18
+ }
Vela3SpanSets.mlpackage/Data/com.apple.CoreML/model.mlmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3e8d0a64e7c85378c23e1e12e3eb2db5f9e6dad50a4172cb57966f6a6657be05
3
+ size 769891
Vela3SpanSets.mlpackage/Data/com.apple.CoreML/weights/weight.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2c3a719b4df3d682f399222484a7daa756954cdbca0c4a74c9943dcfb14c544a
3
+ size 759308736
Vela3SpanSets.mlpackage/Manifest.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fileFormatVersion": "1.0.0",
3
+ "itemInfoEntries": {
4
+ "634082BA-F12E-41DD-B522-05AD1C194B3B": {
5
+ "author": "com.apple.CoreML",
6
+ "description": "CoreML Model Weights",
7
+ "name": "weights",
8
+ "path": "com.apple.CoreML/weights"
9
+ },
10
+ "A5589950-6FBF-4EC8-87FF-05E6C4838F41": {
11
+ "author": "com.apple.CoreML",
12
+ "description": "CoreML Model Specification",
13
+ "name": "model.mlmodel",
14
+ "path": "com.apple.CoreML/model.mlmodel"
15
+ }
16
+ },
17
+ "rootModelIdentifier": "A5589950-6FBF-4EC8-87FF-05E6C4838F41"
18
+ }
config.json ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "UltrabertModel"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "attention_windows": [
8
+ 128,
9
+ 128,
10
+ null,
11
+ 128,
12
+ 128,
13
+ null,
14
+ 128,
15
+ 128,
16
+ null,
17
+ 128,
18
+ 128,
19
+ null,
20
+ 128,
21
+ 128,
22
+ null,
23
+ 128,
24
+ 128,
25
+ null,
26
+ 128,
27
+ 128,
28
+ null,
29
+ 128,
30
+ 128,
31
+ null
32
+ ],
33
+ "auto_map": {
34
+ "AutoConfig": "configuration_ultrabert.UltrabertConfig",
35
+ "AutoModel": "modeling_ultrabert.UltrabertModel",
36
+ "AutoModelForMaskedLM": "modeling_ultrabert.UltrabertForMaskedLM",
37
+ "AutoModelForSequenceClassification": "modeling_ultrabert.UltrabertForSequenceClassification",
38
+ "AutoModelForTokenClassification": "modeling_ultrabert.UltrabertForTokenClassification",
39
+ "AutoModelForQuestionAnswering": "modeling_ultrabert.UltrabertForQuestionAnswering"
40
+ },
41
+ "bos_token_id": 0,
42
+ "classifier_dropout": 0.0,
43
+ "dtype": "float32",
44
+ "eos_token_id": 0,
45
+ "head_dim": 128,
46
+ "hidden_act": "silu",
47
+ "hidden_size": 1024,
48
+ "initializer_range": 0.02,
49
+ "intermediate_size": 3072,
50
+ "mlp_bias": false,
51
+ "model_type": "ultrabert",
52
+ "num_attention_heads": 8,
53
+ "num_hidden_layers": 24,
54
+ "num_key_value_heads": 8,
55
+ "pad_token_id": 0,
56
+ "prediction_head_size": 1024,
57
+ "rms_norm_eps": 1e-06,
58
+ "rope_theta": [
59
+ 10000.0,
60
+ 10000.0,
61
+ 2560000.0,
62
+ 10000.0,
63
+ 10000.0,
64
+ 2560000.0,
65
+ 10000.0,
66
+ 10000.0,
67
+ 2560000.0,
68
+ 10000.0,
69
+ 10000.0,
70
+ 2560000.0,
71
+ 10000.0,
72
+ 10000.0,
73
+ 2560000.0,
74
+ 10000.0,
75
+ 10000.0,
76
+ 2560000.0,
77
+ 10000.0,
78
+ 10000.0,
79
+ 2560000.0,
80
+ 10000.0,
81
+ 10000.0,
82
+ 2560000.0
83
+ ],
84
+ "tie_word_embeddings": false,
85
+ "transformers_version": "5.16.1",
86
+ "vocab_size": 49160,
87
+ "decision": {
88
+ "model": "vela3-fast decision backbone (soup_X2)",
89
+ "marker_ids": {
90
+ "[Q]": 49152,
91
+ "[O]": 49153,
92
+ "[ABS]": 49154,
93
+ "[SEP_SCHEMA]": 49155,
94
+ "[SEG_user]": 49156,
95
+ "[SEG_answer]": 49157,
96
+ "[E]": 49158,
97
+ "[SEG_context]": 49159
98
+ },
99
+ "n_vocab": 49160,
100
+ "n_vocab_base": 49152,
101
+ "proj_dim": 256,
102
+ "readout": "both (cosine/tau + MLP at the [O] markers)",
103
+ "tau": 0.0635916069149971,
104
+ "max_len": 32768,
105
+ "rendering": "ub_d3_common.to_row",
106
+ "noul": "2-option choice {no, yes}; answer = p(yes)"
107
+ }
108
+ }
conversion/convert.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Convert the vela3-fast decision backbone encoder to a fixed-length fp16 Core ML package: python convert.py L [name]
2
+ -> coreml/<name>_L<L>.mlpackage (inputs input_ids / attention_mask int32 [1, L], output hidden fp16 [1, L, 1024])."""
3
+ import sys
4
+ import numpy as np
5
+ import torch
6
+ import coremltools as ct
7
+ import ct_patch # noqa: F401
8
+ from vela3_export import Vela3EncoderExport, load_decision
9
+
10
+ L = int(sys.argv[1]); name = sys.argv[2] if len(sys.argv) > 2 else "vela3_decision"
11
+ m = load_decision()
12
+ g = Vela3EncoderExport(m.encoder, L).eval()
13
+ x = torch.zeros(1, L, dtype=torch.int32); mk = torch.ones(1, L, dtype=torch.int32)
14
+ with torch.no_grad():
15
+ tr = torch.jit.trace(g, (x, mk))
16
+ ml = ct.convert(tr, inputs=[ct.TensorType("input_ids", shape=(1, L), dtype=np.int32), ct.TensorType("attention_mask", shape=(1, L), dtype=np.int32)],
17
+ outputs=[ct.TensorType("hidden", dtype=np.float16)], minimum_deployment_target=ct.target.macOS15,
18
+ compute_precision=ct.precision.FLOAT16, convert_to="mlprogram")
19
+ ml.short_description = f"vela3-fast UltraBERT-380M encoder ({name}), fixed length {L}"
20
+ ml.save(f"coreml/{name}_L{L}.mlpackage")
21
+ print("saved", f"coreml/{name}_L{L}.mlpackage")
conversion/ct_patch.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """coremltools 9 + numpy 2: the torch frontend's _cast folds 1-element constants with int(array([n])), which numpy 2 rejects."""
2
+ import numpy as np
3
+ from coremltools.converters.mil.frontend.torch import ops as _ops
4
+
5
+ _cast0 = _ops._cast
6
+
7
+
8
+ def _cast(context, node, dtype, dtype_name):
9
+ x = _ops._get_inputs(context, node, expected=1)[0]
10
+ if x.can_be_folded_to_const() and np.ndim(x.val) > 0 and np.size(x.val) == 1:
11
+ context.add(_ops.mb.const(val=dtype(np.asarray(x.val).item()), name=node.name), node.name)
12
+ return
13
+ _cast0(context, node, dtype, dtype_name)
14
+
15
+
16
+ _ops._cast = _cast
conversion/package.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build the FluidInference/vela-3.0-coreml release folder (release/):
2
+ Vela3Decision.mlpackage multifunction fp16 encoder (decision backbone), functions L128 / L256 / L512 / L1024
3
+ Vela3SpanSets.mlpackage multifunction fp16 encoder (backbone + span_sets adapter, LoRA merged), functions L512 / L1024
4
+ heads_decision.safetensors, heads_span_sets.safetensors fp32 heads (run on the host)
5
+ tokenizer.json (base tokenizer, the 8 marker tokens removed: markers are inserted by id), config.json, vela3_config.json
6
+ upstream/ the release's own Python (Apache-2.0, unmodified) that renders inputs, decodes spans and picks thresholds"""
7
+ import json, shutil, sys
8
+ from pathlib import Path
9
+ import coremltools as ct
10
+ import torch
11
+ from safetensors.torch import load_file, save_file
12
+
13
+ OUT = Path("release"); OUT.mkdir(exist_ok=True)
14
+ for name, src, Ls in (("Vela3Decision", "vela3_decision", (128, 256, 512, 1024)), ("Vela3SpanSets", "vela3_span_sets", (512, 1024))):
15
+ d = ct.utils.MultiFunctionDescriptor()
16
+ for L in Ls:
17
+ d.add_function(f"coreml/{src}_L{L}.mlpackage", src_function_name="main", target_function_name=f"L{L}")
18
+ d.default_function_name = f"L{Ls[0]}"
19
+ ct.utils.save_multifunction(d, str(OUT / f"{name}.mlpackage"))
20
+ print("packed", name)
21
+
22
+ # heads: decision (from model.safetensors) and span_sets (the adapter's own heads; everything outside the encoder)
23
+ sd = load_file("src/model.safetensors")
24
+ save_file({k: v.float().contiguous() for k, v in sd.items() if not k.startswith("encoder.")}, str(OUT / "heads_decision.safetensors"))
25
+ ad = load_file("src/span_sets_adapter.safetensors")
26
+ heads = {k: v.float().contiguous() for k, v in ad.items() if not k.startswith("encoder.")}
27
+ for k, v in sd.items(): # heads the adapter did not change come from the backbone file
28
+ if not k.startswith("encoder.") and k not in heads:
29
+ heads[k] = v.float().contiguous()
30
+ save_file(heads, str(OUT / "heads_span_sets.safetensors"))
31
+ print("heads", sorted(heads))
32
+
33
+ cfg = json.load(open("src/config.json")); mk = cfg["decision"]["marker_ids"]
34
+ tj = json.load(open("src/tokenizer.json", encoding="utf-8"))
35
+ json.dump(tj, open(OUT / "tokenizer.json", "w", encoding="utf-8"), ensure_ascii=False) # the release's own file (its loaders strip the markers)
36
+ for f in ("config.json", "vela3_config.json", "tokenizer_config.json", "LICENSE"):
37
+ shutil.copy(f"src/{f}", OUT / f)
38
+ up = OUT / "upstream"; up.mkdir(exist_ok=True)
39
+ for f in ("vela3_encoder.py", "vela3_schema.py", "ub_d3_common.py"):
40
+ shutil.copy(f"src/{f}", up / f)
41
+ print("done", sorted(p.name for p in OUT.iterdir()))
conversion/span_export.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """vela3-fast span adapters for Core ML: build the release SchemaNet (frozen backbone + adapter), merge the LoRA deltas into plain
2
+ Linear weights (W + alpha / r * B A), and export the merged encoder with the same fixed-length graph as the decision backbone.
3
+
4
+ python span_export.py # parity: merged export vs the release SchemaNet hidden states
5
+ python span_export.py convert L [adapter] # -> coreml/vela3_<adapter>_L<L>.mlpackage (default adapter: span_sets)"""
6
+ import sys
7
+ import torch
8
+ from torch import nn
9
+ from vela3_export import Vela3EncoderExport, load_decision
10
+
11
+ sys.path.insert(0, "src")
12
+ import vela3_schema as VS # noqa: E402
13
+
14
+
15
+ def build(adapter="span_sets"):
16
+ dec = load_decision()
17
+ return dec, VS.build_adapter(dec, f"src/{adapter}_adapter.safetensors", "cpu")
18
+
19
+
20
+ @torch.no_grad()
21
+ def merge_lora(net):
22
+ """Replace every LoRALinear by an nn.Linear with the merged weight (a copy: the shared backbone tensors are untouched)."""
23
+ n = 0
24
+ for mod in list(net.modules()):
25
+ for name, child in list(mod.named_children()):
26
+ if isinstance(child, VS.LoRALinear):
27
+ b = child.base
28
+ lin = nn.Linear(b.in_features, b.out_features, bias=b.bias is not None)
29
+ lin.weight.copy_(b.weight + child.scale * (child.lora_B @ child.lora_A))
30
+ if b.bias is not None:
31
+ lin.bias.copy_(b.bias)
32
+ setattr(mod, name, lin); n += 1
33
+ return n
34
+
35
+
36
+ if __name__ == "__main__":
37
+ adapter = sys.argv[3] if len(sys.argv) > 3 else "span_sets"
38
+ dec, net = build(adapter)
39
+ if sys.argv[1:2] == ["convert"]:
40
+ import numpy as np, coremltools as ct
41
+ import ct_patch # noqa: F401
42
+ ids = torch.randint(5, 49152, (1, 300)); ids[0, 0] = 0
43
+ with torch.no_grad():
44
+ ref = net.hidden(ids, torch.ones_like(ids))[0]
45
+ print("merged LoRA layers:", merge_lora(net))
46
+ if sys.argv[1:2] != ["convert"]:
47
+ for L in (300, 512):
48
+ g = Vela3EncoderExport(net.encoder, L).eval()
49
+ x = torch.zeros(1, L, dtype=torch.int32); x[0, :300] = ids[0]; mk = torch.zeros(1, L, dtype=torch.int32); mk[0, :300] = 1
50
+ h = g(x, mk)[0, :300]
51
+ print(f"L={L} max|dh|={(h - ref).abs().max():.2e} min cos={nn.functional.cosine_similarity(h, ref, dim=-1).min():.6f}")
52
+ sys.exit()
53
+ L = int(sys.argv[2])
54
+ g = Vela3EncoderExport(net.encoder, L).eval()
55
+ x = torch.zeros(1, L, dtype=torch.int32); mk = torch.ones(1, L, dtype=torch.int32)
56
+ with torch.no_grad():
57
+ tr = torch.jit.trace(g, (x, mk))
58
+ ml = ct.convert(tr, inputs=[ct.TensorType("input_ids", shape=(1, L), dtype=np.int32), ct.TensorType("attention_mask", shape=(1, L), dtype=np.int32)],
59
+ outputs=[ct.TensorType("hidden", dtype=np.float16)], minimum_deployment_target=ct.target.macOS15,
60
+ compute_precision=ct.precision.FLOAT16, convert_to="mlprogram")
61
+ ml.short_description = f"vela3-fast UltraBERT-380M encoder + {adapter} adapter (LoRA merged), fixed length {L}"
62
+ ml.save(f"coreml/vela3_{adapter}_L{L}.mlpackage"); print("saved", f"coreml/vela3_{adapter}_L{L}.mlpackage")
conversion/vela3_export.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """vela3-fast UltraBERT-380M encoder as a fixed-length, eager-attention graph (ids + mask -> final-norm hidden states).
2
+
3
+ Same contract as the CPU path of modeling_ultrabert.UltrabertModel.forward: local layers attend to keys with |i - j| <= 128, global
4
+ layers to all keys, padding masks keys only; RoPE theta per layer (10k local, 2.56M global). Masks use -1e4 instead of finfo.min
5
+ (fp16-safe); cos / sin and the two masks are precomputed for the bucket length."""
6
+ import sys
7
+ import torch
8
+ from torch import nn
9
+
10
+ MASK_VALUE = -1e4
11
+ sys.path.insert(0, "src")
12
+
13
+
14
+ def load_decision(path="src"):
15
+ from vela3_encoder import DecisionEncoder
16
+ return DecisionEncoder.load(path, device="cpu")
17
+
18
+
19
+ class Vela3EncoderExport(nn.Module):
20
+ def __init__(self, enc, length):
21
+ super().__init__()
22
+ cfg = enc.config
23
+ cfg._attn_implementation = "eager"
24
+ self.length, self.layers, self.embed, self.norm = length, enc.layers, enc.embed_tokens, enc.norm
25
+ self.windows, self.thetas = list(cfg.attention_windows), list(cfg.rope_theta)
26
+ pos = torch.arange(length).unsqueeze(0)
27
+ probe = torch.zeros(1, length, cfg.hidden_size)
28
+ self.theta_key = {}
29
+ for i, base in enumerate(sorted(set(self.thetas))):
30
+ cos, sin = enc.rotary_emb[str(base).replace(".", "_")](probe, pos)
31
+ self.register_buffer(f"cos{i}", cos.detach().clone()); self.register_buffer(f"sin{i}", sin.detach().clone())
32
+ self.theta_key[base] = i
33
+ idx = torch.arange(length)
34
+ dist = (idx[:, None] - idx[None, :]).abs()
35
+ self.window_key = {}
36
+ for i, w in enumerate(sorted({w for w in self.windows if w is not None})):
37
+ self.register_buffer(f"band{i}", torch.where(dist <= w, 0.0, MASK_VALUE).view(1, 1, length, length))
38
+ self.window_key[w] = i
39
+
40
+ def forward(self, input_ids, attention_mask):
41
+ pad = (1.0 - attention_mask.float()).view(1, 1, 1, self.length) * MASK_VALUE
42
+ bands = {w: getattr(self, f"band{i}") + pad for w, i in self.window_key.items()}
43
+ x = self.embed(input_ids.long())
44
+ for layer, w, t in zip(self.layers, self.windows, self.thetas):
45
+ k = self.theta_key[t]
46
+ x = layer(x, attention_mask=pad if w is None else bands[w],
47
+ position_embeddings=(getattr(self, f"cos{k}"), getattr(self, f"sin{k}")))
48
+ return self.norm(x)
49
+
50
+
51
+ if __name__ == "__main__": # parity of the export graph vs the release encoder (sdpa, fp32 CPU) on a real decision input
52
+ import json
53
+ import pyarrow.parquet as pq
54
+ m = load_decision()
55
+ m.encoder.config._attn_implementation = "eager"
56
+ r = pq.read_table("data/typed/all/test-00000-of-00001.parquet").to_pylist()[0]
57
+ state, qs = json.loads(r["state"]), json.loads(r["questions"])
58
+ q = next(q for q in qs.values() if q["type"] == "choice")
59
+ ids = m.encode(state, q)["ids"]; n = len(ids)
60
+ with torch.no_grad():
61
+ ref = m.encoder(input_ids=torch.tensor([ids]), attention_mask=torch.ones(1, n, dtype=torch.long)).last_hidden_state[0]
62
+ for L in (n, 512):
63
+ g = Vela3EncoderExport(m.encoder, L).eval()
64
+ x = torch.zeros(1, L, dtype=torch.int32); x[0, :n] = torch.tensor(ids); mk = torch.zeros(1, L, dtype=torch.int32); mk[0, :n] = 1
65
+ h = g(x, mk)[0, :n]
66
+ print(f"n={n} L={L} max|dh|={(h - ref).abs().max():.2e} min cos={nn.functional.cosine_similarity(h, ref, dim=-1).min():.6f}")
conversion/verify_release.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Check release/vela3_coreml.py (fresh import, release folder only) against the fp32 torch release code:
2
+ decisions on typed-decisions TEST (choice + noul, data/ref.jsonl), PII spans on the 25 hand-written demo sections, and
3
+ unsupported-claim spans on a few context / answer pairs. Also times each Core ML function on the GPU."""
4
+ import json, sys, time
5
+ import numpy as np
6
+ import pyarrow.parquet as pq
7
+
8
+ sys.path.insert(0, "release")
9
+ from vela3_coreml import Vela3CoreML # noqa: E402
10
+
11
+ m = Vela3CoreML("release")
12
+ # 1) decisions
13
+ ref = {x["id"]: x for x in map(json.loads, open("data/ref.jsonl"))}
14
+ nq = flips = 0; dmax = 0.0; margins = []
15
+ for r in pq.read_table("data/typed/all/test-00000-of-00001.parquet").to_pylist():
16
+ R = ref[r["id"]]; state, qs = json.loads(r["state"]), json.loads(r["questions"])
17
+ qs = {k: q for k, q in qs.items() if q["type"] in ("choice", "noul")}
18
+ for k, an in m.decide(state, qs).items():
19
+ rb = R["answers"][k]; nq += 1
20
+ if an["type"] == "noul":
21
+ dmax = max(dmax, abs(an["noul"] - rb["noul"])); flips += (an["noul"] >= 0.5) != (rb["noul"] >= 0.5)
22
+ else:
23
+ pr = rb["probabilities"]; dmax = max(dmax, max(abs(an["probabilities"][o] - pr[o]) for o in pr)); flips += an["choice"] != rb["choice"]
24
+ print(f"decisions: {nq} questions, {flips} flips vs fp32 torch, max |dp| {dmax:.4f}")
25
+
26
+ # 2) + 3) spans, torch reference computed fresh
27
+ sys.path.insert(0, "demo")
28
+ from doc import RAW, TAG # noqa: E402
29
+ sections = [TAG.sub(r"\2", l) for l in RAW.strip().splitlines() if l.strip() and not l.startswith("#")]
30
+ sys.path.insert(0, "."); from span_engine import PIIEngine # noqa: E402
31
+ t = PIIEngine("torch").v
32
+ key = lambda ss: {(s["label"], s["start"], s["end"]) for s in ss}
33
+ pii_diff = [i for i, s in enumerate(sections) if key(m.pii(s)) != key(t.span_answer(s, {"type": "span", "criteria": json.load(open("src/vela3_config.json"))["span"]["router_label_sets"]["pii"]})[0]["spans"])]
34
+ n_spans = sum(len(m.pii(s)) for s in sections)
35
+ print(f"pii: {len(sections)} sections, {n_spans} spans, sections whose span set differs from torch: {pii_diff}")
36
+ pairs = [("Adults may take up to 4 g of paracetamol in 24 hours.", "Adults may take up to 6 g of paracetamol in 24 hours."),
37
+ ("The Eiffel Tower is 330 m tall and was finished in 1889.", "The Eiffel Tower, finished in 1899, is 330 m tall."),
38
+ ("Refunds are issued within 5 business days to the original card.", "Refunds are issued within 5 business days to the original card."),
39
+ ("The meeting moved from Tuesday to Thursday at 3 pm in room B.", "The meeting is now on Thursday at 4 pm in room C.")]
40
+ for c, a in pairs:
41
+ got = [s["text"] for s in m.unsupported(c, a)]
42
+ exp = [s["text"] for s in t.span_answer({"context": c, "answer": a}, {"type": "span", "criteria": ["unsupported"]})[0]["spans"]]
43
+ print(f"unsupported: coreml {got} | torch {exp} | {'same' if got == exp else 'DIFF'}")
44
+
45
+ # 4) latency per Core ML function (GPU), median of 20 after warm-up
46
+ for name, enc in (("decision", m.dec_enc), ("span_sets", m.span_enc)):
47
+ row = {}
48
+ for L in enc.lengths:
49
+ ids = list(np.random.randint(5, 49000, size=L - 4))
50
+ for _ in range(3): enc(ids)
51
+ enc.last_ms.clear(); [enc(ids) for _ in range(20)]
52
+ row[f"L{L}"] = round(float(np.median([ms for _, ms in enc.last_ms])), 1)
53
+ print(f"latency {name} (ms, CPU_AND_GPU):", row)
heads_decision.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:402dffef5218b64d55e11372db414046219e0d6dccae93193e92cd6e8a0635d5
3
+ size 11563016
heads_span_sets.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:71bac50e691185155ba9d30a08c4f70bb07bbce37a6caee0f7bb922859a83e92
3
+ size 13662612
reports/verify.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ verify_release.py (release folder only, fresh import) vs the fp32 PyTorch release code (vllm-sr/vela3-fast @ 9e338f39), MacBook Pro M5 Pro, 2026-10-28
2
+
3
+ decisions: 1200 questions, 0 flips vs fp32 torch, max |dp| 0.0026 (typed-decisions TEST, choice + noul)
4
+ pii: 25 sections, 183 spans, sections whose span set differs from torch: []
5
+ unsupported: coreml ['6 g'] | torch ['6 g'] | same
6
+ unsupported: coreml ['finished in 1899'] | torch ['finished in 1899'] | same
7
+ unsupported: coreml [] | torch [] | same
8
+ unsupported: coreml ['Thursday at 4 pm in room C'] | torch ['Thursday at 4 pm in room C'] | same
9
+ latency decision (ms, CPU_AND_GPU): {'L128': 6.7, 'L256': 9.5, 'L512': 17.6, 'L1024': 37.6}
10
+ latency span_sets (ms, CPU_AND_GPU): {'L512': 18.7, 'L1024': 37.5}
11
+
12
+ Neural Engine (CPU_AND_NE), decision backbone, same 1200 questions: 15 flips (top-2 margins up to 0.047), max |dp| 0.047,
13
+ and slower at every length (L128 9.7, L256 21.2, L512 53.5, L1024 135.8 ms, measured on a busy machine) -> not used.
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "backend": "tokenizers",
4
+ "bos_token": "<|endoftext|>",
5
+ "clean_up_tokenization_spaces": false,
6
+ "eos_token": "<|endoftext|>",
7
+ "errors": "replace",
8
+ "extra_special_tokens": [
9
+ "<|endoftext|>",
10
+ "<|im_start|>",
11
+ "<|im_end|>",
12
+ "<repo_name>",
13
+ "<reponame>",
14
+ "<file_sep>",
15
+ "<filename>",
16
+ "<gh_stars>",
17
+ "<issue_start>",
18
+ "<issue_comment>",
19
+ "<issue_closed>",
20
+ "<jupyter_start>",
21
+ "<jupyter_text>",
22
+ "<jupyter_code>",
23
+ "<jupyter_output>",
24
+ "<|sep|>",
25
+ "<|mask|>"
26
+ ],
27
+ "mask_token": "<|mask|>",
28
+ "model_max_length": 32768,
29
+ "pad_token": "<|endoftext|>",
30
+ "sep_token": "<|sep|>",
31
+ "tokenizer_class": "GPT2Tokenizer",
32
+ "unk_token": "<|endoftext|>",
33
+ "vocab_size": 49152
34
+ }
upstream/ub_d3_common.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ub_d3_common.py (UBD3, 16 Oct 2026): one rendering of a typed decision (Decision Index wire format: state + {type, instructions,
2
+ criteria}) into the UBENC row contract, shared by the d3 data prep (training rows) and the Decision Index engine (inference), so
3
+ train and test see byte-identical inputs.
4
+
5
+ state -> one part, role "user": the string as is, or a JSON object as compact JSON (the kit's base.text rendering);
6
+ instructions -> the question text (string as is, object as compact JSON);
7
+ choice -> options {key: description or ""} in criteria order (the encoder reads "key: description", or "key" alone);
8
+ noul -> a 2-option choice {"no": "", "yes": ""}; the answer is p(yes).
9
+ The question is marked nodrop: training never drops options (d3 trains on the full option set, only re-permuted), and has no [ABS]."""
10
+ import json
11
+
12
+ NOUL_OPTIONS = {"no": "", "yes": ""}
13
+
14
+
15
+ def text(x):
16
+ return x if isinstance(x, str) else json.dumps(x, ensure_ascii=False, separators=(",", ":"))
17
+
18
+
19
+ def options_of(q):
20
+ if q["type"] == "noul":
21
+ return dict(NOUL_OPTIONS)
22
+ return {str(k): ("" if v is None else text(v)) for k, v in q["criteria"].items()}
23
+
24
+
25
+ def to_row(rid, state, q, gold=None, soft=None, weight=1.0):
26
+ """state: str | object; q: {type, instructions, criteria?}. gold: option name (noul: "yes"/"no"); soft: {option name: prob}."""
27
+ opts = options_of(q)
28
+ qq = dict(id="d3:" + q["type"], type="choice", over="user", text=text(q.get("instructions", "")), question_paraphrases=[],
29
+ options=opts, abstain=False, nodrop=True, gold=gold if gold is not None else next(iter(opts)))
30
+ if soft is not None:
31
+ qq["soft"] = soft
32
+ if weight != 1.0:
33
+ qq["weight"] = weight
34
+ return dict(id=rid, parts=[dict(role="user", text=text(state if state is not None else ""))], questions=[qq])
upstream/vela3_encoder.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """vela3_encoder.py: inference for vela3-fast (UltraBERT-380M encoder).
2
+
3
+ Three networks on one frozen backbone:
4
+ DecisionEncoder the decision backbone (UBD3 stage 1b, soup a+c) and its heads: every choice / noul decision that is not a router
5
+ question. This class and model.safetensors are unchanged from the decision-only preview (8667a7bb), so these
6
+ answers are the preview's, bit for bit.
7
+ span adapter LoRA r64 on all 24 layers + the top 4 layers + span head (span_adapter.safetensors): every span question.
8
+ router adapter LoRA r64 on all 24 layers + choice / set head (router_adapter.safetensors): choice / set questions whose
9
+ instructions are one of the router texts in router_questions.json.
10
+
11
+ Decision rendering (one encoder input per question, exactly as in training, ub_d3_common.to_row):
12
+ [BOS] [Q] instructions [O] key_1: description_1 [O] key_2 ... [SEP_SCHEMA] [SEG_user] state [EOS]
13
+ state / instructions: strings as is, JSON objects as compact JSON; noul = the 2-option choice {no, yes}, answer = p(yes).
14
+ Readout (both, as trained): cosine(w_o(norm(H[O_i])) + w_q(norm(H[Q])), w_p(norm(mean H over [SEG_user] .. state))) / tau
15
+ + MLP(H[O_i]); softmax over the question's options. Nothing is truncated: an input over max_len raises Unsupported.
16
+ Span and router passes: vela3_schema.py (the Vela 2.0 layout, 8,192-token windows). Evidence questions (EV-FIX, 18 Oct 2026,
17
+ DIAG_04B_EV_HALU.md): one window up to span.evidence.max_len (32,768) on the same span adapter, and a threshold by target length
18
+ (span.evidence.buckets: <= 2,048 tokens the short-dev pick, longer the QASPER-validation pick).
19
+ Task adapters (round 1, 19 Oct 2026; vela3_config.json span.task_adapters): relation questions ("Which spans are the <relation> of <head>?",
20
+ "Which spans are related to <head> by these relations?", ...) -> the relation adapter, per-form thresholds (pair = one relation, multi =
21
+ several); open-label entity questions (names only) stay on the span adapter.
22
+
23
+ from vela3_encoder import Vela3Encoder
24
+ m = Vela3Encoder.load("path/to/this/folder") # cuda if available
25
+ m.system_one(state, {"q": {"type": "choice", "instructions": "...", "criteria": {"a": "...", "b": None}},
26
+ "ents": {"type": "span", "instructions": "Which spans are named entities of these types?",
27
+ "criteria": {"person": None, "company": None}}})
28
+ m.predict(state, questions) # decisions only, the preview's API and answers (the Decision Index engine uses it)
29
+ """
30
+ import json, math
31
+ from pathlib import Path
32
+
33
+ import numpy as np
34
+ import torch
35
+ import torch.nn as nn
36
+
37
+ from ub_d3_common import to_row
38
+
39
+ MARKERS = ["[Q]", "[O]", "[ABS]", "[SEP_SCHEMA]", "[SEG_user]", "[SEG_answer]", "[E]", "[SEG_context]"]
40
+
41
+
42
+ class Unsupported(ValueError):
43
+ pass
44
+
45
+
46
+ def opt_text(name, desc):
47
+ return name if not desc else f"{name}: {desc}"
48
+
49
+
50
+ class DecisionEncoder(nn.Module):
51
+ def __init__(self, cfg, proj_dim=256):
52
+ super().__init__()
53
+ from transformers import AutoModel
54
+ self.encoder = AutoModel.from_config(cfg, trust_remote_code=True, attn_implementation="sdpa", dtype=torch.float32)
55
+ h = cfg.hidden_size
56
+ self.norm = nn.LayerNorm(h)
57
+ self.w_o, self.w_q, self.w_p = nn.Linear(h, proj_dim), nn.Linear(h, proj_dim), nn.Linear(h, proj_dim)
58
+ self.log_tau = nn.Parameter(torch.tensor(math.log(0.05)))
59
+ self.cls_mlp = nn.Sequential(nn.Linear(h, 2 * h), nn.ReLU(), nn.Dropout(0.1), nn.Linear(2 * h, 1))
60
+
61
+ @classmethod
62
+ def load(cls, path, device=None, max_len=32768, token_budget=65536):
63
+ from safetensors.torch import load_file
64
+ from transformers import AutoConfig, AutoTokenizer
65
+ path = Path(path); device = device or ("cuda" if torch.cuda.is_available() else "cpu")
66
+ cfg = AutoConfig.from_pretrained(str(path), trust_remote_code=True)
67
+ m = cls(cfg, cfg.decision["proj_dim"])
68
+ m.load_state_dict(load_file(str(path / "model.safetensors")), strict=True)
69
+ m = m.to(device).eval()
70
+ # text is tokenised with the base UltraBERT tokenizer (as in training); the 8 marker tokens are the rows appended after it
71
+ m.tok = AutoTokenizer.from_pretrained(str(path), trust_remote_code=True)
72
+ m.mk = {t: int(cfg.decision["marker_ids"][t]) for t in MARKERS}
73
+ assert len(m.tok) == cfg.decision["n_vocab_base"] == min(m.mk.values()), "tokenizer / marker mismatch"
74
+ m.device, m.max_len, m.budget = device, int(max_len), int(token_budget)
75
+ return m
76
+
77
+ def _ids(self, s):
78
+ return self.tok(s, add_special_tokens=False)["input_ids"] if s else []
79
+
80
+ def encode(self, state, q, state_ids=None):
81
+ """-> dict(ids, q_pos, opt_pos, names, pool) for one question, or raise Unsupported."""
82
+ qq = to_row("q", state, q)["questions"][0]; st = to_row("q", state, q)["parts"][0]["text"]
83
+ ids = [self.tok.bos_token_id, self.mk["[Q]"]] + self._ids(qq["text"]); opt_pos, names = [], []
84
+ for n, d in qq["options"].items():
85
+ opt_pos.append(len(ids)); names.append(n); ids += [self.mk["[O]"]] + self._ids(opt_text(n, d))
86
+ ids.append(self.mk["[SEP_SCHEMA]"]); ps = len(ids)
87
+ ids += [self.mk["[SEG_user]"]] + (state_ids if state_ids is not None else self._ids(st)); pe = len(ids); ids.append(self.tok.eos_token_id)
88
+ if len(ids) > self.max_len:
89
+ raise Unsupported(f"input longer than the {self.max_len}-token context")
90
+ return dict(ids=ids, q_pos=1, opt_pos=opt_pos, names=names, pool=(ps, pe))
91
+
92
+ def _logits(self, H, recs):
93
+ H = H.float(); dev = H.device
94
+ ob = torch.tensor([b for b, r in enumerate(recs) for _ in r["opt_pos"]], device=dev)
95
+ op = torch.tensor([p for r in recs for p in r["opt_pos"]], device=dev)
96
+ own = torch.tensor([k for k, r in enumerate(recs) for _ in r["opt_pos"]], device=dev)
97
+ b = torch.arange(len(recs), device=dev)
98
+ ps = torch.tensor([r["pool"][0] for r in recs], device=dev); pe = torch.tensor([r["pool"][1] for r in recs], device=dev)
99
+ cs = nn.functional.pad(H.cumsum(1), (0, 0, 1, 0))
100
+ pooled = (cs[b, pe] - cs[b, ps]) / (pe - ps).clamp(min=1).unsqueeze(-1).float()
101
+ v = nn.functional.normalize(self.w_p(self.norm(pooled)), dim=-1)
102
+ uq = self.w_q(self.norm(H[b, torch.tensor([r["q_pos"] for r in recs], device=dev)]))
103
+ u = nn.functional.normalize(self.w_o(self.norm(H[ob, op])) + uq[own], dim=-1)
104
+ lg = (u * v[own]).sum(-1) / self.log_tau.exp() + self.cls_mlp(H[ob, op]).squeeze(-1)
105
+ return list(torch.split(lg, [len(r["opt_pos"]) for r in recs]))
106
+
107
+ @torch.no_grad()
108
+ def forward_recs(self, recs):
109
+ """Batched by length under a token budget (as the evaluated engine); bf16 autocast on CUDA. -> list of prob arrays."""
110
+ out = [None] * len(recs); order = sorted(range(len(recs)), key=lambda i: len(recs[i]["ids"])); i = 0
111
+ amp = torch.autocast("cuda", dtype=torch.bfloat16, enabled=self.device == "cuda")
112
+ while i < len(order):
113
+ j = i + 1
114
+ while j < len(order) and len(recs[order[j]]["ids"]) * (j - i + 1) <= self.budget:
115
+ j += 1
116
+ grp = [recs[k] for k in order[i:j]]; w = max(len(r["ids"]) for r in grp)
117
+ x = torch.full((len(grp), w), self.tok.pad_token_id, dtype=torch.long); msk = torch.zeros_like(x)
118
+ for r_, r in enumerate(grp):
119
+ x[r_, :len(r["ids"])] = torch.tensor(r["ids"]); msk[r_, :len(r["ids"])] = 1
120
+ with amp:
121
+ H = self.encoder(input_ids=x.to(self.device), attention_mask=msk.to(self.device)).last_hidden_state
122
+ for k, lg in zip(order[i:j], self._logits(H, grp)):
123
+ z = lg.double().cpu().numpy(); p = np.exp(z - z.max()); out[k] = p / p.sum()
124
+ i = j
125
+ return out
126
+
127
+ def predict(self, state, questions):
128
+ """questions: {key: {type: choice | noul, instructions, criteria}} -> {key: answer} (choice: choice + probabilities; noul: p(yes))."""
129
+ recs, keys, st = [], [], None
130
+ for k, q in questions.items():
131
+ if q["type"] not in ("choice", "noul"):
132
+ raise Unsupported("Unsupported question type " + str(q["type"]))
133
+ if st is None:
134
+ st = self._ids(to_row("q", state, q)["parts"][0]["text"])
135
+ recs.append(self.encode(state, q, st)); keys.append(k)
136
+ ans = {}
137
+ for k, r, p in zip(keys, recs, self.forward_recs(recs)):
138
+ if questions[k]["type"] == "noul":
139
+ ans[k] = {"type": "noul", "noul": float(p[r["names"].index("yes")])}
140
+ else:
141
+ pr = {n: float(v) for n, v in zip(r["names"], p)}
142
+ ans[k] = {"type": "choice", "choice": max(pr, key=pr.get), "probabilities": pr}
143
+ return ans, sum(len(r["ids"]) for r in recs)
144
+
145
+
146
+ # =====================================================================================================================
147
+ # vela3-fast: decisions (the preview's DecisionEncoder, unchanged) + gated span / router adapters
148
+ # =====================================================================================================================
149
+ import re as _re
150
+
151
+ ROLES = ("user", "context", "answer")
152
+ _REL_Q = _re.compile(r"\bspans? (?:are|is) the .+ (?:of|for)\b|\brelat(?:ed|ion|ions|es|ing)?\b|\b(?:head|tail)\b|\bstands? in\b"
153
+ r"|\bwith respect to\b|\bcounterpart\b|\bsuch that\b|\brole of\b")
154
+ _EV_Q = _re.compile(r"\b(?:evidence|support(?:s|ing|ed)?|cite[sd]?|citations?)\b")
155
+
156
+
157
+ def _norm(s):
158
+ return " ".join(str(s or "").split())
159
+
160
+
161
+ def _parts(state):
162
+ """System One state -> [(role, text)]: a string is the user part; an object of text parts uses the roles user / context / answer."""
163
+ if isinstance(state, str):
164
+ return [("user", state)]
165
+ if isinstance(state, dict) and state and all(isinstance(v, str) for v in state.values()):
166
+ bad = [k for k in state if k not in ROLES]
167
+ if bad:
168
+ raise ValueError(f"span / router state parts must be named {ROLES}, got {bad}")
169
+ return list(state.items())
170
+ raise ValueError("span and router questions need a text state or an object of text parts {user | context | answer: text}")
171
+
172
+
173
+ class Vela3Encoder:
174
+ """vela3-fast. system_one(state, questions): choice / noul (decision backbone), router choice / set (router adapter), span
175
+ (span adapter). predict(state, questions): the preview's decision API (decision backbone only)."""
176
+
177
+ def __init__(self, path, device=None, max_len=32768, token_budget=65536, adapter_bf16=False, entity_route=None):
178
+ """adapter_bf16: run the span / router passes under bf16 autocast (default fp32, as evaluated). Decisions: unchanged (bf16 autocast on GPU)."""
179
+ import vela3_schema as VS
180
+ path = Path(path)
181
+ self.decision = DecisionEncoder.load(path, device=device, max_len=max_len, token_budget=token_budget)
182
+ dev = self.decision.device
183
+ self.cfg = json.loads((path / "vela3_config.json").read_text())
184
+ rq = json.loads((path / "router_questions.json").read_text())["questions"]
185
+ self.router_q = {_norm(t): s for t, s in rq.items()}
186
+ span_net = VS.build_adapter(self.decision, path / "span_adapter.safetensors", dev)
187
+ self.span = VS.SchemaEngine(path, span_net, dev, amp_bf16=adapter_bf16)
188
+ ev_len = int(self.cfg["span"]["evidence"].get("max_len", self.span.max_len)) # EV-FIX: evidence engine, same net (no extra weights)
189
+ evf = self.cfg["span"]["evidence"].get("adapter") # EVFAST: optional dedicated evidence adapter (evidence questions only; missing file = off)
190
+ ev_net = VS.build_adapter(self.decision, path / evf, dev) if evf and (path / evf).exists() else span_net
191
+ self.span_ev = self.span if (ev_len == self.span.max_len and ev_net is span_net) else VS.SchemaEngine(path, ev_net, dev, tokenizer=self.span.tok, max_len=ev_len,
192
+ token_budget=max(ev_len, 32768), amp_bf16=adapter_bf16)
193
+ self.task = {} # per-task span adapters (span.task_adapters: {task: file}); a missing file = route off
194
+ for t, f in (self.cfg["span"].get("task_adapters") or {}).items():
195
+ if (path / f).exists():
196
+ self.task[t] = VS.SchemaEngine(path, VS.build_adapter(self.decision, path / f, dev), dev, tokenizer=self.span.tok, amp_bf16=adapter_bf16)
197
+ # entity route for names-only open-label entity questions: "ner" (the NER adapter, default) or "span" (the span adapter). The
198
+ # end-to-end relation pipeline (entity step, then relation questions) runs with "span" (span.entity_route_relation_pipeline):
199
+ # set VELA3_ENTITY_ROUTE=span, or Vela3Encoder.load(..., entity_route="span"), for that pipeline.
200
+ import os as _os
201
+ self.entity_route = entity_route or _os.environ.get("VELA3_ENTITY_ROUTE") or self.cfg["span"].get("entity_route", "ner")
202
+ # R2c: a second span adapter for the router label sets (span.set_adapter: {file, label_sets, router_set_temperature,
203
+ # thresholds_by_set, pii_buckets}): halu and PII questions are answered by it with its own dev-picked temperature / thresholds
204
+ ss = self.cfg["span"].get("set_adapter"); self.span_set = None
205
+ if ss and (path / ss["file"]).exists():
206
+ self.span_set = VS.SchemaEngine(path, VS.build_adapter(self.decision, path / ss["file"], dev), dev, tokenizer=self.span.tok, amp_bf16=adapter_bf16)
207
+ self.router = VS.SchemaEngine(path, VS.build_adapter(self.decision, path / "router_adapter.safetensors", dev), dev, tokenizer=self.span.tok, amp_bf16=adapter_bf16)
208
+ # DOM04B: optional per-task router adapters (vela3_config.json router.task_adapters: {task: {file, ids}}): a router question whose
209
+ # trained schema id is in ids is answered by that adapter; a missing file = route off (the shared router adapter answers)
210
+ self.router_task = {}
211
+ for t, ta in (self.cfg["router"].get("task_adapters") or {}).items():
212
+ files = ta.get("files") or [ta["file"]] # several files = logit average of the adapters (an ensemble entry)
213
+ if all((path / f).exists() for f in files):
214
+ engs = [VS.SchemaEngine(path, VS.build_adapter(self.decision, path / f, dev), dev, tokenizer=self.span.tok, amp_bf16=adapter_bf16) for f in files]
215
+ for i in ta["ids"]:
216
+ self.router_task[i] = (t, engs)
217
+ self._VS = VS
218
+ self.name = self.cfg["name"]
219
+
220
+ @classmethod
221
+ def load(cls, path, **kw):
222
+ return cls(path, **kw)
223
+
224
+ # ------------------------------------------------------------------ decisions (the preview, unchanged)
225
+ def predict(self, state, questions):
226
+ return self.decision.predict(state, questions)
227
+
228
+ # ------------------------------------------------------------------ router questions
229
+ def _router_answers(self, state, qs):
230
+ textual = isinstance(state, str) or (isinstance(state, dict) and state and all(isinstance(v, str) for v in state.values()) and set(state) <= set(ROLES))
231
+ parts = _parts(state) if textual else [("user", json.dumps(state, ensure_ascii=False, separators=(",", ":")))] # JSON state: compact JSON
232
+ roles = [r for r, _ in parts]; rows = {}
233
+ for k, q in qs.items():
234
+ s = self.router_q[_norm(q.get("instructions"))]
235
+ crit = q.get("criteria") or {}
236
+ if isinstance(crit, (list, tuple)):
237
+ crit = {str(c): None for c in crit}
238
+ opts = {str(n): (str(d) if d else (s["options"] or {}).get(str(n), "")) for n, d in crit.items()} or dict(s["options"])
239
+ over = q.get("over") or (s["over"] if s["over"] in roles else roles[-1])
240
+ rows.setdefault((over, s["id"] if s["id"] in self.router_task else None), []).append(dict(id=k, type=s["type"], over=over, text=q["instructions"], options=opts, abstain=bool(s["abstain"])))
241
+ out, n_tok = {}, 0
242
+ for (over, task), gq in rows.items():
243
+ engs = self.router_task[task][1] if task else [self.router]; head = f"router:{self.router_task[task][0]}" if task else "router"
244
+ raws = [e.predict_raw([dict(parts=[dict(role=r, text=t) for r, t in parts], questions=gq)])[0] for e in engs]; raw = raws[0]
245
+ if len(raws) > 1: # logit average over the ensemble's adapters (same questions, same option order)
246
+ for qi, q in enumerate(raw["qs"]):
247
+ q["logits"] = list(np.mean([np.asarray(r_["qs"][qi]["logits"], np.float64) for r_ in raws], axis=0))
248
+ n_tok += raw["n_input"]
249
+ for q in raw["qs"]:
250
+ lg = np.asarray(q["logits"], np.float64); n = len(q["names"])
251
+ if q["qtype"] == "set":
252
+ p = 1 / (1 + np.exp(-lg[:n])); thr = float(self.cfg["router"]["set_threshold"])
253
+ pr = {nm: float(v) for nm, v in zip(q["names"], p)}
254
+ out[q["qid"]] = {"type": "set", "selected": [nm for nm, v in pr.items() if v > thr], "probabilities": pr, "threshold": thr, "head": head}
255
+ else:
256
+ z = lg[:n]; p = np.exp(z - z.max()); p /= p.sum(); pr = {nm: float(v) for nm, v in zip(q["names"], p)}
257
+ out[q["qid"]] = {"type": "choice", "choice": max(pr, key=pr.get), "probabilities": pr, "head": head}
258
+ return out, n_tok
259
+
260
+ # ------------------------------------------------------------------ span questions
261
+ def _label_set(self, names):
262
+ sp = self.cfg["span"]
263
+ for k, ls in sp["router_label_sets"].items():
264
+ if names and set(names) <= set(ls):
265
+ return k
266
+ if names and {n.strip().lower() for n in names} <= {x.lower() for x in sp["evidence"]["labels"]}:
267
+ return "evidence"
268
+ return None
269
+
270
+ def span_answer(self, state, q):
271
+ VS = self._VS; sp = self.cfg["span"]
272
+ parts = _parts(state); roles = [r for r, _ in parts]
273
+ target = q.get("target") or q.get("over") or ("answer" if "answer" in roles else roles[-1])
274
+ if target not in roles:
275
+ raise ValueError(f"target {target!r} is not a part of the state")
276
+ crit = q.get("criteria") or q.get("labels")
277
+ if isinstance(crit, dict):
278
+ labels = [(str(k), "" if v is None else str(v)) for k, v in crit.items()]
279
+ elif isinstance(crit, (list, tuple)):
280
+ labels = [(str(k), "") for k in crit]
281
+ else:
282
+ raise ValueError("span questions need criteria: {label: description or null} or a list of labels")
283
+ names = [n for n, _ in labels]
284
+ if not names or len(set(names)) != len(names):
285
+ raise ValueError("span labels must be distinct and at least one")
286
+ lset = self._label_set(names); question = q.get("instructions")
287
+ if lset in sp["schemas"]: # a trained router label set: its question text and label descriptions fill what the request leaves empty
288
+ sch = sp["schemas"][lset]; labels = [(n, d or sch["labels"].get(n, "")) for n, d in labels]; question = question or sch["question"]
289
+ if lset == "evidence":
290
+ question = question or sp["evidence"]["question"]
291
+ question = question or sp["default_question"]
292
+ row = dict(parts=[dict(role=r, text=t) for r, t in parts], questions=[dict(id="q", type="span", over=target, text=question, labels=dict(labels))])
293
+ evq = lset == "evidence" or (lset not in ("pii", "halu", "toxic") and bool(_EV_Q.search(_norm(question).lower())))
294
+ eng, head = (self.span_ev if evq else self.span), "span" # EV-FIX: evidence questions in one long window
295
+ nq = _norm(question).lower(); names_only = not any(d for _, d in labels)
296
+ if lset is None and not evq: # task routes: relation questions -> the relation adapter; names-only entity questions -> ner (when shipped)
297
+ if _REL_Q.search(nq):
298
+ if "relation" in self.task:
299
+ eng, head = self.task["relation"], "relation"
300
+ elif names_only and "ner" in self.task and self.entity_route == "ner":
301
+ eng, head = self.task["ner"], "ner"
302
+ ss = sp.get("set_adapter")
303
+ if ss and self.span_set is not None and lset in ss["label_sets"]: # R2c: router label sets on the set adapter, with its thresholds
304
+ eng, head = self.span_set, "span_set"
305
+ sp = dict(sp, router_set_temperature=ss["router_set_temperature"], thresholds_by_set=dict(sp["thresholds_by_set"], **ss["thresholds_by_set"]), pii_buckets=ss["pii_buckets"])
306
+ raw = eng.predict_raw([row])[0]
307
+ n_tok = raw["n_tokens"][target]
308
+ self.span.last = eng.last = dict(target_tokens=int(n_tok), windows=max(1, raw["windows"]), prompt_tokens=[int(raw["n_input"])])
309
+ # threshold and temperature: the dev picks of this checkpoint (vela3_config.json span.threshold_sources)
310
+ if lset == "pii":
311
+ b = next(b for b in sp["pii_buckets"] if n_tok <= b["max_tokens"]); thr0, T = b["threshold"], sp["router_set_temperature"]
312
+ why = f"pii label set, {b['name']} bucket ({n_tok} target tokens)"
313
+ elif lset in ("halu", "toxic"):
314
+ thr0, T, why = sp["thresholds_by_set"][lset], sp["router_set_temperature"], f"{lset} label set"
315
+ elif evq:
316
+ bs = sp["evidence"].get("buckets")
317
+ if bs: # EV-FIX: threshold by target length
318
+ b = next(b for b in bs if n_tok <= b["max_tokens"]); thr0, T, why = b["threshold"], 1.0, f"evidence question, {b['name']} bucket ({n_tok} target tokens)"
319
+ else:
320
+ thr0, T, why = sp["evidence"]["threshold"], 1.0, "evidence question"
321
+ elif head == "relation": # per-form dev picks: one relation (pair) / several (multi)
322
+ thr0 = sp["relation"]["threshold_pair" if len(labels) == 1 else "threshold_multi"]; T, why = 1.0, f"relation question ({'pair' if len(labels) == 1 else 'multi'})"
323
+ elif _REL_Q.search(nq):
324
+ thr0, T, why = sp["relation_threshold"], 1.0, "relation question"
325
+ elif head == "ner":
326
+ thr0, T, why = sp["ner"]["threshold"], 1.0, "open labels, names only"
327
+ else:
328
+ thr0, T, why = sp["threshold"], 1.0, "open labels"
329
+ thr = float(q.get("threshold", thr0)); text = dict(parts)[target]
330
+ S = raw["span"]; spans = []
331
+ if S is not None and len(S["offs"]):
332
+ p = VS._sigmoid(S["logits"] / T); wo = S["offs"]
333
+ spans = VS.decode_spans(p, wo, S["names"], text, thr)
334
+ for s in spans:
335
+ k = S["names"].index(s["label"]); m = (wo[:, 0] < s["end"]) & (wo[:, 1] > s["start"])
336
+ s["text"] = text[s["start"]:s["end"]]; s["score"] = float(p[m, k].mean()) if m.any() else 0.0
337
+ return {"type": "span", "target": target, "spans": spans, "head": head, "head_reason": f"{head} adapter; {why}", "threshold": thr}, raw["n_input"]
338
+
339
+ # ------------------------------------------------------------------ System One
340
+ def system_one(self, state, questions, model=None):
341
+ """questions {qid: question} -> {"model", "answers": {qid: answer}, "usage"}. Choice / noul: the decision backbone (the
342
+ preview's answers); choice / set whose instructions are a router text: the router adapter; span: the span adapter.
343
+ A question that cannot be answered gets {"type", "error", "message"}; the others are still answered."""
344
+ dec, rout, span, answers, n = {}, {}, {}, {}, 0
345
+ for k, q in questions.items():
346
+ t = q.get("type") if isinstance(q, dict) else None
347
+ if t == "span":
348
+ span[k] = q
349
+ elif t in ("choice", "set") and _norm(q.get("instructions")) in self.router_q:
350
+ if self.router_q[_norm(q.get("instructions"))]["type"] != t:
351
+ answers[k] = {"type": t, "error": "invalid_question", "message": "router question asked with another type than trained"}
352
+ else:
353
+ rout[k] = q
354
+ elif t in ("choice", "noul"):
355
+ dec[k] = q
356
+ else:
357
+ answers[k] = {"type": t, "error": "invalid_question", "message": f"unsupported question type {t!r} (choice, noul, span; set for router questions)"}
358
+ if dec:
359
+ try:
360
+ a, m = self.decision.predict(state, dec); answers.update(a); n += m
361
+ except Unsupported as e:
362
+ answers.update({k: {"type": q["type"], "error": "unsupported", "message": str(e)} for k, q in dec.items()})
363
+ if rout:
364
+ try:
365
+ a, m = self._router_answers(state, rout); answers.update(a); n += m
366
+ except ValueError as e:
367
+ answers.update({k: {"type": q["type"], "error": "invalid_question", "message": str(e)} for k, q in rout.items()})
368
+ for k, q in span.items():
369
+ try:
370
+ a, m = self.span_answer(state, q); answers[k] = a; n += m
371
+ except ValueError as e:
372
+ answers[k] = {"type": "span", "error": "invalid_question", "message": str(e)}
373
+ return {"model": "vllm-sr/" + self.name, "answers": {k: answers[k] for k in questions}, "usage": {"input_tokens": int(n), "output_tokens": 0}}
upstream/vela3_schema.py ADDED
@@ -0,0 +1,604 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """vela3_schema.py (vela3-fast): the span and router passes.
2
+
3
+ Sequence layout, word units, truncation, 8,192-token windows with 512 overlap, window aggregation and the span decoder are the
4
+ Vela 2.0 research scorer's (score_schema_v2 + train_schema_generic eval assembly + schema_lib_r4 word units + span_decode_r4
5
+ decode_v2), copied verbatim from the public Vela 2.0 0.3B runtime (vllm-sr/Vela-2.0-0.3B vela2_inference.py, Apache-2.0):
6
+ <bos> ([Q] q ([O] name: desc)* [ABS]?)* ([E] label: desc)* [SEP_SCHEMA] ([SEG_role] part)* <eos>
7
+ Only the network differs: UltraBERT-380M with a LoRA adapter (SchemaNet below), frozen weights shared with the decision backbone."""
8
+ import json
9
+ import math
10
+ import random
11
+ import re
12
+ from collections import defaultdict
13
+ from pathlib import Path
14
+
15
+ import numpy as np
16
+
17
+ # =====================================================================================================================
18
+ # word units (schema_lib_r4._WORD, GLiNER2 WhitespaceTokenSplitter + CJK char level, r4 URL rule)
19
+ # =====================================================================================================================
20
+ _CJK = ("⺀-⿿ -〿぀-ヿ㄀-ㇿ㐀-䶿一-鿿ꀀ-꓏"
21
+ "가-힯豈-﫿︰-﹏＀-￯")
22
+ _TRAIL = ".,;:!?)\\]}>\"'”’»"
23
+ _WORD = re.compile(rf"""(?:https?://|www\.)[^\s{_CJK}]+?(?=[{_TRAIL}]*(?![^\s{_CJK}]))
24
+ |[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{{2,}}
25
+ |@[a-z0-9_]+
26
+ |[{_CJK}]
27
+ |[^\W{_CJK}]+(?:[-_][^\W{_CJK}]+)*
28
+ |\S""", re.VERBOSE | re.IGNORECASE)
29
+
30
+
31
+ def split_words(text):
32
+ return [(m.start(), m.end()) for m in _WORD.finditer(text)]
33
+
34
+
35
+ def word_first_tokens(text, offs):
36
+ """(word char offsets (W, 2), index of each word's first overlapping sub-word token (W,)) (schema_lib_r4)."""
37
+ w = split_words(text)
38
+ if not w or offs is None or len(offs) == 0:
39
+ return np.zeros((0, 2), np.int32), np.zeros(0, np.int32)
40
+ offs = np.asarray(offs)
41
+ st, en = offs[:, 0], offs[:, 1]
42
+ valid = en > st
43
+ ends = np.where(valid, en, -1)
44
+ wo, ft = [], []
45
+ cummax_end = np.maximum.accumulate(ends)
46
+ for a, b in w:
47
+ t = int(np.searchsorted(cummax_end, a, side="right"))
48
+ while t < len(offs) and not valid[t]:
49
+ t += 1
50
+ if t < len(offs) and st[t] < b:
51
+ wo.append((a, b)); ft.append(t)
52
+ return np.asarray(wo, np.int32).reshape(-1, 2), np.asarray(ft, np.int32)
53
+
54
+
55
+ # =====================================================================================================================
56
+ # span decoder (span_decode_r4.decode_v2; word readout -> extend=False)
57
+ # =====================================================================================================================
58
+ _UBODY = rf"[^\s\]\)\}}>「」『』\"'“”{_CJK}]"
59
+ _UNIT = re.compile(rf"(?:https?://|www\.){_UBODY}+?(?=[.,;:!?]*(?!{_UBODY}))"
60
+ rf"|(?:(?![{_CJK}])[^\W_]|[@._\-+])+"
61
+ rf"|\S")
62
+ _ALNUM = re.compile(r"[^\W_]")
63
+ EDGE = set("[](){}<>「」『』【】《》〈〉\"'“”‘’«»‹›")
64
+ _URL_START = re.compile(r"(?:https?://|www\.)", re.IGNORECASE)
65
+ _CJK_RE = re.compile(rf"[{_CJK}]")
66
+ URL_TRAIL = set(".,;:!?)")
67
+
68
+
69
+ def _units(text):
70
+ u = np.full(len(text) + 1, -1, dtype=np.int64)
71
+ for k, m in enumerate(_UNIT.finditer(text)):
72
+ u[m.start():m.end()] = k
73
+ return u
74
+
75
+
76
+ def _first_nonspace(text, a, b):
77
+ while a < b and text[a].isspace():
78
+ a += 1
79
+ return a
80
+
81
+
82
+ def _trim_edges(text, s, e):
83
+ while s < e and (text[s].isspace() or text[s] in EDGE):
84
+ s += 1
85
+ while e > s and (text[e - 1].isspace() or text[e - 1] in EDGE):
86
+ e -= 1
87
+ return s, e
88
+
89
+
90
+ def _trim_url(text, s, e):
91
+ if not _URL_START.match(text, s):
92
+ return s, e
93
+ m = _CJK_RE.search(text, s, e)
94
+ if m:
95
+ e = m.start()
96
+ while e > s and (text[e - 1] in URL_TRAIL or text[e - 1] in EDGE or text[e - 1].isspace()):
97
+ e -= 1
98
+ return s, e
99
+
100
+
101
+ def _trim(text, s, e):
102
+ s, e = _trim_edges(text, s, e)
103
+ return _trim_url(text, s, e)
104
+
105
+
106
+ def decode_spans(probs, offs, names, text, thr, fill=True, extend=False, unit_vote=True):
107
+ """span_decode_r4.decode_v2 with the scorer's word-readout arguments (extend=False, trim_edges=True, no bridge)."""
108
+ probs = np.asarray(probs, dtype=np.float32); offs = np.asarray(offs)
109
+ T = len(offs)
110
+ if T == 0:
111
+ return []
112
+ valid = offs[:, 1] > offs[:, 0]
113
+ k = probs.argmax(1); pk = probs[np.arange(T), k]
114
+ lab = np.where(valid & (pk > thr), k, -1)
115
+ u = _units(text)
116
+ tu = np.full(T, -1, dtype=np.int64)
117
+ alnum = np.zeros(T, dtype=bool)
118
+ for t in range(T):
119
+ if not valid[t]:
120
+ continue
121
+ a, b = int(offs[t, 0]), int(offs[t, 1])
122
+ f = _first_nonspace(text, a, b)
123
+ tu[t] = u[f] if f < b and f < len(text) else -1
124
+ alnum[t] = bool(_ALNUM.search(text[a:b]))
125
+ if unit_vote or fill or extend:
126
+ t = 0
127
+ while t < T:
128
+ if tu[t] < 0:
129
+ t += 1; continue
130
+ t2 = t
131
+ while t2 + 1 < T and (tu[t2 + 1] == tu[t] or not valid[t2 + 1]):
132
+ t2 += 1
133
+ idx = [i for i in range(t, t2 + 1) if valid[i]]
134
+ L = [i for i in idx if lab[i] >= 0]
135
+ if L:
136
+ if unit_vote and len({int(lab[i]) for i in L}) > 1:
137
+ sc = {}
138
+ for i in L:
139
+ sc[int(lab[i])] = sc.get(int(lab[i]), 0.0) + float(pk[i])
140
+ w = max(sc, key=sc.get)
141
+ for i in L:
142
+ lab[i] = w
143
+ if fill:
144
+ for c in set(int(lab[i]) for i in L):
145
+ pos = [i for i in L if lab[i] == c]
146
+ for i in idx:
147
+ if pos[0] < i < pos[-1] and lab[i] < 0:
148
+ lab[i] = c
149
+ if extend:
150
+ for c in set(int(lab[i]) for i in idx if lab[i] >= 0):
151
+ pos = [idx.index(i) for i in idx if lab[i] == c]
152
+ if extend == "unit":
153
+ an = [j for j, i in enumerate(idx) if alnum[i]]
154
+ lo, hi = min([pos[0]] + an[:1]), max([pos[-1]] + an[-1:])
155
+ if all(lab[idx[j]] < 0 or lab[idx[j]] == c for j in range(lo, hi + 1)):
156
+ for j in range(lo, hi + 1):
157
+ lab[idx[j]] = c
158
+ else:
159
+ j = pos[0] - 1
160
+ while j >= 0 and lab[idx[j]] < 0 and alnum[idx[j]]:
161
+ lab[idx[j]] = c; j -= 1
162
+ j = pos[-1] + 1
163
+ while j < len(idx) and lab[idx[j]] < 0 and alnum[idx[j]]:
164
+ lab[idx[j]] = c; j += 1
165
+ t = t2 + 1
166
+ spans, cur = [], None
167
+ for t in range(T):
168
+ if not valid[t]:
169
+ continue
170
+ c = int(lab[t])
171
+ if cur is not None and c == cur[0]:
172
+ cur[2] = int(offs[t, 1]); cur[3].append(t); continue
173
+ if cur is not None:
174
+ spans.append(cur)
175
+ cur = [c, int(offs[t, 0]), int(offs[t, 1]), [t]] if c >= 0 else None
176
+ if cur is not None:
177
+ spans.append(cur)
178
+ res = []
179
+ for c, s, e, ts in spans:
180
+ s, e = _trim(text, s, e)
181
+ if e <= s:
182
+ continue
183
+ res.append(dict(start=s, end=e, label=names[c], probability=float(np.mean(probs[ts, c]))))
184
+ return res
185
+
186
+
187
+ # =====================================================================================================================
188
+ # sequence assembly (schema_lib.assemble, eval path: cap_schema=False)
189
+ # =====================================================================================================================
190
+ def assemble(mk, bos, eos, questions, elabels, segments, max_len, protected, shrink, prompt_floor=64):
191
+ qs = [dict(q, opts=list(q["opts"])) for q in questions]
192
+ seg = [(r, list(t)) for r, t in segments]
193
+ fixed = 2 + 1 + len(seg)
194
+ elabels = list(elabels)
195
+ tr = {"shrink_cut": 0, "protected_cut": 0}
196
+
197
+ def over():
198
+ return fixed + sum(q["len"] for q in qs) + sum(e["len"] for e in elabels) + sum(len(t) for _, t in seg) - max_len
199
+ si = next((i for i, (r, _) in enumerate(seg) if r == shrink), None)
200
+ if over() > 0 and si is not None:
201
+ keep = max(min(len(seg[si][1]), prompt_floor), len(seg[si][1]) - over())
202
+ tr["shrink_cut"] += len(seg[si][1]) - keep
203
+ seg[si] = (seg[si][0], seg[si][1][:keep])
204
+ if over() > 0 and si is not None:
205
+ keep = max(1, len(seg[si][1]) - over())
206
+ tr["shrink_cut"] += len(seg[si][1]) - keep
207
+ seg[si] = (seg[si][0], seg[si][1][:keep])
208
+ if over() > 0:
209
+ for i, (r, t) in enumerate(seg):
210
+ if r in protected and over() > 0:
211
+ keep = max(1, len(t) - over())
212
+ tr["protected_cut"] += len(t) - keep
213
+ seg[i] = (r, t[:keep])
214
+ if over() > 0:
215
+ raise ValueError(f"schema alone does not fit max_length ({over()} tokens over)")
216
+ ids = [bos]
217
+ qrec, erec = [], []
218
+ for q in qs:
219
+ rec = dict(qid=q["qid"], type=q["type"], over=q["over"], q_pos=len(ids), opt_pos=[], opt_names=[], abs_pos=None)
220
+ ids.append(mk["[Q]"]); ids.extend(q["qtoks"])
221
+ for n, t in q["opts"]:
222
+ rec["opt_pos"].append(len(ids)); rec["opt_names"].append(n)
223
+ ids.append(mk["[O]"]); ids.extend(t)
224
+ if q["abstain"]:
225
+ rec["abs_pos"] = len(ids); ids.append(mk["[ABS]"])
226
+ qrec.append(rec)
227
+ for e in elabels:
228
+ erec.append(dict(name=e["name"], pos=len(ids)))
229
+ ids.append(mk["[E]"]); ids.extend(e["toks"])
230
+ ids.append(mk["[SEP_SCHEMA]"])
231
+ ranges = {}
232
+ for r, t in seg:
233
+ start = len(ids)
234
+ ids.append(mk[f"[SEG_{r}]"]); ids.extend(t)
235
+ ranges[r] = (start, len(ids), len(t))
236
+ ids.append(eos)
237
+ return dict(ids=ids, questions=qrec, elabels=erec, ranges=ranges, trunc=tr, seg_lens={r: len(t) for r, t in seg})
238
+
239
+
240
+ def _opt_text(name, desc):
241
+ return name if not desc else f"{name}: {desc}"
242
+
243
+
244
+ def _softmax(x):
245
+ x = np.asarray(x, dtype=np.float64); e = np.exp(x - x.max()); return e / e.sum()
246
+
247
+
248
+ def _sigmoid(x):
249
+ return 1 / (1 + np.exp(-np.asarray(x, dtype=np.float64)))
250
+
251
+
252
+
253
+
254
+ # =====================================================================================================================
255
+ # engine (Vela 2.0 runtime, verbatim; constructed by SchemaEngine below)
256
+ # =====================================================================================================================
257
+ class _Core:
258
+ PII_QUESTION = "Which spans are personal information?"
259
+
260
+ # ------------------------------------------------------------------ tokenisation
261
+ def _ids(self, s):
262
+ if s not in self._tc:
263
+ self._tc[s] = self.tok.encode(s, add_special_tokens=False).ids
264
+ return self._tc[s]
265
+
266
+ def _ids_offs(self, s):
267
+ e = self.tok.encode(s, add_special_tokens=False)
268
+ return np.asarray(e.ids, np.int32), np.asarray(e.offsets, np.int32).reshape(-1, 2)
269
+
270
+ # ------------------------------------------------------------------ generic contract -> internal row
271
+ def _prep(self, row):
272
+ """Generic-contract row {parts: [{role, text}], questions: [{id, type, over, text, options, levels, labels,
273
+ abstain}]} -> tokenised internal row (same fields as the research scorer's pool rows)."""
274
+ roles = [p["role"] for p in row["parts"]]
275
+ if len(set(roles)) != len(roles):
276
+ raise ValueError(f"one part per role, got {roles}")
277
+ span_roles = {q["over"] for q in row["questions"] if q["type"] == "span"}
278
+ if len([q for q in row["questions"] if q["type"] == "span"]) > 1:
279
+ raise ValueError("one span question per row (predict() splits requests with several)")
280
+ parts = []
281
+ for p in row["parts"]:
282
+ ids, offs = self._ids_offs(p["text"])
283
+ words = word_first_tokens(p["text"], offs) if p["role"] in span_roles else None
284
+ parts.append((p["role"], ids, offs if p["role"] in span_roles else None, words))
285
+ for q in row["questions"]:
286
+ for o in (q["over"] if isinstance(q["over"], list) else [q["over"]]):
287
+ if o not in roles:
288
+ raise ValueError(f"question {q.get('id')} is over '{o}' but the row has parts {roles}")
289
+ return dict(parts=parts, qs=row["questions"])
290
+
291
+ def _build_question(self, q):
292
+ typ = q["type"]; qtoks = self._ids(q["text"])
293
+ if typ == "span":
294
+ labels = q["labels"]
295
+ return "span", [dict(name=n, toks=self._ids(_opt_text(n, labels[n])), len=1 + len(self._ids(_opt_text(n, labels[n]))))
296
+ for n in labels]
297
+ opts = q.get("options") or {}
298
+ if typ == "score":
299
+ names = list(q["levels"]); abstain = False
300
+ elif typ == "set":
301
+ names = list(opts); abstain = False
302
+ elif typ == "choice":
303
+ names = list(opts); abstain = bool(q.get("abstain"))
304
+ else:
305
+ raise ValueError(typ)
306
+ ot = [(n, self._ids(_opt_text(n, opts.get(n, "")))) for n in names]
307
+ length = 1 + len(qtoks) + sum(1 + len(t) for _, t in ot) + (1 if abstain else 0)
308
+ return "q", dict(qid=q["id"], type="choice" if typ == "score" else typ, qtype=typ, over=q["over"], qtoks=qtoks,
309
+ opts=ot, abstain=abstain, len=length)
310
+
311
+ def _assemble(self, r):
312
+ qs, el, span_over = [], [], None
313
+ for q in r["qs"]:
314
+ kind, x = self._build_question(q)
315
+ if kind == "span":
316
+ el, span_over = x, q["over"]
317
+ else:
318
+ qs.append(x)
319
+ overs = set()
320
+ for q in qs:
321
+ overs |= set(q["over"] if isinstance(q["over"], list) else [q["over"]])
322
+ if span_over:
323
+ overs.add(span_over)
324
+ roles = [p[0] for p in r["parts"]]
325
+ shrink = next((x for x in roles if x not in overs), None)
326
+ rec = assemble(self.mk, self.bos, self.eos, qs, el, [(p[0], p[1]) for p in r["parts"]], self.max_len, overs, shrink)
327
+ R = rec["ranges"]
328
+ for q, orig in zip(rec["questions"], qs):
329
+ o = q["over"]
330
+ q["pool"] = (R[o[0]][0], R[o[-1]][1]) if isinstance(o, list) else (R[o][0], R[o][1])
331
+ q["qtype"] = orig["qtype"]
332
+ if span_over:
333
+ s, e, n = R[span_over]
334
+ part = next(p for p in r["parts"] if p[0] == span_over)
335
+ wo, ft = part[3]
336
+ keep = ft < n
337
+ rec.update(names=[x["name"] for x in rec["elabels"]], e_pos=[x["pos"] for x in rec["elabels"]],
338
+ w_offs=wo[keep], w_pos=(s + 1 + ft[keep]).astype(np.int64))
339
+ return rec
340
+
341
+ def _windows(self, r, rec):
342
+ span_over = next((q["over"] for q in r["qs"] if q["type"] == "span"), None)
343
+ overs = [q["over"] for q in r["qs"]]
344
+ role = span_over or (overs[0] if all(o == overs[0] for o in overs) and isinstance(overs[0], str) else None)
345
+ if role is None:
346
+ self.stats["cut_not_windowed"] += 1
347
+ return None
348
+ part = next(p for p in r["parts"] if p[0] == role)
349
+ N = len(part[1]); L = rec["seg_lens"][role]
350
+ if L >= N:
351
+ return None
352
+ ov = min(self.overlap, L // 4); stride = max(1, L - ov)
353
+ out = []
354
+ for a in range(0, max(1, N - ov), stride):
355
+ b = min(N, a + L)
356
+ words = gidx = None
357
+ if part[3] is not None:
358
+ wo, ft = part[3]; sel = np.nonzero((ft >= a) & (ft < b))[0]
359
+ words = (wo[sel], ft[sel] - a); gidx = sel
360
+ np_ = (role, part[1][a:b], None if part[2] is None else part[2][a:b], words)
361
+ out.append((dict(r, parts=[np_ if p[0] == role else p for p in r["parts"]]), (a, b), gidx))
362
+ if b >= N:
363
+ break
364
+ self.stats["windowed_rows"] += 1; self.stats["windows"] += len(out)
365
+ return out
366
+
367
+ def _forward(self, recs):
368
+ B = len(recs); W = max(len(r["ids"]) for r in recs)
369
+ x = np.full((B, W), self.pad, np.int64); m = np.zeros((B, W), np.int64)
370
+ qi, oi, ui, ei, qsz, spn = [], [], [], [], [], []
371
+ for b, r in enumerate(recs):
372
+ x[b, :len(r["ids"])] = r["ids"]; m[b, :len(r["ids"])] = 1
373
+ for q in r["questions"]:
374
+ pos = list(q["opt_pos"]) + ([q["abs_pos"]] if q["abs_pos"] is not None else [])
375
+ own = len(qi); qi.append((b, q["q_pos"], q["pool"][0], q["pool"][1]))
376
+ oi.extend((b, p, own) for p in pos); qsz.append(len(pos))
377
+ if "w_pos" in r:
378
+ k0, e0 = len(ui), len(ei)
379
+ ui.extend((b, int(p)) for p in r["w_pos"]); ei.extend((b, int(p)) for p in r["e_pos"])
380
+ spn.append((k0, len(ui), e0, len(ei)))
381
+ else:
382
+ spn.append(None)
383
+ nq, no, nu, ne = len(qi), len(oi), len(ui), len(ei)
384
+ # never feed an empty index tensor (a dummy row is added and dropped)
385
+ qa = np.asarray(qi or [(0, 0, 0, 1)], np.int64).reshape(-1, 4)
386
+ oa = np.asarray(oi or [(0, 0, 0)], np.int64).reshape(-1, 3)
387
+ ua = np.asarray(ui or [(0, 0)], np.int64).reshape(-1, 2)
388
+ ea = np.asarray(ei or [(0, 0)], np.int64).reshape(-1, 2)
389
+ lg, sp = self.run(x, m, qa, oa, ua, ea)
390
+ lg = lg[:no]; out = []; c = 0; qk = 0
391
+ for b, r in enumerate(recs):
392
+ qs = []
393
+ for q in r["questions"]:
394
+ n = qsz[qk]; qk += 1
395
+ qs.append(lg[c:c + n]); c += n
396
+ s = spn[b]
397
+ out.append(dict(qs=qs, span=None if s is None else sp[s[0]:s[1], s[2]:s[3]]))
398
+ return out
399
+
400
+ def predict_raw(self, rows):
401
+ """Generic-contract rows -> per row dict(qs=[dict(qid, qtype, names, logits (incl. [ABS] last if any),
402
+ has_abs)], span=dict(names, offs (word char offsets), logits (W, L)) | None, n_tokens, windows)."""
403
+ prepped = [self._prep(r) for r in rows]
404
+ jobs = []
405
+ for k, r in enumerate(prepped):
406
+ rec = self._assemble(r)
407
+ Wn = self._windows(r, rec) if rec["trunc"]["protected_cut"] else None
408
+ if not Wn:
409
+ if rec["trunc"]["protected_cut"]:
410
+ self.stats["labelled_cut"] += 1
411
+ jobs.append((k, None, None, rec))
412
+ else:
413
+ for r2, ab, gidx in Wn:
414
+ jobs.append((k, ab, gidx, self._assemble(r2)))
415
+ outs = [None] * len(jobs)
416
+ order = sorted(range(len(jobs)), key=lambda j: len(jobs[j][3]["ids"]))
417
+ cur = []
418
+
419
+ def flush(js):
420
+ for j, o in zip(js, self._forward([jobs[j][3] for j in js])):
421
+ outs[j] = o
422
+ for j in order:
423
+ w = max([len(jobs[i][3]["ids"]) for i in cur] + [len(jobs[j][3]["ids"])])
424
+ if cur and (len(cur) + 1 > self.bs or w * (len(cur) + 1) > self.budget):
425
+ flush(cur); cur = []
426
+ cur.append(j)
427
+ if cur:
428
+ flush(cur)
429
+ per = defaultdict(list)
430
+ for (k, ab, gidx, rec), o in zip(jobs, outs):
431
+ per[k].append((ab, gidx, rec, o))
432
+ final = []
433
+ for k, r in enumerate(prepped):
434
+ lst = per[k]; rec0 = lst[0][2]
435
+ qs = []
436
+ for qi, q in enumerate(rec0["questions"]):
437
+ L = np.stack([o["qs"][qi] for _, _, _, o in lst])
438
+ agg = L.max(0) if q["qtype"] == "set" else L.mean(0)
439
+ qs.append(dict(qid=q["qid"], qtype=q["qtype"], names=q["opt_names"], logits=agg, has_abs=q["abs_pos"] is not None))
440
+ span = None
441
+ if "w_pos" in rec0:
442
+ names = rec0["names"]
443
+ if len(lst) == 1 and lst[0][0] is None:
444
+ span = dict(names=names, offs=np.asarray(rec0["w_offs"]), logits=lst[0][3]["span"].astype(np.float64))
445
+ else:
446
+ role = next(q["over"] for q in r["qs"] if q["type"] == "span")
447
+ part = next(p for p in r["parts"] if p[0] == role)
448
+ U = len(part[3][0])
449
+ acc = np.zeros((U, len(names)), np.float64); cnt = np.zeros(U, np.float64)
450
+ for (a, b), gidx, _, o in lst:
451
+ lg = o["span"]; n = len(lg)
452
+ acc[gidx[:n]] += lg; cnt[gidx[:n]] += 1
453
+ cov = cnt > 0
454
+ span = dict(names=names, offs=np.asarray(part[3][0])[:U],
455
+ logits=np.where(cov[:, None], acc / np.maximum(cnt, 1)[:, None], -30.0))
456
+ self.stats["units_uncovered"] += int((~cov).sum())
457
+ n_tok = {p[0]: len(p[1]) for p in r["parts"]}
458
+ final.append(dict(qs=qs, span=span, n_tokens=n_tok, windows=len(lst) if lst[0][0] is not None else 0,
459
+ n_input=sum(len(x[2]["ids"]) for x in lst)))
460
+ return final
461
+
462
+
463
+
464
+ # =====================================================================================================================
465
+ # the network: UltraBERT-380M + Vela 2.0 SchemaEncoderV2 heads, with a LoRA adapter on the shared frozen backbone
466
+ # =====================================================================================================================
467
+ import torch # noqa: E402
468
+ from torch import nn # noqa: E402
469
+
470
+ LORA_TARGETS = ("q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj")
471
+
472
+
473
+ class LoRALinear(nn.Module):
474
+ """base(x) + (alpha / r) B A x, as trained (ub_lora.LoRALinear)."""
475
+
476
+ def __init__(self, base, r, alpha):
477
+ super().__init__()
478
+ self.base, self.scale = base, alpha / r
479
+ self.lora_A = nn.Parameter(torch.zeros(r, base.in_features)); self.lora_B = nn.Parameter(torch.zeros(base.out_features, r))
480
+
481
+ def forward(self, x):
482
+ return self.base(x) + nn.functional.linear(nn.functional.linear(x, self.lora_A), self.lora_B) * self.scale
483
+
484
+
485
+ def inject_lora(net, r, alpha, layers="all"):
486
+ L = net.encoder.layers
487
+ ids = list(range(len(L))) if layers in (None, "", "all") else list(range(len(L) - int(layers.split(":")[1]), len(L)))
488
+ n = 0
489
+ for i in ids:
490
+ for _, mod in list(L[i].named_modules()):
491
+ for t in LORA_TARGETS:
492
+ child = getattr(mod, t, None)
493
+ if isinstance(child, nn.Linear):
494
+ setattr(mod, t, LoRALinear(child, r, alpha)); n += 1
495
+ return n
496
+
497
+
498
+ class SchemaNet(nn.Module):
499
+ """Vela 2.0 SchemaEncoderV2 (readout "both", word span readout) on UltraBERT: choice / set logits at the [O] / [ABS] markers
500
+ (cosine against the pooled part + MLP), span logits = cosine(word state, [E] label state) / tau_span."""
501
+
502
+ def __init__(self, encoder, hidden, proj_dim, span):
503
+ super().__init__()
504
+ self.encoder = encoder; h, d = hidden, proj_dim
505
+ self.norm = nn.LayerNorm(h)
506
+ self.w_o, self.w_q, self.w_p = nn.Linear(h, d), nn.Linear(h, d), nn.Linear(h, d)
507
+ self.log_tau = nn.Parameter(torch.zeros(()))
508
+ self.cls_mlp = nn.Sequential(nn.Linear(h, 2 * h), nn.ReLU(), nn.Dropout(0.1), nn.Linear(2 * h, 1))
509
+ self.span = span
510
+ if span:
511
+ self.w_t, self.w_e = nn.Linear(h, d), nn.Linear(h, d)
512
+ self.log_tau_span = nn.Parameter(torch.zeros(()))
513
+
514
+ def hidden(self, input_ids, attention_mask):
515
+ return self.encoder(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state
516
+
517
+ def heads(self, hid, q_index, opt_index, unit_index, ent_index): # = modeling_vela2._Vela2Forward.heads, readout "both"
518
+ H = hid.float()
519
+ ob, op, own = opt_index[:, 0], opt_index[:, 1], opt_index[:, 2]
520
+ Ho = H[ob, op]
521
+ cs = nn.functional.pad(H.cumsum(1), (0, 0, 1, 0))
522
+ b, qp, ps, pe = q_index[:, 0], q_index[:, 1], q_index[:, 2], q_index[:, 3]
523
+ pooled = (cs[b, pe] - cs[b, ps]) / (pe - ps).clamp(min=1).unsqueeze(-1).float()
524
+ v = nn.functional.normalize(self.w_p(self.norm(pooled)), dim=-1)
525
+ uq = self.w_q(self.norm(H[b, qp]))
526
+ u = nn.functional.normalize(self.w_o(self.norm(Ho)) + uq[own], dim=-1)
527
+ lg = (u * v[own]).sum(-1) / self.log_tau.exp() + self.cls_mlp(Ho).squeeze(-1)
528
+ if not self.span:
529
+ return lg, torch.zeros((unit_index.shape[0], ent_index.shape[0]), device=H.device)
530
+ t = nn.functional.normalize(self.w_t(self.norm(H[unit_index[:, 0], unit_index[:, 1]])), dim=-1)
531
+ e = nn.functional.normalize(self.w_e(self.norm(H[ent_index[:, 0], ent_index[:, 1]])), dim=-1)
532
+ return lg, (t @ e.T) / self.log_tau_span.exp()
533
+
534
+
535
+ def _set_param(root, name, p):
536
+ *path, leaf = name.split(".")
537
+ mod = root
538
+ for x in path:
539
+ mod = getattr(mod, x)
540
+ setattr(mod, leaf, p)
541
+
542
+
543
+ def build_adapter(base, file, device):
544
+ """base: the loaded decision model (vela3_encoder.DecisionEncoder: the frozen backbone and its heads). file: an adapter
545
+ safetensors (only the tensors that differ from the backbone). Returns a SchemaNet whose frozen weights are the base's own
546
+ Parameter objects (shared, not copied) and whose adapter tensors come from the file. Every parameter is accounted for."""
547
+ from safetensors import safe_open
548
+ from safetensors.torch import load_file
549
+ from transformers import AutoModel
550
+ with safe_open(str(file), "pt") as f:
551
+ meta = f.metadata()
552
+ delta = load_file(str(file))
553
+ enc = AutoModel.from_config(base.encoder.config, trust_remote_code=True, attn_implementation="sdpa", dtype=torch.float32)
554
+ net = SchemaNet(enc, base.encoder.config.hidden_size, base.w_o.out_features, span="w_t.weight" in delta)
555
+ inject_lora(net, int(meta["lora_rank"]), float(meta["lora_alpha"]), meta.get("lora_layers", "all"))
556
+ bp = dict(base.named_parameters()); used = set()
557
+ for name, p in list(net.named_parameters()):
558
+ if name in delta:
559
+ _set_param(net, name, nn.Parameter(delta[name].to(device), requires_grad=False)); used.add(name)
560
+ else:
561
+ bn = name.replace(".base.", ".")
562
+ if bn not in bp or bp[bn].shape != p.shape:
563
+ raise RuntimeError(f"{file}: {name} is neither in the adapter nor in the backbone")
564
+ _set_param(net, name, bp[bn])
565
+ left = set(delta) - used
566
+ if left:
567
+ raise RuntimeError(f"{file}: unused adapter tensors {sorted(left)[:5]}")
568
+ return net.to(device).eval()
569
+
570
+
571
+ class _GatedBackend:
572
+ """_TorchBackend of the Vela 2.0 runtime for one SchemaNet. fp32 by default: the adapter passes were evaluated (dev reads, thresholds)
573
+ in fp32 (the research gated loader computes the adapter hidden states lazily, outside the scorer's bf16 autocast). amp_bf16=True
574
+ runs the encoder under bf16 autocast on GPU instead (faster; not what the thresholds were picked on)."""
575
+
576
+ def __init__(self, net, device, amp_bf16=False):
577
+ self.net, self.device, self.amp = net, device, bool(amp_bf16)
578
+
579
+ def __call__(self, x, m, qi, oi, ui, ei):
580
+ dev = self.device
581
+ with torch.no_grad():
582
+ X, M = torch.from_numpy(x).to(dev), torch.from_numpy(m).to(dev)
583
+ with torch.autocast("cuda", dtype=torch.bfloat16, enabled=self.amp and str(dev).startswith("cuda")):
584
+ h = self.net.hidden(X, M)
585
+ lg, sp = self.net.heads(h, *(torch.from_numpy(a).to(dev) for a in (qi, oi, ui, ei)))
586
+ return lg.float().cpu().numpy(), sp.float().cpu().numpy()
587
+
588
+
589
+ class SchemaEngine(_Core):
590
+ """The Vela 2.0 engine (predict_raw: raw logits per question and per word x label) on one adapter."""
591
+
592
+ def __init__(self, path, net, device, tokenizer=None, max_len=8192, overlap=512, token_budget=32768, batch_size=32, amp_bf16=False):
593
+ from tokenizers import Tokenizer
594
+ path = Path(path); cfg = json.loads((path / "config.json").read_text())
595
+ self.mk = {k: int(v) for k, v in cfg["decision"]["marker_ids"].items()}
596
+ self.bos, self.eos, self.pad = cfg["bos_token_id"], cfg["eos_token_id"], cfg["pad_token_id"]
597
+ if tokenizer is None: # the base UltraBERT tokenizer (the markers are inserted by id, never parsed from text)
598
+ tj = json.loads((path / "tokenizer.json").read_text(encoding="utf-8"))
599
+ tj["added_tokens"] = [t for t in tj["added_tokens"] if t["content"] not in self.mk]
600
+ tokenizer = Tokenizer.from_str(json.dumps(tj)); tokenizer.no_padding(); tokenizer.no_truncation()
601
+ self.tok, self._tc = tokenizer, {}
602
+ self.max_len, self.overlap, self.budget, self.bs = int(max_len), int(overlap), int(token_budget), int(batch_size)
603
+ self.run = _GatedBackend(net, device, amp_bf16)
604
+ self.stats = defaultdict(int); self.last = {}
vela3_config.json ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "vela3-fast",
3
+ "format": "vela3-encoder/1",
4
+ "backbone": "UltraBERT-380M (24 layers, hidden 1024, 32K context); frozen decision backbone = soup_X2",
5
+ "adapters": {
6
+ "span": {
7
+ "file": "span_adapter.safetensors",
8
+ "lora_rank": 64,
9
+ "lora_alpha": 128,
10
+ "lora_layers": "all (24 layers x q/k/v/o/gate/up/down = 168 modules)",
11
+ "full_layers": [
12
+ 20,
13
+ 21,
14
+ 22,
15
+ 23
16
+ ],
17
+ "switched_on": "every span question",
18
+ "source": "span/ckpt-060000",
19
+ "trained_on": "soup_X2"
20
+ },
21
+ "router": {
22
+ "file": "router_adapter.safetensors",
23
+ "lora_rank": 64,
24
+ "lora_alpha": 128,
25
+ "lora_layers": "all (168 modules)",
26
+ "full_layers": [
27
+ 16,
28
+ 17,
29
+ 18,
30
+ 19,
31
+ 20,
32
+ 21,
33
+ 22,
34
+ 23
35
+ ],
36
+ "switched_on": "choice / set questions whose instructions are one of the 18 router texts (router_questions.json; router_texts_v2: + MASSIVE intent / scenario)",
37
+ "source": "router/ckpt-070000",
38
+ "trained_on": "soup_X2"
39
+ },
40
+ "relation": {
41
+ "file": "relation_adapter.safetensors",
42
+ "lora_rank": 128,
43
+ "full_layers": [
44
+ 20,
45
+ 21,
46
+ 22,
47
+ 23
48
+ ],
49
+ "switched_on": "span questions with a relation wording (vela3_encoder._REL_Q), not router / evidence label sets",
50
+ "source": "relation/ckpt-020000",
51
+ "trained_on": "soup_X2"
52
+ },
53
+ "ner": {
54
+ "file": "ner_adapter.safetensors",
55
+ "lora_rank": 128,
56
+ "full_layers": [
57
+ 20,
58
+ 21,
59
+ 22,
60
+ 23
61
+ ],
62
+ "switched_on": "names-only open-label entity questions",
63
+ "source": "ner/ckpt-016000",
64
+ "trained_on": "soup_X2"
65
+ },
66
+ "span_set": {
67
+ "file": "span_sets_adapter.safetensors",
68
+ "switched_on": "halu and PII label sets",
69
+ "source": "span_sets/ckpt-060000",
70
+ "trained_on": "soup_X2"
71
+ },
72
+ "evidence": {
73
+ "file": "evidence_adapter.safetensors",
74
+ "switched_on": "evidence questions (evidence label set, or evidence / support / cite wording outside pii / halu / toxic)",
75
+ "source": "evidence/ckpt-060720",
76
+ "trained_on": "soup_X2",
77
+ "recipe": "evfast C1 (RESULTS_EVFAST.md §10.4) on X2",
78
+ "lora_rank": 64,
79
+ "lora_alpha": 128,
80
+ "full_layers": [
81
+ 20,
82
+ 21,
83
+ 22,
84
+ 23
85
+ ]
86
+ }
87
+ },
88
+ "decisions": "choice / noul questions that are not router questions: the decision backbone, one encoder input per question (vela3_encoder.DecisionEncoder)",
89
+ "router": {
90
+ "set_threshold": 0.5,
91
+ "set_threshold_source": "fixed 0.5 (not tuned)",
92
+ "probabilities": "softmax over the real options, no temperature",
93
+ "task_adapters": {
94
+ "domain": {
95
+ "ids": [
96
+ "domain"
97
+ ],
98
+ "source": "domain/ckpt-006000",
99
+ "file": "domain_adapter.safetensors"
100
+ },
101
+ "factcheck": {
102
+ "ids": [
103
+ "factcheck"
104
+ ],
105
+ "source": "factcheck/ckpt-000750",
106
+ "file": "factcheck_adapter.safetensors"
107
+ },
108
+ "feedback": {
109
+ "file": "feedback_df_adapter.safetensors",
110
+ "ids": [
111
+ "feedback"
112
+ ],
113
+ "source": "feedback_df/ckpt-002000"
114
+ }
115
+ }
116
+ },
117
+ "span": {
118
+ "default_question": "Which spans are named entities of these types?",
119
+ "threshold": 0.6,
120
+ "relation_threshold": 0.55,
121
+ "evidence": {
122
+ "labels": [
123
+ "evidence"
124
+ ],
125
+ "question": "Which spans of the context support the answer to the question?",
126
+ "threshold": 0.5,
127
+ "max_len": 32768,
128
+ "buckets": [
129
+ {
130
+ "name": "short",
131
+ "max_tokens": 2048,
132
+ "threshold": 0.5
133
+ },
134
+ {
135
+ "name": "long",
136
+ "max_tokens": 1000000000000,
137
+ "threshold": 0.4
138
+ }
139
+ ],
140
+ "source": "short: ub_zs EV dev pick; long (> 2048 target tokens): QASPER validation thr half; one window up to 32768 tokens",
141
+ "adapter": "evidence_adapter.safetensors"
142
+ },
143
+ "router_set_temperature": 0.29842907190322876,
144
+ "thresholds_by_set": {
145
+ "halu": 0.45,
146
+ "toxic": 0.5
147
+ },
148
+ "pii_buckets": [
149
+ {
150
+ "name": "short",
151
+ "max_tokens": 1024,
152
+ "threshold": 0.35
153
+ },
154
+ {
155
+ "name": "4K",
156
+ "max_tokens": 6144,
157
+ "threshold": 0.95
158
+ },
159
+ {
160
+ "name": "8K",
161
+ "max_tokens": 1000000000000,
162
+ "threshold": 0.4
163
+ }
164
+ ],
165
+ "threshold_sources": {
166
+ "open_relation_evidence": "ub_zs dev on this package",
167
+ "evidence_long": "kd_eval QASPER-validation thr half",
168
+ "halu_pii": "score_schema_r4 dev on the dev1 package, T_span from its eval_v2 calibration",
169
+ "toxic": "not tuned (0.5)"
170
+ },
171
+ "router_label_sets": {
172
+ "pii": [
173
+ "AGE",
174
+ "CREDIT_CARD",
175
+ "DATE_TIME",
176
+ "DOMAIN_NAME",
177
+ "EMAIL_ADDRESS",
178
+ "GPE",
179
+ "IBAN_CODE",
180
+ "IP_ADDRESS",
181
+ "NRP",
182
+ "ORGANIZATION",
183
+ "PERSON",
184
+ "PHONE_NUMBER",
185
+ "STREET_ADDRESS",
186
+ "TITLE",
187
+ "US_DRIVER_LICENSE",
188
+ "US_SSN",
189
+ "ZIP_CODE"
190
+ ],
191
+ "halu": [
192
+ "unsupported"
193
+ ],
194
+ "toxic": [
195
+ "Criminal Planning/Confessions",
196
+ "Violence",
197
+ "Hate/Identity Hate",
198
+ "Harassment",
199
+ "Profanity",
200
+ "Sexual",
201
+ "Sexual (minor)",
202
+ "Controlled/Regulated Substances",
203
+ "PII/Privacy",
204
+ "Guns and Illegal Weapons",
205
+ "Suicide and Self Harm",
206
+ "Unauthorized Advice",
207
+ "Political/Misinformation/Conspiracy",
208
+ "Fraud/Deception",
209
+ "Illegal Activity",
210
+ "Threat",
211
+ "Copyright/Trademark/Plagiarism",
212
+ "High Risk Gov Decision Making",
213
+ "Immoral/Unethical",
214
+ "Needs Caution",
215
+ "Other",
216
+ "S1",
217
+ "S2",
218
+ "S3",
219
+ "S4",
220
+ "S5",
221
+ "S6",
222
+ "S7",
223
+ "S8",
224
+ "S9",
225
+ "S10",
226
+ "S11",
227
+ "S12",
228
+ "S14",
229
+ "others",
230
+ "social_stereotypes_and_unfair_discrimination",
231
+ "disseminating_false_or_misleading_information_encouraging_disinformation_campaigns",
232
+ "violence_and_physical_harm",
233
+ "private_information_individual",
234
+ "sensitive_information_organization_government",
235
+ "defamation_encouraging_unethical_or_unsafe_actions",
236
+ "toxic_language_hate_speech",
237
+ "fraud_assisting_illegal_activities",
238
+ "copyright_violations",
239
+ "causing_material_harm_by_disseminating_misinformation",
240
+ "sexual_content",
241
+ "mental_health_over-reliance_crisis"
242
+ ]
243
+ },
244
+ "schemas": {
245
+ "pii": {
246
+ "question": "Which spans are personal information?",
247
+ "labels": {
248
+ "AGE": "a person's age",
249
+ "CREDIT_CARD": "a payment card number",
250
+ "DATE_TIME": "a date, time or date of birth",
251
+ "DOMAIN_NAME": "an internet domain name or website address",
252
+ "EMAIL_ADDRESS": "an e-mail address",
253
+ "GPE": "a country, city, state or other geopolitical place",
254
+ "IBAN_CODE": "an international bank account number (IBAN)",
255
+ "IP_ADDRESS": "an IPv4 or IPv6 address",
256
+ "NRP": "a nationality, religious or political group",
257
+ "ORGANIZATION": "the name of a company, institution or other organisation",
258
+ "PERSON": "a person's name",
259
+ "PHONE_NUMBER": "a telephone number",
260
+ "STREET_ADDRESS": "a street address or postal address",
261
+ "TITLE": "a personal or professional title such as Dr. or Mrs.",
262
+ "US_DRIVER_LICENSE": "a US driver's licence number",
263
+ "US_SSN": "a US social security number",
264
+ "ZIP_CODE": "a postal or ZIP code"
265
+ },
266
+ "over": "user"
267
+ },
268
+ "halu": {
269
+ "question": "Which spans of the answer are not supported by the context?",
270
+ "labels": {
271
+ "unsupported": "a claim not supported by the context"
272
+ },
273
+ "over": "answer"
274
+ },
275
+ "toxic": {
276
+ "question": "Which spans are harmful?",
277
+ "labels": {
278
+ "Criminal Planning/Confessions": "planning, assisting or confessing to a crime",
279
+ "Violence": "inciting, threatening or describing physical violence against people",
280
+ "Hate/Identity Hate": "hatred or dehumanisation targeting a protected identity",
281
+ "Harassment": "targeted abuse, bullying or intimidation of a person",
282
+ "Profanity": "obscene or vulgar language",
283
+ "Sexual": "sexually explicit content involving adults",
284
+ "Sexual (minor)": "any sexual content involving a minor",
285
+ "Controlled/Regulated Substances": "obtaining, producing or misusing drugs or regulated substances",
286
+ "PII/Privacy": "seeking or exposing personal or private information about someone",
287
+ "Guns and Illegal Weapons": "acquiring, building or using weapons illegally",
288
+ "Suicide and Self Harm": "self-harm, suicide or encouragement of either",
289
+ "Unauthorized Advice": "medical, legal or financial advice given without qualification",
290
+ "Political/Misinformation/Conspiracy": "political manipulation, misinformation or conspiracy content",
291
+ "Fraud/Deception": "scams, phishing, forgery or deceiving others for gain",
292
+ "Illegal Activity": "unlawful activity not covered by a more specific category",
293
+ "Threat": "an explicit threat of harm directed at someone",
294
+ "Copyright/Trademark/Plagiarism": "infringing copyright or passing off others' work",
295
+ "High Risk Gov Decision Making": "high-stakes government, military or public-safety decisions",
296
+ "Immoral/Unethical": "conduct that is unethical without being clearly illegal",
297
+ "Needs Caution": "ambiguous content warranting caution without a clear violation",
298
+ "Other": "a safety concern that no other category describes",
299
+ "S1": "violent crimes, including terrorism and physical assault",
300
+ "S2": "non-violent crimes such as theft, trafficking or cybercrime",
301
+ "S3": "sex-related crimes including trafficking and sexual assault",
302
+ "S4": "child sexual exploitation of any kind",
303
+ "S5": "defamation, false damaging statements about a real person",
304
+ "S6": "specialised medical, legal or financial advice without qualification",
305
+ "S7": "privacy violations, exposing personal information",
306
+ "S8": "intellectual property infringement",
307
+ "S9": "indiscriminate weapons, chemical, biological, nuclear or radiological",
308
+ "S10": "hate targeting a protected characteristic",
309
+ "S11": "suicide and self-harm",
310
+ "S12": "sexual content involving adults",
311
+ "S14": "abuse of a code interpreter or execution environment",
312
+ "others": "a safety concern that no other category describes",
313
+ "social_stereotypes_and_unfair_discrimination": "stereotyping or unfair treatment based on a protected characteristic",
314
+ "disseminating_false_or_misleading_information_encouraging_disinformation_campaigns": "spreading false or misleading claims, or organising a disinformation campaign",
315
+ "violence_and_physical_harm": "inciting, threatening or describing physical harm to people",
316
+ "private_information_individual": "seeking or exposing a private individual's personal information",
317
+ "sensitive_information_organization_government": "seeking or exposing confidential organisational or government information",
318
+ "defamation_encouraging_unethical_or_unsafe_actions": "defaming a real person, or encouraging unethical or unsafe conduct",
319
+ "toxic_language_hate_speech": "abusive, degrading or hateful language directed at people",
320
+ "fraud_assisting_illegal_activities": "scams, forgery or assistance with unlawful activity",
321
+ "copyright_violations": "reproducing or infringing copyrighted material",
322
+ "causing_material_harm_by_disseminating_misinformation": "false claims that cause concrete harm, such as medical or safety misinformation",
323
+ "sexual_content": "sexually explicit content involving adults",
324
+ "mental_health_over-reliance_crisis": "mental-health crisis content, or unsafe reliance on the model for care"
325
+ },
326
+ "over": "user"
327
+ }
328
+ },
329
+ "window": {
330
+ "max_len": 8192,
331
+ "overlap": 512,
332
+ "aggregation": "mean of word logits over windows",
333
+ "evidence_max_len": 32768
334
+ },
335
+ "precision": "span / router passes in fp32 (as evaluated: dev reads and thresholds); Vela3Encoder.load(adapter_bf16=True) for bf16 autocast",
336
+ "task_adapters": {
337
+ "relation": "relation_adapter.safetensors",
338
+ "ner": "ner_adapter.safetensors"
339
+ },
340
+ "relation": {
341
+ "threshold_pair": 0.55,
342
+ "threshold_multi": 0.45,
343
+ "source": "rel_dev.py v3 on the dev1 package (NER step = the NER adapter at 0.6): pair = head-conditioned dev pick, multi = CoNLL04 + CrossRE dev e2e pick"
344
+ },
345
+ "ner": {
346
+ "threshold": 0.6,
347
+ "source": "ner_dev.py on this package: one threshold on the thr halves of ner_shift / hier / ner_shift_lc (names only)"
348
+ },
349
+ "threshold_note": "evfast: evidence thresholds from dev reads on this package (set_ev.py, 2026-10-24T20:11:06Z); other thresholds provisional (copied), not used by evidence questions",
350
+ "entity_route": "ner",
351
+ "entity_route_relation_pipeline": "span",
352
+ "set_adapter": {
353
+ "file": "span_sets_adapter.safetensors",
354
+ "label_sets": [
355
+ "halu",
356
+ "pii"
357
+ ],
358
+ "router_set_temperature": 0.29842907190322876,
359
+ "thresholds_by_set": {
360
+ "halu": 0.45
361
+ },
362
+ "pii_buckets": [
363
+ {
364
+ "name": "short",
365
+ "max_tokens": 1024,
366
+ "threshold": 0.35
367
+ },
368
+ {
369
+ "name": "4K",
370
+ "max_tokens": 6144,
371
+ "threshold": 0.95
372
+ },
373
+ {
374
+ "name": "8K",
375
+ "max_tokens": 1000000000000,
376
+ "threshold": 0.4
377
+ }
378
+ ],
379
+ "source": "span_sets/ckpt-060000 (dev2 package: T_span / halu / PII buckets)"
380
+ }
381
+ },
382
+ "build": "final: soup_X2 + span span/ckpt-060000, span_sets span_sets/ckpt-060000, router router/ckpt-070000, relation relation/ckpt-020000, ner ner/ckpt-016000, domain domain/ckpt-006000, factcheck factcheck/ckpt-000750, feedback_df feedback_df/ckpt-002000",
383
+ "build_df": {
384
+ "feedback": {
385
+ "source": "feedback_df/ckpt-002000",
386
+ "tensors": 421,
387
+ "params": 143416066
388
+ }
389
+ }
390
+ }
vela3_coreml.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """vela3_coreml.py: vllm-sr/vela3-fast on Core ML (macOS 15+), no PyTorch weights needed.
2
+
3
+ The encoder runs as a fixed-length fp16 Core ML function (the smallest bucket that fits); the small heads run in fp32 on the host.
4
+ Input rendering, span decoding and thresholds are the release's own code (upstream/, Apache-2.0, unmodified).
5
+
6
+ from vela3_coreml import Vela3CoreML
7
+ m = Vela3CoreML(".") # this folder; compute_units="CPU_AND_GPU" by default
8
+ m.decide("My card was charged twice.", {"intent": {"type": "choice", "instructions": "What does the customer want?",
9
+ "criteria": {"refund": "Money back", "cancel": "Cancel the order"}},
10
+ "urgent": {"type": "noul", "instructions": "The customer needs a fast response."}})
11
+ m.pii("Call Dana Whitfield at 312-555-0110.") # -> [{"label", "start", "end", "text", "score"}]
12
+ m.unsupported(context="...", answer="...") # words of the answer the context does not support
13
+
14
+ Scope: decisions (choice / noul) on the decision backbone, and the two label sets of the span_sets adapter (17 PII types,
15
+ unsupported claims). Inputs are limited to 1,024 tokens per encoder pass: decision inputs longer than that raise Unsupported;
16
+ span inputs longer than that are windowed at 1,024 tokens (the release windows at 8,192), so long-document spans can differ."""
17
+ import json, sys, time
18
+ from pathlib import Path
19
+
20
+ import numpy as np
21
+ import torch
22
+ from torch import nn
23
+
24
+ HERE = Path(__file__).resolve().parent
25
+ sys.path.insert(0, str(HERE / "upstream"))
26
+ import vela3_schema as VS # noqa: E402
27
+ from vela3_encoder import DecisionEncoder, Vela3Encoder, Unsupported # noqa: E402
28
+
29
+ PII = None # filled from vela3_config.json
30
+
31
+
32
+ class _Tok:
33
+ """The slice of the HF tokenizer API the release's DecisionEncoder uses (ids identical to AutoTokenizer on this tokenizer.json)."""
34
+
35
+ def __init__(self, path, cfg):
36
+ from tokenizers import Tokenizer
37
+ self.t = Tokenizer.from_file(str(path / "tokenizer.json")); self.t.no_padding(); self.t.no_truncation()
38
+ self.bos_token_id, self.eos_token_id, self.pad_token_id = cfg["bos_token_id"], cfg["eos_token_id"], cfg["pad_token_id"]
39
+
40
+ def __call__(self, s, add_special_tokens=False):
41
+ return {"input_ids": self.t.encode(s, add_special_tokens=add_special_tokens).ids}
42
+
43
+
44
+ class _Encoder:
45
+ """One multifunction Core ML package: L<n> functions, input_ids / attention_mask int32 [1, n] -> hidden fp16 [1, n, 1024]."""
46
+
47
+ def __init__(self, package, lengths, compute_units):
48
+ import coremltools as ct
49
+ cu = getattr(ct.ComputeUnit, compute_units)
50
+ self.lengths = tuple(lengths)
51
+ self.fn = {L: ct.models.MLModel(str(package), function_name=f"L{L}", compute_units=cu) for L in self.lengths}
52
+ self.last_ms = []
53
+
54
+ def __call__(self, ids):
55
+ n = len(ids)
56
+ L = next((L for L in self.lengths if n <= L), None)
57
+ if L is None:
58
+ raise Unsupported(f"input of {n} tokens is longer than the largest Core ML function (L{self.lengths[-1]})")
59
+ x = np.zeros((1, L), np.int32); x[0, :n] = ids; m = np.zeros((1, L), np.int32); m[0, :n] = 1
60
+ t = time.perf_counter(); h = self.fn[L].predict({"input_ids": x, "attention_mask": m})["hidden"]
61
+ self.last_ms.append((L, 1e3 * (time.perf_counter() - t)))
62
+ return torch.from_numpy(h[0, :n].astype(np.float32))
63
+
64
+
65
+ class _SpanRun:
66
+ """Drop-in for vela3_schema._GatedBackend: __call__(x, m, qi, oi, ui, ei) -> (choice logits, span logits)."""
67
+
68
+ def __init__(self, net, enc):
69
+ self.net, self.enc = net, enc
70
+
71
+ def __call__(self, x, m, qi, oi, ui, ei):
72
+ B, W = x.shape
73
+ H = torch.zeros(B, W, 1024)
74
+ for b in range(B):
75
+ n = int(m[b].sum()); H[b, :n] = self.enc(x[b, :n].tolist())
76
+ with torch.no_grad():
77
+ lg, sp = self.net.heads(H, *(torch.from_numpy(a) for a in (qi, oi, ui, ei)))
78
+ return lg.float().numpy(), sp.float().numpy()
79
+
80
+
81
+ class Vela3CoreML:
82
+ def __init__(self, path=HERE, compute_units="CPU_AND_GPU"):
83
+ global PII
84
+ path = Path(path)
85
+ cfg = json.loads((path / "config.json").read_text()); self.cfg = json.loads((path / "vela3_config.json").read_text())
86
+ PII = self.cfg["span"]["router_label_sets"]["pii"]
87
+ from safetensors.torch import load_file
88
+ # decisions: the release DecisionEncoder without its torch encoder (heads + rendering only), encoder on Core ML
89
+ d = DecisionEncoder.__new__(DecisionEncoder); nn.Module.__init__(d)
90
+ h, p = cfg["hidden_size"], cfg["decision"]["proj_dim"]
91
+ d.norm = nn.LayerNorm(h); d.w_o, d.w_q, d.w_p = nn.Linear(h, p), nn.Linear(h, p), nn.Linear(h, p)
92
+ d.log_tau = nn.Parameter(torch.zeros(())); d.cls_mlp = nn.Sequential(nn.Linear(h, 2 * h), nn.ReLU(), nn.Dropout(0.1), nn.Linear(2 * h, 1))
93
+ d.load_state_dict(load_file(str(path / "heads_decision.safetensors")), strict=True); d.eval()
94
+ d.tok = _Tok(path, cfg); d.mk = {t: int(i) for t, i in cfg["decision"]["marker_ids"].items()}
95
+ d.device, d.max_len, d.budget = "cpu", 1024, 65536
96
+ self.dec_enc = _Encoder(path / "Vela3Decision.mlpackage", (128, 256, 512, 1024), compute_units)
97
+ d.forward_recs = self._decision_forward
98
+ self.decision = d
99
+ # spans: the release SchemaNet heads of the span_sets adapter + its SchemaEngine, encoder on Core ML
100
+ net = VS.SchemaNet(nn.Identity(), h, p, span=True)
101
+ net.load_state_dict(load_file(str(path / "heads_span_sets.safetensors")), strict=True); net.eval()
102
+ self.span_enc = _Encoder(path / "Vela3SpanSets.mlpackage", (512, 1024), compute_units)
103
+ eng = VS.SchemaEngine(path, net, "cpu", max_len=1024)
104
+ eng.run = _SpanRun(net, self.span_enc)
105
+ v = Vela3Encoder.__new__(Vela3Encoder)
106
+ v.cfg, v._VS, v.span, v.span_ev, v.span_set, v.task, v.entity_route = self.cfg, VS, eng, eng, eng, {}, "ner"
107
+ self.v = v
108
+
109
+ @torch.no_grad()
110
+ def _decision_forward(self, recs):
111
+ out = []
112
+ for r in recs:
113
+ H = self.dec_enc(r["ids"])[None]
114
+ z = self.decision._logits(H, [r])[0].double().numpy(); e = np.exp(z - z.max()); out.append(e / e.sum())
115
+ return out
116
+
117
+ def decide(self, state, questions):
118
+ """questions: {key: {type: choice | noul, instructions, criteria}} -> {key: answer} (the release's predict())."""
119
+ return self.decision.predict(state, questions)[0]
120
+
121
+ def pii(self, text, threshold=None):
122
+ q = {"type": "span", "criteria": PII}
123
+ if threshold is not None:
124
+ q["threshold"] = threshold
125
+ return self.v.span_answer(text, q)[0]["spans"]
126
+
127
+ def unsupported(self, context, answer, threshold=None):
128
+ q = {"type": "span", "criteria": ["unsupported"]}
129
+ if threshold is not None:
130
+ q["threshold"] = threshold
131
+ return self.v.span_answer({"context": context, "answer": answer}, q)[0]["spans"]
132
+
133
+
134
+ if __name__ == "__main__":
135
+ m = Vela3CoreML()
136
+ print(m.decide("My card was charged twice and I need this fixed today.",
137
+ {"intent": {"type": "choice", "instructions": "What does the customer want?",
138
+ "criteria": {"refund": "Money back for the duplicate charge", "cancel": "Cancel the order"}},
139
+ "urgent": {"type": "noul", "instructions": "The customer needs a fast response."}}))
140
+ print(m.pii("Hi, I'm Dana Whitfield (dana@example.com, 312-555-0110), 4410 Elm Ridge Drive, Dayton, OH 45429."))
141
+ print(m.unsupported(context="Adults may take up to 4 g of paracetamol in 24 hours.",
142
+ answer="Adults may take up to 6 g of paracetamol in 24 hours."))