brandesdavid commited on
Commit
31629f7
·
verified ·
1 Parent(s): 4578a07

Onebox 1 (9B), version 1.0

Browse files
Files changed (5) hide show
  1. LICENSE +202 -0
  2. README.md +171 -0
  3. onebox.py +393 -0
  4. onebox.safetensors +3 -0
  5. onebox_config.json +18 -0
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ base_model: Qwen/Qwen3.5-9B
4
+ library_name: transformers
5
+ pipeline_tag: text-classification
6
+ tags:
7
+ - onebox
8
+ - newcombs
9
+ - typed-decisions
10
+ - classification
11
+ ---
12
+
13
+ # Onebox 1 (9B)
14
+
15
+ Onebox makes typed decisions about a state. You send a state (text or JSON) and one or more questions, each with a fixed set of allowed options. You get back a probability for every option of every question. The model never writes free text, so there is nothing to parse and nothing to repair.
16
+
17
+ The name comes from Newcomb's problem, where the decision is whether to take one box or two. Onebox takes its decision in one pass.
18
+
19
+ This is the first release of the Onebox series from the newcombs lab. It is a research release: we use it to study how well a local model makes typed decisions and how often it falls for misleading words in the input. This is our measure of whether a model has learned to read a text closely and understand it, rather than to just pick the option whose word fits best.
20
+
21
+ ## What is in this release
22
+
23
+ - `onebox.safetensors`: weights we trained for [Qwen3.5-9B](https://huggingface.co/Qwen/Qwen3.5-9B), 44 million parameters (low rank adapters on the last 18 layers and a small scoring head). Only the text part of the base model is used.
24
+ - `onebox.py`: the inference code. One file, no training code.
25
+ - `onebox_config.json`: base model, sizes and the calibration temperature.
26
+
27
+ ## Question types
28
+
29
+ | type | what you send | what you get |
30
+ |---|---|---|
31
+ | `choice` | named options, optionally with a description each | a probability per option |
32
+ | `noul` | a yes or no question | the probability of yes |
33
+ | `score` | ordered levels | a probability per level and the expected level |
34
+
35
+ The order in which you list the options does not change the answer. Every option is read on its own against the same state, and the options are compared only at the end.
36
+
37
+ ## How to run it
38
+
39
+ ```bash
40
+ pip install torch "transformers>=5.10" safetensors huggingface_hub
41
+ ```
42
+
43
+ ```python
44
+ import sys
45
+ from huggingface_hub import snapshot_download
46
+
47
+ path = snapshot_download("newcombs/onebox-1-9b")
48
+ sys.path.insert(0, path)
49
+ from onebox import load
50
+
51
+ model = load(path) # fetches Qwen/Qwen3.5-9B on first use, about 19 GB
52
+ print(model.decide(
53
+ {"ticket": "Server down since 3am, customers cannot log in"},
54
+ {
55
+ "team": {
56
+ "type": "choice",
57
+ "instructions": "Which team handles this?",
58
+ "criteria": {"billing": "payments, invoices", "technical": "outages, bugs, login", "sales": "new contracts"},
59
+ },
60
+ "urgent": {"type": "noul", "instructions": "Does this need action today?"},
61
+ "severity": {"type": "score", "instructions": "How severe is this?", "criteria": ["minor", "major", "critical"]},
62
+ },
63
+ ))
64
+ ```
65
+
66
+ The request and the answer have the same shape as TypeSafe's System One API (`state`, `questions` with `type`, `instructions` and `criteria`). `load` picks CUDA, Apple MPS or the CPU on its own. In bf16 the model needs about 18 GB of memory.
67
+
68
+ Output (rounded to four places):
69
+
70
+ ```python
71
+ {'answers': {
72
+ 'team': {'type': 'choice', 'choice': 'technical', 'confidence': 0.9307,
73
+ 'probabilities': {'billing': 0.035, 'technical': 0.9307, 'sales': 0.0343}},
74
+ 'urgent': {'type': 'noul', 'noul': 0.9774},
75
+ 'severity': {'type': 'score', 'score': 1.3782, 'confidence': 0.5991,
76
+ 'legend': {'0': 'minor', '1': 'major', '2': 'critical'},
77
+ 'probabilities': {'0': 0.0114, '1': 0.5991, '2': 0.3895}}}}
78
+ ```
79
+
80
+ ## Results
81
+
82
+ All numbers are measured by us with one harness. A decision counts as correct when the most likely option matches the label.
83
+
84
+ ### typed-decisions
85
+
86
+ Public benchmark [LocalLLaMA/typed-decisions](https://huggingface.co/datasets/LocalLLaMA/typed-decisions), official test split: 400 cases with 2000 decisions from four workflows (agent traces, customer service, invoices, security incidents).
87
+
88
+ | model | trained on these four workflows? | accuracy |
89
+ |---|---|---|
90
+ | always the most common answer | n/a | 46.1 % |
91
+ | Laya 421M | no | 36.2 % |
92
+ | Onebox recipe without the typed-decisions training split | no | 59.4 % |
93
+ | openjev 4B v5 | no, according to its manifest | 63.8 % |
94
+ | Clef-Flash (9B) | not as far as its card says | 70.3 % |
95
+ | Julia-1 | unknown | 72.6 % |
96
+ | TypeSafe Jev (closed, published number) | unknown | 72.7 % |
97
+ | Laya 421M, fine-tuned | yes | 76.6 % |
98
+ | **Onebox 1 (9B)** | **yes** | **79.3 %** |
99
+
100
+ Onebox was trained on the training split of this benchmark, so the 79.3 % is the number for workflows it has seen. The row without the training split is closer to what to expect on a workflow it has never seen.
101
+
102
+ By question type on the test split, Onebox reaches 75.3 % on `choice`, 86.2 % on yes or no questions and 77.1 % on `score`. Its expected calibration error is 0.150. On the validation split it reaches 80.5 %.
103
+
104
+ ### How this model was chosen
105
+
106
+ We trained seven variants with the typed-decisions training split and picked the one with the best accuracy on the typed-decisions **validation** split, among the variants that fell for at most 10 of our 104 older lure cases. The released model was trained twice as long as our first variant (7200 instead of 3600 steps).
107
+
108
+ ### Misleading words
109
+
110
+ A lure is a word in the input that points toward the wrong option. A customer writes "I can't open the billing page." The page does not load, so this belongs to the technical team, but the word "billing" pulls toward billing.
111
+
112
+ We built two sets of 200 pairs for this, written by two different language models and checked by us. In each pair, one case has such a lure and the other uses the same word where it really points to the right option. The table shows how often both cases of a pair are right, and in brackets how often the model picked the lure. With descriptions, every option also came with a short description, as in the example above.
113
+
114
+ | model | set A | set A, with descriptions | set B | set B, with descriptions |
115
+ |---|---|---|---|---|
116
+ | Onebox 1 (9B) | 85.0 % (9.5 %) | 90.0 % (7.5 %) | 60.5 % (25.0 %) | 75.5 % (19.5 %) |
117
+ | Clef-Flash (9B) | 90.5 % (6.0 %) | 94.5 % (5.5 %) | 69.5 % (25.5 %) | 83.0 % (14.5 %) |
118
+
119
+ Clef-Flash is clearly better here. The hardest case for both is a broken page, form or app that is named after a topic, like the billing page above. On the billing page itself, every model we tried picked billing (Onebox 99.7 %, Laya 99.9 %, Julia-1 98.9 %), except Clef-Flash, which picked technical with 70 %. This is the main thing we work on for the next version.
120
+
121
+ On our 104 older lure cases, Onebox falls for 7 (openjev 4B: 18, openjev 0.8B: 57).
122
+
123
+ ### Other tasks
124
+
125
+ 150 items per task, fixed sample, none of them seen in training.
126
+
127
+ | task | options | Onebox 1 (9B) |
128
+ |---|---|---|
129
+ | AG News | 4 | 90.0 % |
130
+ | emotion | 6 | 54.7 % |
131
+ | XNLI (English) | 3 | 83.3 % |
132
+ | Banking77 | 77 | 55.3 % |
133
+ | MASSIVE | 59 | 70.0 % |
134
+
135
+ ### Speed
136
+
137
+ With `onebox.py` in bf16 on a MacBook Pro with M5 Max (Apple MPS), a question takes about 0.9 seconds. On the Mac, PyTorch only has slow reference kernels for the linear attention layers of Qwen3.5. Our own MLX server for Apple Silicon answers the same questions in 0.33 seconds on average (0.27 median) and in 0.31 seconds with an 8-bit base model (9.7 GB, 98.3 % same answers). That server is not part of this release yet. We have not measured `onebox.py` on an NVIDIA GPU.
138
+
139
+ Questions with many options stay cheap because the shared part of the input is read once. With 77 options (Banking77) a question takes 0.64 seconds on the MLX server.
140
+
141
+ ## Training data
142
+
143
+ - Public sets with their own labels: SNLI, ANLI, MultiNLI, BoolQ.
144
+ - Decision cases we wrote or generated: workflow decisions, implicature and sarcasm, ordinal scales, and training cases built against lures. None of these overlap with the lure test sets.
145
+ - The training split of typed-decisions (5370 decisions), never the test split.
146
+
147
+ Training ran in one stage on one rented H100 (about 2.3 hours, 7200 steps of 4 decisions). The numbers on this card were measured on a Mac with MLX. We checked that the released PyTorch code gives the same decision as those measurements on 398 of 400 test decisions (the rest is rounding in bf16).
148
+
149
+ ## Limits
150
+
151
+ - Words that name an option still pull Onebox toward it, most of all when a page, form or app named after a topic is broken. See the table above.
152
+ - On workflows it has not seen, expect less than 79.3 %. The same recipe without the typed-decisions training split reaches 59.4 %.
153
+ - Mostly English. We have not measured other languages.
154
+ - It was trained on inputs of up to 768 tokens (about 550 English words). `onebox.py` reads up to 32,000 tokens and cuts longer states from the beginning. How well it decides on longer inputs is not measured yet.
155
+ - It reads text only, no images.
156
+ - It is a research model. Do not use it for decisions about people without a human checking the result.
157
+
158
+ ## License
159
+
160
+ The weights and `onebox.py` are released under the Apache License 2.0. The base model Qwen3.5-9B is licensed under Apache 2.0 by the Qwen team.
161
+
162
+ ## Citation
163
+
164
+ ```bibtex
165
+ @misc{newcombs2026onebox,
166
+ title = {Onebox 1: typed decisions in one pass},
167
+ author = {{newcombs}},
168
+ year = {2026},
169
+ url = {https://huggingface.co/newcombs/onebox-1-9b}
170
+ }
171
+ ```
onebox.py ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Onebox: typed decisions in one pass.
2
+
3
+ Inference code for the newcombs Onebox models (https://huggingface.co/newcombs). It loads the
4
+ base model from Hugging Face, adds the Onebox weights (LoRA on the last decoder layers and a small
5
+ scoring head) and answers requests in the Jev / SystemOne shape:
6
+
7
+ from onebox import load
8
+
9
+ model = load("newcombs/onebox-1-9b")
10
+ model.decide(
11
+ {"ticket": "I was charged twice for March."},
12
+ {"team": {"type": "choice", "instructions": "Which team should handle this?",
13
+ "criteria": {"billing": "payments and refunds", "technical": "bugs and outages"}}},
14
+ )
15
+
16
+ Needs torch, transformers (5.10 or newer, for Qwen3.5), safetensors and huggingface_hub.
17
+ Runs on CUDA, Apple MPS or CPU.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import json
23
+ import math
24
+ from pathlib import Path
25
+ from typing import Any
26
+
27
+ import torch
28
+ import torch.nn as nn
29
+ import torch.nn.functional as F
30
+
31
+ CONFIG_FILE = "onebox_config.json"
32
+ WEIGHTS_FILE = "onebox.safetensors"
33
+
34
+ # ---------------------------------------------------------------- requests
35
+
36
+
37
+ def flatten_value(value: Any) -> str:
38
+ if value is None:
39
+ return ""
40
+ if isinstance(value, str):
41
+ return value
42
+ if isinstance(value, (int, float, bool)):
43
+ return str(value)
44
+ if isinstance(value, list):
45
+ return "\n".join(item for item in (flatten_value(v) for v in value) if item)
46
+ if isinstance(value, dict):
47
+ return "; ".join(f"{key}: {text}" for key, text in ((k, flatten_value(v)) for k, v in value.items()) if text)
48
+ return str(value)
49
+
50
+
51
+ def _clip(text: str, head: int, tail: int) -> str:
52
+ return text if len(text) <= head + tail else text[:head] + "\n...\n" + text[-tail:]
53
+
54
+
55
+ def flatten_state(state: Any) -> str:
56
+ """The state as text. Plain JSON stays JSON; browser states (page, elements) become a short listing."""
57
+ if isinstance(state, str):
58
+ return state
59
+ if not isinstance(state, dict):
60
+ return json.dumps(state, ensure_ascii=False, separators=(",", ":"))
61
+ page = state.get("page") if isinstance(state.get("page"), dict) else {}
62
+ elements = state.get("elements") if isinstance(state.get("elements"), list) else None
63
+ recent = state.get("recent_actions") if isinstance(state.get("recent_actions"), list) else None
64
+ if elements is None and not page:
65
+ return json.dumps(state, ensure_ascii=False, separators=(",", ":"))
66
+ parts: list[str] = []
67
+ url = page.get("url") or state.get("url")
68
+ title = page.get("title") or state.get("title")
69
+ text = page.get("text") or state.get("text") or ""
70
+ if url:
71
+ parts.append(f"url: {url}")
72
+ if title:
73
+ parts.append(f"title: {title}")
74
+ if text:
75
+ parts.append("text: " + _clip(str(text), 2400, 1200))
76
+ if elements:
77
+ lines = []
78
+ for el in elements[:80]:
79
+ if not isinstance(el, dict):
80
+ continue
81
+ val = el.get("value") or el.get("current_value") or ""
82
+ ops = el.get("operations") or []
83
+ bits = [f"[{el.get('index', '')}]", str(el.get("role", "")), str(el.get("label", ""))]
84
+ if val != "" and val is not None:
85
+ bits.append(f"value={val}")
86
+ if ops:
87
+ bits.append(",".join(str(item) for item in ops))
88
+ lines.append(" ".join(bit for bit in bits if bit and bit != "[]"))
89
+ if len(elements) > 80:
90
+ lines.append(f"... {len(elements) - 80} more elements")
91
+ parts.append("elements:\n" + "\n".join(lines))
92
+ if recent:
93
+ parts.append("recent: " + json.dumps(recent[-10:], ensure_ascii=False, separators=(",", ":")))
94
+ extra = {k: v for k, v in state.items() if k not in {"page", "elements", "recent_actions", "url", "title", "text"}}
95
+ if extra:
96
+ parts.append(json.dumps(extra, ensure_ascii=False, separators=(",", ":")))
97
+ return "\n".join(parts)
98
+
99
+
100
+ def _hypothesis(key: str, description: str) -> str:
101
+ desc = (description or "").strip()
102
+ return key if not desc or desc == key else f"{key}: {desc}"
103
+
104
+
105
+ def parse_question(raw: dict) -> tuple[str, str, list[str], list[str]]:
106
+ """(type, question text, option texts the model reads, option ids returned to the caller)."""
107
+ kind = str(raw.get("type") or "choice").lower()
108
+ if kind not in ("noul", "choice", "score"):
109
+ raise ValueError(f"type must be noul, choice or score, not {kind!r}")
110
+ instructions = flatten_value(raw.get("instructions"))
111
+ criteria = raw.get("criteria")
112
+ if kind == "noul":
113
+ question = instructions or "Is the answer yes?"
114
+ if isinstance(criteria, dict) and flatten_value(criteria):
115
+ question = f"{question}\n{flatten_value(criteria)}"
116
+ return "noul", question, ["no", "yes"], ["false", "true"]
117
+ if kind == "score":
118
+ if not isinstance(criteria, list) or len(criteria) < 2:
119
+ raise ValueError("score: criteria must be a list of at least two levels")
120
+ levels = [str(i) for i in range(len(criteria))]
121
+ texts = [_hypothesis(level, flatten_value(item)) for level, item in zip(levels, criteria)]
122
+ return "score", instructions or "Which score holds for the state?", texts, levels
123
+ if not isinstance(criteria, dict) or not criteria:
124
+ raise ValueError("choice: criteria must be an object with at least one option")
125
+ keys = [str(key) for key in criteria]
126
+ texts = [_hypothesis(key, flatten_value(val)) for key, val in criteria.items()]
127
+ return "choice", instructions or "Which statement holds for the state?", texts, keys
128
+
129
+
130
+ # ---------------------------------------------------------------- prompt
131
+
132
+ SYSTEM = "Read the state and the question. Decide which of the allowed options holds."
133
+ RULE = ("Which option holds for the state? "
134
+ "A shared word between state and option is not a reason to pick it. "
135
+ "An action name is not evidence that the action is required.")
136
+ _MARK = "\u0000USER\u0000"
137
+
138
+
139
+ def chat_frame(tokenizer) -> tuple[str, str]:
140
+ text = tokenizer.apply_chat_template([{"role": "system", "content": SYSTEM}, {"role": "user", "content": _MARK}],
141
+ tokenize=False, add_generation_prompt=True, enable_thinking=False)
142
+ if text.count(_MARK) != 1:
143
+ raise ValueError("chat template does not place the user message once")
144
+ opening, closing = text.split(_MARK)
145
+ return opening, closing
146
+
147
+
148
+ def build_inputs(tokenizer, frame, state: str, question: str, kind: str, options: list[str], cap: int):
149
+ """Prefix ids (chat opening, state, question, rule) and one branch of ids per option.
150
+
151
+ The state is cut from the left so that prefix and the longest branch fit `cap`; at least
152
+ 256 tokens of state and question stay."""
153
+ opening, closing = frame
154
+ stem = tokenizer.encode(f"State: {state}\nQuestion (type: {kind}): {question}\n")
155
+ instruction = tokenizer.encode(RULE + closing + "Option:")
156
+ opening = tokenizer.encode(opening)
157
+ branches = [tokenizer.encode(f" {str(o).strip()}\n") for o in options]
158
+ words = [tokenizer.encode(f" {str(o).strip()}") for o in options]
159
+ keep = max(cap - max(len(b) for b in branches) - len(instruction) - len(opening), 256)
160
+ return opening + stem[-keep:] + instruction, branches, words
161
+
162
+
163
+ # ---------------------------------------------------------------- model
164
+
165
+
166
+ class LoRALinear(nn.Module):
167
+ def __init__(self, base: nn.Linear, a: torch.Tensor, b: torch.Tensor, scale: float):
168
+ super().__init__()
169
+ self.base = base
170
+ self.a = nn.Parameter(a.float(), requires_grad=False) # (in, rank)
171
+ self.b = nn.Parameter(b.float(), requires_grad=False) # (rank, out)
172
+ self.scale = scale
173
+
174
+ def forward(self, x):
175
+ # the low-rank path in float32, as during training
176
+ return (self.base(x) + ((x.float() @ self.a) @ self.b) * self.scale).to(x.dtype)
177
+
178
+
179
+ def _linear(d_in: int, d_out: int, bias: bool = True) -> nn.Linear:
180
+ return nn.Linear(d_in, d_out, bias=bias)
181
+
182
+
183
+ class MultiHeadAttention(nn.Module):
184
+ def __init__(self, width: int, heads: int):
185
+ super().__init__()
186
+ self.heads = heads
187
+ self.query_proj = _linear(width, width, False)
188
+ self.key_proj = _linear(width, width, False)
189
+ self.value_proj = _linear(width, width, False)
190
+ self.out_proj = _linear(width, width, False)
191
+
192
+ def forward(self, q, k, v):
193
+ def split(x):
194
+ return x.unflatten(-1, (self.heads, -1)).transpose(1, 2)
195
+
196
+ q, k, v = split(self.query_proj(q)), split(self.key_proj(k)), split(self.value_proj(v))
197
+ w = torch.softmax((q @ k.transpose(-1, -2)) * math.sqrt(1.0 / q.shape[-1]), dim=-1)
198
+ return self.out_proj((w @ v).transpose(1, 2).flatten(-2))
199
+
200
+
201
+ class EncoderLayer(nn.Module):
202
+ def __init__(self, width: int, heads: int):
203
+ super().__init__()
204
+ self.attention = MultiHeadAttention(width, heads)
205
+ self.ln1 = nn.LayerNorm(width, eps=1e-5)
206
+ self.ln2 = nn.LayerNorm(width, eps=1e-5)
207
+ self.linear1 = _linear(width, 4 * width)
208
+ self.linear2 = _linear(4 * width, width)
209
+
210
+ def forward(self, x):
211
+ y = self.ln1(x)
212
+ x = x + self.attention(y, y, y)
213
+ return x + self.linear2(torch.relu(self.linear1(self.ln2(x))))
214
+
215
+
216
+ class Encoder(nn.Module):
217
+ def __init__(self, n: int, width: int, heads: int):
218
+ super().__init__()
219
+ self.layers = nn.ModuleList([EncoderLayer(width, heads) for _ in range(n)])
220
+ self.ln = nn.LayerNorm(width, eps=1e-5)
221
+
222
+ def forward(self, x):
223
+ for layer in self.layers:
224
+ x = layer(x)
225
+ return self.ln(x)
226
+
227
+
228
+ class EvidenceLayer(nn.Module):
229
+ def __init__(self, width: int, heads: int):
230
+ super().__init__()
231
+ self.query_norm = nn.LayerNorm(width, eps=1e-5)
232
+ self.memory_norm = nn.LayerNorm(width, eps=1e-5)
233
+ self.attention = MultiHeadAttention(width, heads)
234
+ self.ff_norm = nn.LayerNorm(width, eps=1e-5)
235
+ self.ff_in = _linear(width, 4 * width)
236
+ self.ff_out = _linear(4 * width, width)
237
+
238
+ def forward(self, options, memory):
239
+ m = self.memory_norm(memory)[None]
240
+ options = options + self.attention(self.query_norm(options)[None], m, m)[0]
241
+ return options + self.ff_out(F.gelu(self.ff_in(self.ff_norm(options))))
242
+
243
+
244
+ class Head(nn.Module):
245
+ """Scores all options of one question together, given the question vector, one vector per
246
+ option branch, the prefix hidden states and the output embeddings of the option words."""
247
+
248
+ def __init__(self, dim: int, width: int, heads: int, layers: int, evidence_layers: int):
249
+ super().__init__()
250
+ self.option_in = _linear(dim, width)
251
+ self.query_in = _linear(dim, width)
252
+ self.role = nn.Parameter(torch.zeros(2, width))
253
+ self.layers = Encoder(layers, width, heads)
254
+ self.out = nn.Linear(width, 1)
255
+ self.memory_in = _linear(dim, width)
256
+ self.evidence = nn.ModuleList([EvidenceLayer(width, heads) for _ in range(evidence_layers)])
257
+ self.lexical_in = _linear(dim, width)
258
+ self.prior_scale = nn.Parameter(torch.zeros(1))
259
+
260
+ def forward(self, options, query, memory, lexical):
261
+ q = self.query_in(query)[None] + self.role[0]
262
+ o = self.option_in(options) + self.role[1] + self.lexical_in(lexical)
263
+ m = self.memory_in(memory)
264
+ for layer in self.evidence:
265
+ o = layer(o, m)
266
+ z = self.layers(torch.cat([q, o], dim=0)[None])[0]
267
+ logits = self.out(z[1:]).reshape(-1)
268
+ unit = lexical / lexical.norm(dim=-1, keepdim=True)
269
+ anchor = query / query.norm()
270
+ return logits + torch.exp(torch.clamp(self.prior_scale, max=math.log(100.0))) * (unit @ anchor)
271
+
272
+
273
+ def _fork(cache, k: int) -> None:
274
+ """Repeat every cached prefix state K times along the batch, one copy per option branch."""
275
+ for layer in cache.layers:
276
+ for states in (getattr(layer, "conv_states", None), getattr(layer, "recurrent_states", None)):
277
+ if states:
278
+ for i, s in states.items():
279
+ if s is not None:
280
+ states[i] = s.repeat_interleave(k, dim=0)
281
+ if getattr(layer, "keys", None) is not None and layer.keys.numel():
282
+ layer.keys = layer.keys.repeat_interleave(k, dim=0)
283
+ layer.values = layer.values.repeat_interleave(k, dim=0)
284
+
285
+
286
+ class Onebox:
287
+ def __init__(self, text, lm_weight, head, tokenizer, config: dict, device):
288
+ self.text, self.lm_weight, self.head, self.tokenizer = text, lm_weight, head, tokenizer
289
+ self.config, self.device = config, device
290
+ self.frame = chat_frame(tokenizer)
291
+ self.pad = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else tokenizer.eos_token_id
292
+ self.temperature = float(config.get("temperature", 1.0))
293
+
294
+ def _padded(self, seqs):
295
+ width = max(len(s) for s in seqs)
296
+ pool = torch.zeros((len(seqs), width), dtype=torch.float32)
297
+ for k, seq in enumerate(seqs):
298
+ pool[k, : len(seq)] = 1.0 / len(seq)
299
+ ids = torch.tensor([s + [self.pad] * (width - len(s)) for s in seqs], dtype=torch.long)
300
+ return ids.to(self.device), pool.to(self.device)
301
+
302
+ @torch.inference_mode()
303
+ def logits(self, state: str, question: str, kind: str, options: list[str], max_length: int | None = None):
304
+ """One raw logit per option, before temperature. `kind` is noul, choice or score."""
305
+ from transformers import DynamicCache
306
+
307
+ prefix, branches, words = build_inputs(self.tokenizer, self.frame, state, question, kind, options,
308
+ int(max_length or self.config["max_length"]))
309
+ rows, pool = self._padded(branches)
310
+ word_ids, word_pool = self._padded(words)
311
+ cache = DynamicCache(config=self.text.config)
312
+ for layer in cache.layers:
313
+ if hasattr(layer, "record_past"):
314
+ layer.record_past = True
315
+ h = self.text(input_ids=torch.tensor([prefix], device=self.device), past_key_values=cache,
316
+ use_cache=True).last_hidden_state
317
+ _fork(cache, rows.shape[0])
318
+ hb = self.text(input_ids=rows, past_key_values=cache, use_cache=True).last_hidden_state.float()
319
+ option_vecs = (pool[:, :, None] * hb).sum(dim=1)
320
+ memory = h[0].float()
321
+ lexical = (word_pool[:, :, None] * self.lm_weight[word_ids].float()).sum(dim=1)
322
+ return self.head(option_vecs, memory[-1], memory, lexical).float().cpu()
323
+
324
+ def decide(self, state: Any, questions: dict, max_length: int | None = None) -> dict:
325
+ """Answer a Jev / SystemOne request: `state` (text or JSON) and `questions` keyed by id."""
326
+ text = flatten_state(state)
327
+ if not text.strip():
328
+ raise ValueError("state is empty")
329
+ answers = {}
330
+ for qid, raw in questions.items():
331
+ kind, question, texts, ids = parse_question(raw)
332
+ p = torch.softmax(self.logits(text, question, kind, texts, max_length) / self.temperature, dim=-1).tolist()
333
+ if kind == "noul":
334
+ answers[qid] = {"type": "noul", "noul": round(p[1], 4)}
335
+ continue
336
+ probs = {key: round(v, 4) for key, v in zip(ids, p)}
337
+ best = max(ids, key=lambda key: probs[key])
338
+ if kind == "choice":
339
+ answers[qid] = {"type": "choice", "choice": best, "confidence": probs[best], "probabilities": probs}
340
+ else:
341
+ answers[qid] = {"type": "score", "score": round(sum(i * v for i, v in enumerate(p)), 4),
342
+ "confidence": probs[best], "legend": dict(zip(ids, [flatten_value(c) for c in raw["criteria"]])),
343
+ "probabilities": probs}
344
+ return {"answers": answers}
345
+
346
+
347
+ def _default_device() -> str:
348
+ if torch.cuda.is_available():
349
+ return "cuda"
350
+ if torch.backends.mps.is_available():
351
+ return "mps"
352
+ return "cpu"
353
+
354
+
355
+ def load(path: str | Path = "newcombs/onebox-1-9b", device: str | None = None, dtype=torch.bfloat16) -> Onebox:
356
+ """Load a released Onebox model from a local folder or a Hugging Face repo id."""
357
+ from safetensors.torch import load_file
358
+ from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
359
+
360
+ path = Path(path)
361
+ if not path.is_dir():
362
+ from huggingface_hub import snapshot_download
363
+
364
+ path = Path(snapshot_download(str(path)))
365
+ config = json.loads((path / CONFIG_FILE).read_text(encoding="utf-8"))
366
+ device = device or _default_device()
367
+ base = config["base_model"]
368
+ if AutoConfig.from_pretrained(base).model_type == "qwen3_5":
369
+ from transformers import Qwen3_5ForConditionalGeneration as Model
370
+ else:
371
+ Model = AutoModelForCausalLM
372
+ model = Model.from_pretrained(base, dtype=dtype)
373
+ if hasattr(model.model, "visual"):
374
+ model.model.visual = None # text only
375
+ text = getattr(model.model, "language_model", model.model)
376
+ weights = load_file(str(path / WEIGHTS_FILE))
377
+ scale = float(config["lora_scale"])
378
+ patched = 0
379
+ for key in [k for k in weights if k.startswith("lora.") and k.endswith(".a")]:
380
+ name = key[len("lora."):-len(".a")] # layers.<i>.<block>.<proj>
381
+ parent_name, child = name.rsplit(".", 1)
382
+ parent = text.get_submodule(parent_name)
383
+ setattr(parent, child, LoRALinear(getattr(parent, child), weights[key], weights[f"lora.{name}.b"], scale))
384
+ patched += 1
385
+ h = config["head"]
386
+ head = Head(text.config.hidden_size, h["width"], h["heads"], h["layers"], h["evidence_layers"])
387
+ head.load_state_dict({k[len("head."):]: v for k, v in weights.items() if k.startswith("head.")}, strict=True)
388
+ if patched != int(config["lora_modules"]):
389
+ raise RuntimeError(f"expected {config['lora_modules']} LoRA modules, found {patched}")
390
+ text.eval().to(device)
391
+ head.float().eval().to(device)
392
+ tokenizer = AutoTokenizer.from_pretrained(base)
393
+ return Onebox(text, model.lm_head.weight.to(device), head, tokenizer, config, device)
onebox.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dfd42c4560a56ab258707ffcd55a48b38c6aac788a1560537dc022a0ab969c64
3
+ size 174325928
onebox_config.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "onebox-1-9b",
3
+ "version": "1.0",
4
+ "base_model": "Qwen/Qwen3.5-9B",
5
+ "lora_rank": 16,
6
+ "lora_scale": 1.0,
7
+ "lora_layers": 18,
8
+ "lora_modules": 113,
9
+ "head": {
10
+ "width": 512,
11
+ "heads": 8,
12
+ "layers": 2,
13
+ "evidence_layers": 2
14
+ },
15
+ "temperature": 1.4293804277338802,
16
+ "max_length": 32000,
17
+ "trained_max_length": 768
18
+ }