sb-decision 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sb_decision-0.2.0/LICENSE +202 -0
- sb_decision-0.2.0/NOTICE +12 -0
- sb_decision-0.2.0/PKG-INFO +105 -0
- sb_decision-0.2.0/README.md +82 -0
- sb_decision-0.2.0/pyproject.toml +34 -0
- sb_decision-0.2.0/setup.cfg +4 -0
- sb_decision-0.2.0/src/sb_decision/__init__.py +22 -0
- sb_decision-0.2.0/src/sb_decision/cli.py +38 -0
- sb_decision-0.2.0/src/sb_decision/core.py +135 -0
- sb_decision-0.2.0/src/sb_decision/modeling.py +149 -0
- sb_decision-0.2.0/src/sb_decision.egg-info/PKG-INFO +105 -0
- sb_decision-0.2.0/src/sb_decision.egg-info/SOURCES.txt +15 -0
- sb_decision-0.2.0/src/sb_decision.egg-info/dependency_links.txt +1 -0
- sb_decision-0.2.0/src/sb_decision.egg-info/entry_points.txt +2 -0
- sb_decision-0.2.0/src/sb_decision.egg-info/requires.txt +3 -0
- sb_decision-0.2.0/src/sb_decision.egg-info/top_level.txt +1 -0
- sb_decision-0.2.0/tests/test_sb_decision.py +85 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 Sarathi Balakrishnan
|
|
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.
|
sb_decision-0.2.0/NOTICE
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
SB Decision Model (Browser Decision Model)
|
|
2
|
+
Copyright 2026 Sarathi Balakrishnan
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0. Redistributions must keep this NOTICE.
|
|
5
|
+
|
|
6
|
+
Built on:
|
|
7
|
+
- ModernBERT (Answer.AI / LightOn), Apache-2.0, the encoder backbone.
|
|
8
|
+
- GLiClass (Knowledgator), Apache-2.0, the label-token scoring recipe and the pretrained checkpoint the
|
|
9
|
+
fine-tune started from.
|
|
10
|
+
|
|
11
|
+
The decision framing, option-set design, synthetic data recipe, trained-in abstention, calibration, ONNX export
|
|
12
|
+
recipe, browser runtime and documentation are original work by Sarathi Balakrishnan.
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sb-decision
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: SB Decision Model: score your own options for any text in one pass, with a trained-in ask. By Sarathi Balakrishnan.
|
|
5
|
+
Author: Sarathi Balakrishnan
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Model, https://huggingface.co/sarathi-balakrishnan/browser-decision-model-base
|
|
8
|
+
Project-URL: Author, https://huggingface.co/sarathi-balakrishnan
|
|
9
|
+
Keywords: decision,routing,triage,classification,zero-shot,guardrail
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
License-File: NOTICE
|
|
19
|
+
Requires-Dist: torch>=2.2
|
|
20
|
+
Requires-Dist: transformers>=4.48
|
|
21
|
+
Requires-Dist: huggingface_hub>=0.24
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# sb-decision
|
|
25
|
+
|
|
26
|
+
The SB Decision Model, by Sarathi Balakrishnan. Give it a text and your own list of options, each written as
|
|
27
|
+
`name: when to choose it`, and it returns a calibrated probability per option in one pass. Nothing is retrained per
|
|
28
|
+
use case: the option definitions are the policy. A reserved `ask` option is trained to win when the deciding fact is
|
|
29
|
+
missing from the text, so irreversible actions go to a person instead of being guessed.
|
|
30
|
+
|
|
31
|
+
Not an LLM. It never generates text. It is the router, guardrail, or triage layer in front of one.
|
|
32
|
+
|
|
33
|
+
## Install
|
|
34
|
+
|
|
35
|
+
```
|
|
36
|
+
pip install sb-decision
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Use
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from sb_decision import SBDecision
|
|
43
|
+
|
|
44
|
+
m = SBDecision.load() # sarathi-balakrishnan/browser-decision-model-base
|
|
45
|
+
m.decide(
|
|
46
|
+
"Package arrived broken, second time this month. I want a manager.",
|
|
47
|
+
[
|
|
48
|
+
"refund: customer wants money back for a damaged, wrong, or missing item",
|
|
49
|
+
"replace: customer wants the product again",
|
|
50
|
+
"escalate: angry, threatens to leave, or asks for a manager",
|
|
51
|
+
],
|
|
52
|
+
)
|
|
53
|
+
# {'decision': 'escalate', 'band': 'auto', 'scores': {'escalate': 0.90, 'ask': 0.09, 'refund': 0.01, 'replace': 0.01}}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
`band` is `auto` when the top score is at or above `auto=0.7`, `review` at or above `review=0.4`, otherwise
|
|
57
|
+
`abstain`. If `ask` wins it is always `abstain`. Both thresholds are arguments; they are statements about the error
|
|
58
|
+
rate you accept, not model constants.
|
|
59
|
+
|
|
60
|
+
Independent tags, when several options can apply at once:
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
m.decide(
|
|
64
|
+
"Headache since morning and now my chest feels tight.",
|
|
65
|
+
["headache: pain in the head", "chest pain: pressure or tightness in the chest", "rash: skin redness or itching"],
|
|
66
|
+
mode="multi",
|
|
67
|
+
)
|
|
68
|
+
# {'decision': 'chest pain', 'band': 'auto', 'tags': ['headache', 'chest pain'],
|
|
69
|
+
# 'scores': {'chest pain': 0.76, 'headache': 0.61, 'ask': 0.14, 'rash': 0.0}}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Many texts at once: `m.scores_many(texts, options)`. Command line:
|
|
73
|
+
|
|
74
|
+
```
|
|
75
|
+
sb-decision "It doesn't work on my machine." -o "crash: the app exits or hangs" -o "slow: works but takes too long" -o "question: asks how to do something"
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Access
|
|
79
|
+
|
|
80
|
+
The package is public; the weights are in private preview. `SBDecision.load()` raises `SBAccessError` with contact
|
|
81
|
+
details if your Hugging Face token does not have access. To try it on your own option set, contact Sarathi
|
|
82
|
+
Balakrishnan at https://huggingface.co/sarathi-balakrishnan .
|
|
83
|
+
|
|
84
|
+
## Writing options
|
|
85
|
+
|
|
86
|
+
- One line per option, saying when to choose it, with the boundary to its neighbours explicit.
|
|
87
|
+
- Describe what the text says, not what you will do about it. "chest pressure with sweating or arm tingling" scores;
|
|
88
|
+
"tell the caller to call 911" does not.
|
|
89
|
+
- Keep `ask` in the list whenever the action is irreversible.
|
|
90
|
+
- Up to 12 options, 1,024 tokens, English. It decides from the text, not the world: no lookups, no arithmetic.
|
|
91
|
+
|
|
92
|
+
## Results
|
|
93
|
+
|
|
94
|
+
Measured on 4,745 messages from five domains never seen in training or validation.
|
|
95
|
+
|
|
96
|
+
| model | params | held-out top-1 vs teacher | ask recall | false ask | calibration error (ECE) |
|
|
97
|
+
|---|---|---|---|---|---|
|
|
98
|
+
| base | 151M | 0.765 | 0.752 | 0.024 | 0.030 |
|
|
99
|
+
| large | 399M | 0.796 | 0.822 | 0.021 | 0.072 |
|
|
100
|
+
|
|
101
|
+
The teacher's own self-agreement on the same messages is 0.883.
|
|
102
|
+
|
|
103
|
+
## License
|
|
104
|
+
|
|
105
|
+
Apache-2.0. See NOTICE.
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# sb-decision
|
|
2
|
+
|
|
3
|
+
The SB Decision Model, by Sarathi Balakrishnan. Give it a text and your own list of options, each written as
|
|
4
|
+
`name: when to choose it`, and it returns a calibrated probability per option in one pass. Nothing is retrained per
|
|
5
|
+
use case: the option definitions are the policy. A reserved `ask` option is trained to win when the deciding fact is
|
|
6
|
+
missing from the text, so irreversible actions go to a person instead of being guessed.
|
|
7
|
+
|
|
8
|
+
Not an LLM. It never generates text. It is the router, guardrail, or triage layer in front of one.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```
|
|
13
|
+
pip install sb-decision
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Use
|
|
17
|
+
|
|
18
|
+
```python
|
|
19
|
+
from sb_decision import SBDecision
|
|
20
|
+
|
|
21
|
+
m = SBDecision.load() # sarathi-balakrishnan/browser-decision-model-base
|
|
22
|
+
m.decide(
|
|
23
|
+
"Package arrived broken, second time this month. I want a manager.",
|
|
24
|
+
[
|
|
25
|
+
"refund: customer wants money back for a damaged, wrong, or missing item",
|
|
26
|
+
"replace: customer wants the product again",
|
|
27
|
+
"escalate: angry, threatens to leave, or asks for a manager",
|
|
28
|
+
],
|
|
29
|
+
)
|
|
30
|
+
# {'decision': 'escalate', 'band': 'auto', 'scores': {'escalate': 0.90, 'ask': 0.09, 'refund': 0.01, 'replace': 0.01}}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
`band` is `auto` when the top score is at or above `auto=0.7`, `review` at or above `review=0.4`, otherwise
|
|
34
|
+
`abstain`. If `ask` wins it is always `abstain`. Both thresholds are arguments; they are statements about the error
|
|
35
|
+
rate you accept, not model constants.
|
|
36
|
+
|
|
37
|
+
Independent tags, when several options can apply at once:
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
m.decide(
|
|
41
|
+
"Headache since morning and now my chest feels tight.",
|
|
42
|
+
["headache: pain in the head", "chest pain: pressure or tightness in the chest", "rash: skin redness or itching"],
|
|
43
|
+
mode="multi",
|
|
44
|
+
)
|
|
45
|
+
# {'decision': 'chest pain', 'band': 'auto', 'tags': ['headache', 'chest pain'],
|
|
46
|
+
# 'scores': {'chest pain': 0.76, 'headache': 0.61, 'ask': 0.14, 'rash': 0.0}}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Many texts at once: `m.scores_many(texts, options)`. Command line:
|
|
50
|
+
|
|
51
|
+
```
|
|
52
|
+
sb-decision "It doesn't work on my machine." -o "crash: the app exits or hangs" -o "slow: works but takes too long" -o "question: asks how to do something"
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Access
|
|
56
|
+
|
|
57
|
+
The package is public; the weights are in private preview. `SBDecision.load()` raises `SBAccessError` with contact
|
|
58
|
+
details if your Hugging Face token does not have access. To try it on your own option set, contact Sarathi
|
|
59
|
+
Balakrishnan at https://huggingface.co/sarathi-balakrishnan .
|
|
60
|
+
|
|
61
|
+
## Writing options
|
|
62
|
+
|
|
63
|
+
- One line per option, saying when to choose it, with the boundary to its neighbours explicit.
|
|
64
|
+
- Describe what the text says, not what you will do about it. "chest pressure with sweating or arm tingling" scores;
|
|
65
|
+
"tell the caller to call 911" does not.
|
|
66
|
+
- Keep `ask` in the list whenever the action is irreversible.
|
|
67
|
+
- Up to 12 options, 1,024 tokens, English. It decides from the text, not the world: no lookups, no arithmetic.
|
|
68
|
+
|
|
69
|
+
## Results
|
|
70
|
+
|
|
71
|
+
Measured on 4,745 messages from five domains never seen in training or validation.
|
|
72
|
+
|
|
73
|
+
| model | params | held-out top-1 vs teacher | ask recall | false ask | calibration error (ECE) |
|
|
74
|
+
|---|---|---|---|---|---|
|
|
75
|
+
| base | 151M | 0.765 | 0.752 | 0.024 | 0.030 |
|
|
76
|
+
| large | 399M | 0.796 | 0.822 | 0.021 | 0.072 |
|
|
77
|
+
|
|
78
|
+
The teacher's own self-agreement on the same messages is 0.883.
|
|
79
|
+
|
|
80
|
+
## License
|
|
81
|
+
|
|
82
|
+
Apache-2.0. See NOTICE.
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "sb-decision"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "SB Decision Model: score your own options for any text in one pass, with a trained-in ask. By Sarathi Balakrishnan."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
authors = [{ name = "Sarathi Balakrishnan" }]
|
|
11
|
+
license = { text = "Apache-2.0" }
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
keywords = ["decision", "routing", "triage", "classification", "zero-shot", "guardrail"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 4 - Beta",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"License :: OSI Approved :: Apache Software License",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
20
|
+
]
|
|
21
|
+
dependencies = ["torch>=2.2", "transformers>=4.48", "huggingface_hub>=0.24"]
|
|
22
|
+
|
|
23
|
+
[project.urls]
|
|
24
|
+
Model = "https://huggingface.co/sarathi-balakrishnan/browser-decision-model-base"
|
|
25
|
+
Author = "https://huggingface.co/sarathi-balakrishnan"
|
|
26
|
+
|
|
27
|
+
[project.scripts]
|
|
28
|
+
sb-decision = "sb_decision.cli:main"
|
|
29
|
+
|
|
30
|
+
[tool.setuptools.packages.find]
|
|
31
|
+
where = ["src"]
|
|
32
|
+
|
|
33
|
+
[tool.setuptools]
|
|
34
|
+
license-files = ["LICENSE", "NOTICE"]
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""SB Decision Model by Sarathi Balakrishnan: your options, scored in one pass, with a trained-in ask.
|
|
2
|
+
|
|
3
|
+
from sb_decision import SBDecision
|
|
4
|
+
m = SBDecision.load()
|
|
5
|
+
m.decide("Package arrived broken, I want a manager.",
|
|
6
|
+
["refund: customer wants money back", "escalate: angry or asks for a manager"])
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from sb_decision.core import ASK, DEFAULT_MODEL, SBAccessError, SBDecision, parse_options
|
|
10
|
+
from sb_decision.modeling import SBDecisionConfig, SBDecisionModel
|
|
11
|
+
|
|
12
|
+
__version__ = "0.2.0"
|
|
13
|
+
__all__ = [
|
|
14
|
+
"ASK",
|
|
15
|
+
"DEFAULT_MODEL",
|
|
16
|
+
"SBAccessError",
|
|
17
|
+
"SBDecision",
|
|
18
|
+
"SBDecisionConfig",
|
|
19
|
+
"SBDecisionModel",
|
|
20
|
+
"parse_options",
|
|
21
|
+
"__version__",
|
|
22
|
+
]
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""sb-decision "text" -o "refund: customer wants money back" -o "escalate: asks for a manager" """
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from sb_decision.core import DEFAULT_MODEL, SBAccessError, SBDecision
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def main(argv: list[str] | None = None) -> int:
|
|
13
|
+
ap = argparse.ArgumentParser(
|
|
14
|
+
prog="sb-decision", description="Score your own options for a text with the SB Decision Model."
|
|
15
|
+
)
|
|
16
|
+
ap.add_argument("text")
|
|
17
|
+
ap.add_argument("-o", "--option", action="append", required=True, help="'name: when to choose it' (repeat)")
|
|
18
|
+
ap.add_argument(
|
|
19
|
+
"--mode", choices=["single", "multi"], default="single", help="single = pick one, multi = independent tags"
|
|
20
|
+
)
|
|
21
|
+
ap.add_argument("--no-ask", action="store_true", help="do not add the trained 'ask' option")
|
|
22
|
+
ap.add_argument("--auto", type=float, default=0.7)
|
|
23
|
+
ap.add_argument("--review", type=float, default=0.4)
|
|
24
|
+
ap.add_argument("--model", default=DEFAULT_MODEL, help="Hugging Face repo id or local folder")
|
|
25
|
+
ap.add_argument("--device", default="cpu")
|
|
26
|
+
a = ap.parse_args(argv)
|
|
27
|
+
try:
|
|
28
|
+
m = SBDecision.load(a.model, device=a.device)
|
|
29
|
+
except SBAccessError as e:
|
|
30
|
+
print(str(e), file=sys.stderr)
|
|
31
|
+
return 2
|
|
32
|
+
r = m.decide(a.text, a.option, mode=a.mode, include_ask=not a.no_ask, auto=a.auto, review=a.review)
|
|
33
|
+
print(json.dumps(r, indent=1))
|
|
34
|
+
return 0
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
if __name__ == "__main__":
|
|
38
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""SBDecision: load the model once, then decide(text, options)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import torch
|
|
6
|
+
from huggingface_hub.errors import GatedRepoError, HfHubHTTPError, RepositoryNotFoundError
|
|
7
|
+
from transformers import AutoTokenizer
|
|
8
|
+
|
|
9
|
+
from sb_decision.modeling import LABEL_TOKEN, SEP_TOKEN, SBDecisionModel
|
|
10
|
+
|
|
11
|
+
DEFAULT_MODEL = "sarathi-balakrishnan/browser-decision-model-base"
|
|
12
|
+
ASK = {"name": "ask", "definition": "not enough information to decide"}
|
|
13
|
+
AUTHOR_PAGE = "https://huggingface.co/sarathi-balakrishnan"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class SBAccessError(RuntimeError):
|
|
17
|
+
"""The package installed fine, but the weights are not reachable with this token."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def parse_options(options: list[str | dict]) -> list[dict]:
|
|
21
|
+
"""'name: when to choose it' strings or {'name', 'definition'} dicts -> dicts. Names are lower-cased."""
|
|
22
|
+
out: list[dict] = []
|
|
23
|
+
for o in options:
|
|
24
|
+
if isinstance(o, str):
|
|
25
|
+
name, _, definition = o.partition(":")
|
|
26
|
+
out.append({"name": name.strip().lower(), "definition": definition.strip()})
|
|
27
|
+
else:
|
|
28
|
+
out.append({"name": str(o["name"]).strip().lower(), "definition": str(o.get("definition", "")).strip()})
|
|
29
|
+
if any(not o["name"] for o in out):
|
|
30
|
+
raise ValueError("every option needs a name")
|
|
31
|
+
return out
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def band(decision: str, p: float, auto: float, review: float) -> str:
|
|
35
|
+
if decision == ASK["name"]:
|
|
36
|
+
return "abstain"
|
|
37
|
+
return "auto" if p >= auto else "review" if p >= review else "abstain"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class SBDecision:
|
|
41
|
+
"""One loaded model. ``decide`` for a verdict with a band, ``scores`` for the raw calibrated probabilities."""
|
|
42
|
+
|
|
43
|
+
def __init__(self, model: SBDecisionModel, tokenizer, device: str = "cpu") -> None:
|
|
44
|
+
self.model = model.to(device).eval()
|
|
45
|
+
self.tokenizer = tokenizer
|
|
46
|
+
self.device = device
|
|
47
|
+
|
|
48
|
+
@classmethod
|
|
49
|
+
def load(
|
|
50
|
+
cls, model: str = DEFAULT_MODEL, device: str = "cpu", token: str | None = None, revision: str | None = None
|
|
51
|
+
) -> SBDecision:
|
|
52
|
+
"""``model`` is a Hugging Face repo id or a local folder. The weights are in private preview: loading needs a
|
|
53
|
+
Hugging Face token with access, otherwise SBAccessError says how to get it."""
|
|
54
|
+
try:
|
|
55
|
+
m = SBDecisionModel.from_pretrained(model, token=token, revision=revision)
|
|
56
|
+
tok = AutoTokenizer.from_pretrained(model, token=token, revision=revision)
|
|
57
|
+
except (GatedRepoError, RepositoryNotFoundError) as e:
|
|
58
|
+
raise SBAccessError(_access_message(model)) from e
|
|
59
|
+
except HfHubHTTPError as e:
|
|
60
|
+
if e.response is not None and e.response.status_code in (401, 403, 404):
|
|
61
|
+
raise SBAccessError(_access_message(model)) from e
|
|
62
|
+
raise
|
|
63
|
+
except OSError as e:
|
|
64
|
+
if "401" in str(e) or "403" in str(e) or "404" in str(e) or "not a valid model identifier" in str(e):
|
|
65
|
+
raise SBAccessError(_access_message(model)) from e
|
|
66
|
+
raise
|
|
67
|
+
return cls(m, tok, device)
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def max_options(self) -> int:
|
|
71
|
+
return int(getattr(self.model.config, "max_options", 12))
|
|
72
|
+
|
|
73
|
+
def build_input(self, text: str, options: list[dict]) -> str:
|
|
74
|
+
labels = [f"{o['name']}: {o['definition']}" if o["definition"] else o["name"] for o in options]
|
|
75
|
+
return "".join(LABEL_TOKEN + lab for lab in labels) + SEP_TOKEN + text
|
|
76
|
+
|
|
77
|
+
@torch.no_grad()
|
|
78
|
+
def scores_many(
|
|
79
|
+
self,
|
|
80
|
+
texts: list[str],
|
|
81
|
+
options: list[str | dict],
|
|
82
|
+
mode: str = "single",
|
|
83
|
+
include_ask: bool = True,
|
|
84
|
+
max_len: int = 1024,
|
|
85
|
+
batch_size: int = 16,
|
|
86
|
+
) -> list[dict[str, float]]:
|
|
87
|
+
opts = parse_options(options)
|
|
88
|
+
if include_ask and all(o["name"] != ASK["name"] for o in opts):
|
|
89
|
+
opts = [*opts, ASK]
|
|
90
|
+
if not 2 <= len(opts) <= self.max_options:
|
|
91
|
+
raise ValueError(f"need 2..{self.max_options} options including ask, got {len(opts)}")
|
|
92
|
+
if mode not in ("single", "multi"):
|
|
93
|
+
raise ValueError("mode is 'single' (pick one, softmax) or 'multi' (independent, sigmoid)")
|
|
94
|
+
out: list[dict[str, float]] = []
|
|
95
|
+
for i in range(0, len(texts), batch_size):
|
|
96
|
+
chunk = [self.build_input(t, opts) for t in texts[i : i + batch_size]]
|
|
97
|
+
enc = self.tokenizer(chunk, truncation=True, max_length=max_len, padding="longest", return_tensors="pt")
|
|
98
|
+
enc = {k: v.to(self.device) for k, v in enc.items()}
|
|
99
|
+
z = self.model(**enc, max_num_classes=len(opts), calibrated=True).logits.float()
|
|
100
|
+
p = torch.softmax(z, -1) if mode == "single" else torch.sigmoid(z)
|
|
101
|
+
out.extend({o["name"]: round(float(row[k]), 4) for k, o in enumerate(opts)} for row in p.cpu())
|
|
102
|
+
return out
|
|
103
|
+
|
|
104
|
+
def scores(self, text: str, options: list[str | dict], **kw) -> dict[str, float]:
|
|
105
|
+
return self.scores_many([text], options, **kw)[0]
|
|
106
|
+
|
|
107
|
+
def decide(
|
|
108
|
+
self,
|
|
109
|
+
text: str,
|
|
110
|
+
options: list[str | dict],
|
|
111
|
+
mode: str = "single",
|
|
112
|
+
include_ask: bool = True,
|
|
113
|
+
auto: float = 0.7,
|
|
114
|
+
review: float = 0.4,
|
|
115
|
+
**kw,
|
|
116
|
+
) -> dict:
|
|
117
|
+
"""{'decision', 'band' (auto | review | abstain), 'scores'}; in multi mode also 'tags' (every option >= 0.5)."""
|
|
118
|
+
s = self.scores(text, options, mode=mode, include_ask=include_ask, **kw)
|
|
119
|
+
top = max(s, key=s.get)
|
|
120
|
+
r = {
|
|
121
|
+
"decision": top,
|
|
122
|
+
"band": band(top, s[top], auto, review),
|
|
123
|
+
"scores": dict(sorted(s.items(), key=lambda kv: -kv[1])),
|
|
124
|
+
}
|
|
125
|
+
if mode == "multi":
|
|
126
|
+
r["tags"] = [n for n, p in s.items() if p >= 0.5 and n != ASK["name"]]
|
|
127
|
+
return r
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _access_message(model: str) -> str:
|
|
131
|
+
return (
|
|
132
|
+
f"sb-decision is installed, but the model weights at '{model}' are not reachable with this Hugging Face token. "
|
|
133
|
+
"The SB Decision Model is in private preview: to get access, contact Sarathi Balakrishnan at "
|
|
134
|
+
f"{AUTHOR_PAGE} . Once granted, log in with `hf auth login` or pass token=... to SBDecision.load()."
|
|
135
|
+
)
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""SB Decision Model: the inference architecture, self-contained (torch + transformers only).
|
|
2
|
+
|
|
3
|
+
This file ships inside the Hugging Face repo, so the model loads with
|
|
4
|
+
``AutoModel.from_pretrained(repo, trust_remote_code=True)`` and no other package.
|
|
5
|
+
|
|
6
|
+
Architecture: a ModernBERT encoder reads ``<<LABEL>>name: definition … <<SEP>>text`` in one pass; the hidden
|
|
7
|
+
state at each ``<<LABEL>>`` token (projected) is dotted with the projected [CLS] state to give one logit per option.
|
|
8
|
+
The state-dict layout matches the training checkpoint (``model.encoder_model.*``, ``model.text_projector.*``,
|
|
9
|
+
``model.classes_projector.*``), so fine-tuned weights load unchanged.
|
|
10
|
+
|
|
11
|
+
Copyright 2026 Sarathi Balakrishnan. Apache-2.0. See NOTICE for the encoder and recipe this builds on.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import torch
|
|
17
|
+
from torch import nn
|
|
18
|
+
from transformers import AutoConfig, AutoModel, PretrainedConfig, PreTrainedModel
|
|
19
|
+
from transformers.activations import ACT2FN
|
|
20
|
+
from transformers.modeling_outputs import SequenceClassifierOutput
|
|
21
|
+
|
|
22
|
+
LABEL_TOKEN = "<<LABEL>>"
|
|
23
|
+
SEP_TOKEN = "<<SEP>>"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class SBDecisionConfig(PretrainedConfig):
|
|
27
|
+
model_type = "sb_decision"
|
|
28
|
+
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
encoder_config: dict | PretrainedConfig | None = None,
|
|
32
|
+
hidden_size: int = 768,
|
|
33
|
+
class_token_index: int = 50368,
|
|
34
|
+
text_token_index: int = 50369,
|
|
35
|
+
calibration_temperature: float = 1.0,
|
|
36
|
+
projector_hidden_act: str = "gelu",
|
|
37
|
+
dropout: float = 0.1,
|
|
38
|
+
max_options: int = 12,
|
|
39
|
+
**kwargs,
|
|
40
|
+
) -> None:
|
|
41
|
+
super().__init__(**kwargs)
|
|
42
|
+
if isinstance(encoder_config, dict):
|
|
43
|
+
encoder_config = AutoConfig.for_model(**encoder_config)
|
|
44
|
+
self.encoder_config = encoder_config
|
|
45
|
+
self.hidden_size = hidden_size
|
|
46
|
+
self.class_token_index = class_token_index
|
|
47
|
+
self.text_token_index = text_token_index
|
|
48
|
+
self.calibration_temperature = calibration_temperature # "temperature" alone is reserved for generation
|
|
49
|
+
self.projector_hidden_act = projector_hidden_act
|
|
50
|
+
self.dropout = dropout
|
|
51
|
+
self.max_options = max_options
|
|
52
|
+
|
|
53
|
+
def to_dict(self) -> dict:
|
|
54
|
+
d = super().to_dict()
|
|
55
|
+
if self.encoder_config is not None:
|
|
56
|
+
d["encoder_config"] = self.encoder_config.to_dict()
|
|
57
|
+
return d
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class Projector(nn.Module):
|
|
61
|
+
def __init__(self, enc_dim: int, hidden: int, act: str, dropout: float) -> None:
|
|
62
|
+
super().__init__()
|
|
63
|
+
self.linear_1 = nn.Linear(enc_dim, hidden)
|
|
64
|
+
self.act = ACT2FN[act]
|
|
65
|
+
self.dropout = nn.Dropout(dropout)
|
|
66
|
+
self.linear_2 = nn.Linear(hidden, enc_dim)
|
|
67
|
+
|
|
68
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
69
|
+
return self.linear_2(self.dropout(self.act(self.linear_1(x))))
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class DotScorer(nn.Module):
|
|
73
|
+
def forward(self, text: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
|
|
74
|
+
return torch.einsum("bd,bkd->bk", text, labels)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class SBDecisionCore(nn.Module):
|
|
78
|
+
def __init__(self, cfg: SBDecisionConfig) -> None:
|
|
79
|
+
super().__init__()
|
|
80
|
+
enc_dim = cfg.encoder_config.hidden_size
|
|
81
|
+
self.encoder_model = AutoModel.from_config(cfg.encoder_config)
|
|
82
|
+
self.text_projector = Projector(enc_dim, cfg.hidden_size, cfg.projector_hidden_act, cfg.dropout)
|
|
83
|
+
self.classes_projector = Projector(enc_dim, cfg.hidden_size, cfg.projector_hidden_act, cfg.dropout)
|
|
84
|
+
self.logit_scale = nn.Parameter(torch.tensor(1.0)) # present in the checkpoint, unused at inference
|
|
85
|
+
self.scorer = DotScorer()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def label_positions_from_ids(input_ids: torch.Tensor, label_token_id: int, k: int | None = None) -> torch.Tensor:
|
|
89
|
+
"""[B, K] index of each <<LABEL>> token, -1 padded."""
|
|
90
|
+
mask = input_ids == label_token_id
|
|
91
|
+
k = k or int(mask.sum(-1).max().item())
|
|
92
|
+
pos = torch.full((input_ids.shape[0], k), -1, dtype=torch.long, device=input_ids.device)
|
|
93
|
+
for b in range(input_ids.shape[0]):
|
|
94
|
+
idx = mask[b].nonzero().flatten()[:k]
|
|
95
|
+
pos[b, : idx.numel()] = idx
|
|
96
|
+
return pos
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class SBDecisionModel(PreTrainedModel):
|
|
100
|
+
config_class = SBDecisionConfig
|
|
101
|
+
base_model_prefix = "model"
|
|
102
|
+
|
|
103
|
+
def __init__(self, config: SBDecisionConfig) -> None:
|
|
104
|
+
super().__init__(config)
|
|
105
|
+
self.model = SBDecisionCore(config)
|
|
106
|
+
self.post_init()
|
|
107
|
+
|
|
108
|
+
def forward(
|
|
109
|
+
self,
|
|
110
|
+
input_ids: torch.Tensor,
|
|
111
|
+
attention_mask: torch.Tensor | None = None,
|
|
112
|
+
label_positions: torch.Tensor | None = None,
|
|
113
|
+
max_num_classes: int | None = None,
|
|
114
|
+
calibrated: bool = False,
|
|
115
|
+
**kwargs,
|
|
116
|
+
) -> SequenceClassifierOutput:
|
|
117
|
+
"""logits[b, k] for option k of row b; padded slots are -1e4. ``calibrated`` divides by the temperature."""
|
|
118
|
+
m = self.model
|
|
119
|
+
hidden = m.encoder_model(input_ids=input_ids, attention_mask=attention_mask)[0] # [B, S, D]
|
|
120
|
+
if label_positions is None:
|
|
121
|
+
label_positions = label_positions_from_ids(input_ids, self.config.class_token_index, max_num_classes)
|
|
122
|
+
valid = (label_positions >= 0).to(hidden.dtype)
|
|
123
|
+
idx = label_positions.clamp(min=0).unsqueeze(-1).expand(-1, -1, hidden.shape[-1])
|
|
124
|
+
labels = m.classes_projector(torch.gather(hidden, 1, idx)) # [B, K, D]
|
|
125
|
+
text = m.text_projector(hidden[:, 0, :]) # [B, D]
|
|
126
|
+
logits = m.scorer(text, labels) * valid + (valid - 1.0) * 1e4
|
|
127
|
+
if calibrated:
|
|
128
|
+
logits = logits / self.config.calibration_temperature
|
|
129
|
+
return SequenceClassifierOutput(logits=logits)
|
|
130
|
+
|
|
131
|
+
@staticmethod
|
|
132
|
+
def build_input(text: str, options: list[dict]) -> str:
|
|
133
|
+
labels = [f"{o['name']}: {o['definition']}" if o.get("definition") else o["name"] for o in options]
|
|
134
|
+
return "".join(LABEL_TOKEN + label for label in labels) + SEP_TOKEN + text
|
|
135
|
+
|
|
136
|
+
@torch.no_grad()
|
|
137
|
+
def score(self, tokenizer, text: str, options: list[dict], mode: str = "single", max_len: int = 1024) -> dict:
|
|
138
|
+
"""Calibrated probability per option. mode "single" = softmax (pick one), "multi" = sigmoid (independent)."""
|
|
139
|
+
if not 2 <= len(options) <= self.config.max_options:
|
|
140
|
+
raise ValueError(f"2..{self.config.max_options} options, got {len(options)}")
|
|
141
|
+
enc = tokenizer(self.build_input(text, options), truncation=True, max_length=max_len, return_tensors="pt")
|
|
142
|
+
enc = {k: v.to(self.device) for k, v in enc.items()}
|
|
143
|
+
z = self(**enc, max_num_classes=len(options), calibrated=True).logits[0].float()
|
|
144
|
+
p = torch.softmax(z, -1) if mode == "single" else torch.sigmoid(z)
|
|
145
|
+
return {o["name"]: round(float(p[i]), 4) for i, o in enumerate(options)}
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
AutoConfig.register("sb_decision", SBDecisionConfig, exist_ok=True)
|
|
149
|
+
AutoModel.register(SBDecisionConfig, SBDecisionModel, exist_ok=True)
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sb-decision
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: SB Decision Model: score your own options for any text in one pass, with a trained-in ask. By Sarathi Balakrishnan.
|
|
5
|
+
Author: Sarathi Balakrishnan
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Model, https://huggingface.co/sarathi-balakrishnan/browser-decision-model-base
|
|
8
|
+
Project-URL: Author, https://huggingface.co/sarathi-balakrishnan
|
|
9
|
+
Keywords: decision,routing,triage,classification,zero-shot,guardrail
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
License-File: NOTICE
|
|
19
|
+
Requires-Dist: torch>=2.2
|
|
20
|
+
Requires-Dist: transformers>=4.48
|
|
21
|
+
Requires-Dist: huggingface_hub>=0.24
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# sb-decision
|
|
25
|
+
|
|
26
|
+
The SB Decision Model, by Sarathi Balakrishnan. Give it a text and your own list of options, each written as
|
|
27
|
+
`name: when to choose it`, and it returns a calibrated probability per option in one pass. Nothing is retrained per
|
|
28
|
+
use case: the option definitions are the policy. A reserved `ask` option is trained to win when the deciding fact is
|
|
29
|
+
missing from the text, so irreversible actions go to a person instead of being guessed.
|
|
30
|
+
|
|
31
|
+
Not an LLM. It never generates text. It is the router, guardrail, or triage layer in front of one.
|
|
32
|
+
|
|
33
|
+
## Install
|
|
34
|
+
|
|
35
|
+
```
|
|
36
|
+
pip install sb-decision
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Use
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from sb_decision import SBDecision
|
|
43
|
+
|
|
44
|
+
m = SBDecision.load() # sarathi-balakrishnan/browser-decision-model-base
|
|
45
|
+
m.decide(
|
|
46
|
+
"Package arrived broken, second time this month. I want a manager.",
|
|
47
|
+
[
|
|
48
|
+
"refund: customer wants money back for a damaged, wrong, or missing item",
|
|
49
|
+
"replace: customer wants the product again",
|
|
50
|
+
"escalate: angry, threatens to leave, or asks for a manager",
|
|
51
|
+
],
|
|
52
|
+
)
|
|
53
|
+
# {'decision': 'escalate', 'band': 'auto', 'scores': {'escalate': 0.90, 'ask': 0.09, 'refund': 0.01, 'replace': 0.01}}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
`band` is `auto` when the top score is at or above `auto=0.7`, `review` at or above `review=0.4`, otherwise
|
|
57
|
+
`abstain`. If `ask` wins it is always `abstain`. Both thresholds are arguments; they are statements about the error
|
|
58
|
+
rate you accept, not model constants.
|
|
59
|
+
|
|
60
|
+
Independent tags, when several options can apply at once:
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
m.decide(
|
|
64
|
+
"Headache since morning and now my chest feels tight.",
|
|
65
|
+
["headache: pain in the head", "chest pain: pressure or tightness in the chest", "rash: skin redness or itching"],
|
|
66
|
+
mode="multi",
|
|
67
|
+
)
|
|
68
|
+
# {'decision': 'chest pain', 'band': 'auto', 'tags': ['headache', 'chest pain'],
|
|
69
|
+
# 'scores': {'chest pain': 0.76, 'headache': 0.61, 'ask': 0.14, 'rash': 0.0}}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Many texts at once: `m.scores_many(texts, options)`. Command line:
|
|
73
|
+
|
|
74
|
+
```
|
|
75
|
+
sb-decision "It doesn't work on my machine." -o "crash: the app exits or hangs" -o "slow: works but takes too long" -o "question: asks how to do something"
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Access
|
|
79
|
+
|
|
80
|
+
The package is public; the weights are in private preview. `SBDecision.load()` raises `SBAccessError` with contact
|
|
81
|
+
details if your Hugging Face token does not have access. To try it on your own option set, contact Sarathi
|
|
82
|
+
Balakrishnan at https://huggingface.co/sarathi-balakrishnan .
|
|
83
|
+
|
|
84
|
+
## Writing options
|
|
85
|
+
|
|
86
|
+
- One line per option, saying when to choose it, with the boundary to its neighbours explicit.
|
|
87
|
+
- Describe what the text says, not what you will do about it. "chest pressure with sweating or arm tingling" scores;
|
|
88
|
+
"tell the caller to call 911" does not.
|
|
89
|
+
- Keep `ask` in the list whenever the action is irreversible.
|
|
90
|
+
- Up to 12 options, 1,024 tokens, English. It decides from the text, not the world: no lookups, no arithmetic.
|
|
91
|
+
|
|
92
|
+
## Results
|
|
93
|
+
|
|
94
|
+
Measured on 4,745 messages from five domains never seen in training or validation.
|
|
95
|
+
|
|
96
|
+
| model | params | held-out top-1 vs teacher | ask recall | false ask | calibration error (ECE) |
|
|
97
|
+
|---|---|---|---|---|---|
|
|
98
|
+
| base | 151M | 0.765 | 0.752 | 0.024 | 0.030 |
|
|
99
|
+
| large | 399M | 0.796 | 0.822 | 0.021 | 0.072 |
|
|
100
|
+
|
|
101
|
+
The teacher's own self-agreement on the same messages is 0.883.
|
|
102
|
+
|
|
103
|
+
## License
|
|
104
|
+
|
|
105
|
+
Apache-2.0. See NOTICE.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
NOTICE
|
|
3
|
+
README.md
|
|
4
|
+
pyproject.toml
|
|
5
|
+
src/sb_decision/__init__.py
|
|
6
|
+
src/sb_decision/cli.py
|
|
7
|
+
src/sb_decision/core.py
|
|
8
|
+
src/sb_decision/modeling.py
|
|
9
|
+
src/sb_decision.egg-info/PKG-INFO
|
|
10
|
+
src/sb_decision.egg-info/SOURCES.txt
|
|
11
|
+
src/sb_decision.egg-info/dependency_links.txt
|
|
12
|
+
src/sb_decision.egg-info/entry_points.txt
|
|
13
|
+
src/sb_decision.egg-info/requires.txt
|
|
14
|
+
src/sb_decision.egg-info/top_level.txt
|
|
15
|
+
tests/test_sb_decision.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
sb_decision
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""sb-decision on a tiny random model: option parsing, bands, modes, batching, save/load, CLI, access error."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
import torch
|
|
9
|
+
from sb_decision import ASK, SBAccessError, SBDecision, SBDecisionConfig, SBDecisionModel, parse_options
|
|
10
|
+
from sb_decision.cli import main
|
|
11
|
+
from sb_decision.core import band
|
|
12
|
+
from tokenizers import Tokenizer, models, pre_tokenizers
|
|
13
|
+
from transformers import PreTrainedTokenizerFast
|
|
14
|
+
|
|
15
|
+
LABEL, SEP = 60, 61
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@pytest.fixture(scope="module")
|
|
19
|
+
def tiny(tmp_path_factory):
|
|
20
|
+
torch.manual_seed(0)
|
|
21
|
+
enc = {
|
|
22
|
+
"model_type": "modernbert", "hidden_size": 32, "intermediate_size": 64, "num_hidden_layers": 2,
|
|
23
|
+
"num_attention_heads": 4, "vocab_size": 64, "max_position_embeddings": 128, "local_attention": 8,
|
|
24
|
+
"global_attn_every_n_layers": 1, "pad_token_id": 0, "bos_token_id": 1, "eos_token_id": 2,
|
|
25
|
+
"cls_token_id": 1, "sep_token_id": 2,
|
|
26
|
+
} # fmt: skip
|
|
27
|
+
cfg = SBDecisionConfig(
|
|
28
|
+
encoder_config=enc, hidden_size=16, class_token_index=LABEL, text_token_index=SEP, calibration_temperature=0.5
|
|
29
|
+
)
|
|
30
|
+
model = SBDecisionModel(cfg).eval()
|
|
31
|
+
vocab = {"[PAD]": 0, "[CLS]": 1, "[SEP]": 2, "[UNK]": 3, **{f"w{i}": i for i in range(4, 60)}}
|
|
32
|
+
vocab.update({"<<LABEL>>": LABEL, "<<SEP>>": SEP})
|
|
33
|
+
t = Tokenizer(models.WordLevel(vocab, unk_token="[UNK]"))
|
|
34
|
+
t.pre_tokenizer = pre_tokenizers.Whitespace()
|
|
35
|
+
tok = PreTrainedTokenizerFast(
|
|
36
|
+
tokenizer_object=t, pad_token="[PAD]", cls_token="[CLS]", sep_token="[SEP]", unk_token="[UNK]"
|
|
37
|
+
)
|
|
38
|
+
tok.add_special_tokens({"additional_special_tokens": ["<<LABEL>>", "<<SEP>>"]})
|
|
39
|
+
d = tmp_path_factory.mktemp("tiny")
|
|
40
|
+
model.save_pretrained(d)
|
|
41
|
+
tok.save_pretrained(d)
|
|
42
|
+
return str(d)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def test_parse_options():
|
|
46
|
+
assert parse_options(["Refund: money back", {"name": "Escalate", "definition": "manager"}, "ask"]) == [
|
|
47
|
+
{"name": "refund", "definition": "money back"},
|
|
48
|
+
{"name": "escalate", "definition": "manager"},
|
|
49
|
+
{"name": "ask", "definition": ""},
|
|
50
|
+
]
|
|
51
|
+
with pytest.raises(ValueError):
|
|
52
|
+
parse_options([": no name"])
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def test_band():
|
|
56
|
+
assert band("refund", 0.9, 0.7, 0.4) == "auto"
|
|
57
|
+
assert band("refund", 0.5, 0.7, 0.4) == "review"
|
|
58
|
+
assert band("refund", 0.1, 0.7, 0.4) == "abstain"
|
|
59
|
+
assert band("ask", 0.99, 0.7, 0.4) == "abstain"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def test_decide_shapes_and_modes(tiny):
|
|
63
|
+
m = SBDecision.load(tiny)
|
|
64
|
+
opts = ["w10: w11 w12", "w13: w14"]
|
|
65
|
+
r = m.decide("w20 w21 w22", opts)
|
|
66
|
+
assert set(r) == {"decision", "band", "scores"} and set(r["scores"]) == {"w10", "w13", ASK["name"]}
|
|
67
|
+
assert abs(sum(r["scores"].values()) - 1) < 0.01 # softmax
|
|
68
|
+
r2 = m.decide("w20 w21 w22", opts, mode="multi", include_ask=False)
|
|
69
|
+
assert set(r2["scores"]) == {"w10", "w13"} and "tags" in r2
|
|
70
|
+
many = m.scores_many(["w20", "w21 w22", "w23"], opts, batch_size=2)
|
|
71
|
+
assert len(many) == 3 and many[0] == m.scores("w20", opts)
|
|
72
|
+
with pytest.raises(ValueError):
|
|
73
|
+
m.decide("w20", ["w10: w11"], include_ask=False)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def test_cli(tiny, capsys):
|
|
77
|
+
assert main(["w20 w21", "-o", "w10: w11", "-o", "w13: w14", "--model", tiny]) == 0
|
|
78
|
+
out = json.loads(capsys.readouterr().out)
|
|
79
|
+
assert out["band"] in ("auto", "review", "abstain")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def test_access_error_message():
|
|
83
|
+
with pytest.raises(SBAccessError) as e:
|
|
84
|
+
SBDecision.load("sarathi-balakrishnan/this-repo-does-not-exist-xyz", token="hf_invalid")
|
|
85
|
+
assert "private preview" in str(e.value) and "sarathi-balakrishnan" in str(e.value)
|