anyjev 0.0.1__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.
- anyjev-0.0.1/LICENSE +202 -0
- anyjev-0.0.1/PKG-INFO +167 -0
- anyjev-0.0.1/README.md +134 -0
- anyjev-0.0.1/anyjev/__init__.py +14 -0
- anyjev-0.0.1/anyjev/backends/__init__.py +3 -0
- anyjev-0.0.1/anyjev/backends/base.py +21 -0
- anyjev-0.0.1/anyjev/backends/fake.py +94 -0
- anyjev-0.0.1/anyjev/backends/hf.py +52 -0
- anyjev-0.0.1/anyjev/backends/vllm.py +58 -0
- anyjev-0.0.1/anyjev/calibrate/__init__.py +6 -0
- anyjev-0.0.1/anyjev/calibrate/contextual.py +47 -0
- anyjev-0.0.1/anyjev/calibrate/permute.py +58 -0
- anyjev-0.0.1/anyjev/calibrate/posthoc.py +60 -0
- anyjev-0.0.1/anyjev/decider.py +236 -0
- anyjev-0.0.1/anyjev/question.py +90 -0
- anyjev-0.0.1/anyjev/readout.py +115 -0
- anyjev-0.0.1/anyjev/result.py +98 -0
- anyjev-0.0.1/anyjev/state.py +20 -0
- anyjev-0.0.1/anyjev.egg-info/PKG-INFO +167 -0
- anyjev-0.0.1/anyjev.egg-info/SOURCES.txt +27 -0
- anyjev-0.0.1/anyjev.egg-info/dependency_links.txt +1 -0
- anyjev-0.0.1/anyjev.egg-info/requires.txt +13 -0
- anyjev-0.0.1/anyjev.egg-info/top_level.txt +1 -0
- anyjev-0.0.1/pyproject.toml +49 -0
- anyjev-0.0.1/setup.cfg +4 -0
- anyjev-0.0.1/tests/test_calibrate.py +98 -0
- anyjev-0.0.1/tests/test_decider_fake.py +143 -0
- anyjev-0.0.1/tests/test_metrics.py +28 -0
- anyjev-0.0.1/tests/test_question.py +40 -0
anyjev-0.0.1/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.
|
anyjev-0.0.1/PKG-INFO
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: anyjev
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Turn any LLM into a Jev-style decision model: typed decisions with calibrated probabilities, training-free by default. Not affiliated with TypeSafe AI.
|
|
5
|
+
Author: Jiamu (Morris) Zhang
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/MorrisZJ/AnyJev
|
|
8
|
+
Project-URL: Repository, https://github.com/MorrisZJ/AnyJev
|
|
9
|
+
Project-URL: Changelog, https://github.com/MorrisZJ/AnyJev/blob/main/CHANGELOG.md
|
|
10
|
+
Keywords: llm,decision,calibration,jev,system-one
|
|
11
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: numpy>=1.24
|
|
23
|
+
Provides-Extra: hf
|
|
24
|
+
Requires-Dist: torch>=2.3; extra == "hf"
|
|
25
|
+
Requires-Dist: transformers>=4.45; extra == "hf"
|
|
26
|
+
Provides-Extra: bench
|
|
27
|
+
Requires-Dist: datasets>=2.20; extra == "bench"
|
|
28
|
+
Requires-Dist: scikit-learn>=1.4; extra == "bench"
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
31
|
+
Requires-Dist: ruff; extra == "dev"
|
|
32
|
+
Dynamic: license-file
|
|
33
|
+
|
|
34
|
+
# AnyJev
|
|
35
|
+
|
|
36
|
+
**English** | [简体中文](README.zh-CN.md)
|
|
37
|
+
|
|
38
|
+
**Turn any LLM into a Jev-style decision model. Typed decisions, real probabilities, no training.**
|
|
39
|
+
|
|
40
|
+
Give it a state and typed questions, get back a decision and a probability per question in one prefill, no generation. Works with the model you already run.
|
|
41
|
+
|
|
42
|
+
What makes it different from reading logits with `max_tokens=1`:
|
|
43
|
+
|
|
44
|
+
- **Training-free debiasing on by default (L0).** Cyclic-shift marginalization removes option-order bias; a label-free prior estimate removes the model's label bias. Zero labels.
|
|
45
|
+
- **Post-hoc calibration when you have labels (L1).** Temperature scaling per (model, question), stored as a small artifact.
|
|
46
|
+
- **Every result says which one you got.** `decision.level` is `raw`, `L0`, or `L1`. Downstream code can refuse to act on the wrong one.
|
|
47
|
+
- **A benchmark that reports calibration.** Accuracy, Brier, ECE, order-flip rate, coverage at 5% risk, from one command.
|
|
48
|
+
|
|
49
|
+
> Not affiliated with, endorsed by, or derived from TypeSafe AI or Jev. All comparisons are measured and reproducible from `bench/results/`.
|
|
50
|
+
|
|
51
|
+
## Install
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
pip install -e ".[hf]" # library + transformers backend
|
|
55
|
+
pip install -e ".[hf,bench,dev]" # plus datasets and pytest
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Ten lines
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
from anyjev import Decider, Question
|
|
62
|
+
from anyjev.backends.hf import HFBackend
|
|
63
|
+
|
|
64
|
+
d = Decider(HFBackend("Qwen/Qwen3-8B"))
|
|
65
|
+
|
|
66
|
+
route = Question.choice("Which handler should process this request?",
|
|
67
|
+
["billing", "technical", "sales", "other"], name="route")
|
|
68
|
+
safe = Question.noul("Is the proposed tool call destructive or irreversible?", name="safe")
|
|
69
|
+
done = Question.score("How complete is the task on a 0 to 1 scale?", bins=5, name="done")
|
|
70
|
+
|
|
71
|
+
state = {"conversation": [...], "proposed_tool_call": {...}}
|
|
72
|
+
r = d.decide(state, [route, safe, done])
|
|
73
|
+
|
|
74
|
+
r["route"].argmax # "billing"
|
|
75
|
+
r["route"].distribution # {"billing": 0.81, "technical": 0.07, ...}
|
|
76
|
+
r["safe"].p_true # 0.12
|
|
77
|
+
r["done"].value # 0.35
|
|
78
|
+
r.level # "L0" (debiased, not calibrated)
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
With labels:
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
art = d.calibrate(safe, calib_states, calib_labels) # ~100 to 500 examples -> L1 artifact
|
|
85
|
+
r = d.decide(state, [safe], level="L1")
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## Why L0 is not optional
|
|
89
|
+
|
|
90
|
+
A `noul` question, "Is this email spam?". Raw readout on the email gives P(Yes) = 0.62. The same prompt with the email replaced by `N/A` gives P(Yes) = 0.70: the model leans Yes regardless of content. Divide by that prior and renormalize, and the answer is P(Yes) = 0.41. The judgment flips. Position bias does the same thing to `choice` questions when you reorder the options. Both are fixable without training, and AnyJev fixes them by default.
|
|
91
|
+
|
|
92
|
+
## Levels
|
|
93
|
+
|
|
94
|
+
Full contract in [docs/levels.md](docs/levels.md).
|
|
95
|
+
|
|
96
|
+
| Level | Needs | Does | Does not |
|
|
97
|
+
|---|---|---|---|
|
|
98
|
+
| `raw` | nothing | restricted softmax over label tokens (what the clones do) | anything about bias or calibration |
|
|
99
|
+
| `L0` | nothing | removes position bias and label-prior bias | make the model's uncertainty calibrated |
|
|
100
|
+
| `L1` | 100 to 500 labels per question | temperature scaling on top of L0 | survive distribution shift beyond the calibration set |
|
|
101
|
+
|
|
102
|
+
## Benchmark
|
|
103
|
+
|
|
104
|
+
```bash
|
|
105
|
+
python -m bench.run --model Qwen/Qwen3-8B --tasks newsgroups,injection,banking20 --n 300 --calib 200
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Results land in `bench/results/<date>/` as Markdown and JSON with hardware and library versions. `python -m bench.table bench/results/<date>` regenerates the table below; nothing is typed in by hand.
|
|
109
|
+
|
|
110
|
+
### Reorder the options and one in five answers changes
|
|
111
|
+
|
|
112
|
+
Three open models, three tasks, 300 test items each. `flip` is the fraction of items whose answer changes when the option list is reversed (`choice`) or the phrasing is swapped between "Yes or No" and "No or Yes" (`noul`). `raw` is what every logit-reading clone does. `L0` is AnyJev's default, zero labels. `L1` adds one temperature fit on 200 labels.
|
|
113
|
+
|
|
114
|
+
| model | task | K | raw flip | L0 flip | raw acc | L0 acc | raw ECE | L1 ECE |
|
|
115
|
+
|---|---|---|---|---|---|---|---|---|
|
|
116
|
+
| Qwen3-8B | banking20 | 20 | 0.227 | 0.077 | 0.750 | 0.807 | 0.235 | 0.100 |
|
|
117
|
+
| Qwen3-8B | newsgroups | 20 | 0.237 | 0.173 | 0.640 | 0.660 | 0.331 | 0.157 |
|
|
118
|
+
| Qwen3-8B | injection | 2 | 0.060 | 0.000 | 0.693 | 0.710 | 0.287 | 0.162 |
|
|
119
|
+
| Qwen2.5-7B-Instruct | banking20 | 20 | 0.197 | 0.067 | 0.723 | 0.767 | 0.236 | 0.072 |
|
|
120
|
+
| Qwen2.5-7B-Instruct | newsgroups | 20 | 0.233 | 0.123 | 0.660 | 0.707 | 0.276 | 0.082 |
|
|
121
|
+
| Qwen2.5-7B-Instruct | injection | 2 | 0.053 | 0.000 | 0.737 | 0.813 | 0.189 | 0.037 |
|
|
122
|
+
| Qwen3-30B-A3B-Instruct-2507 | banking20 | 20 | 0.143 | 0.097 | 0.733 | 0.767 | 0.246 | 0.079 |
|
|
123
|
+
| Qwen3-30B-A3B-Instruct-2507 | newsgroups | 20 | 0.133 | 0.100 | 0.730 | 0.740 | 0.249 | 0.086 |
|
|
124
|
+
| Qwen3-30B-A3B-Instruct-2507 | injection | 2 | 0.093 | 0.000 | 0.723 | 0.767 | 0.253 | 0.080 |
|
|
125
|
+
|
|
126
|
+
Full table with every ablation row (permutation only, each prior alone, Brier, coverage at 5% risk): [docs/results_bench.md](docs/results_bench.md). One H100, bf16, transformers 4.55.4; regenerate with `python -m bench.table bench/results_batchprior_v0/2026-09-20`.
|
|
127
|
+
|
|
128
|
+
### On Laya's own benchmark, zero-shot
|
|
129
|
+
|
|
130
|
+
| system | acc | soft_acc | ece | brier_mean | score_mae |
|
|
131
|
+
|---|---|---|---|---|---|
|
|
132
|
+
| laya-multilingual (zero-shot), measured here | 0.340 | 0.325 | 0.287 | 0.269 | 0.688 |
|
|
133
|
+
| laya (zero-shot), measured here | 0.359 | 0.331 | 0.177 | 0.227 | 0.694 |
|
|
134
|
+
| Qwen2.5-7B-Instruct + raw logits (clone baseline) | 0.621 | 0.514 | 0.287 | 0.209 | 0.437 |
|
|
135
|
+
| Qwen3-8B + raw logits (clone baseline) | 0.626 | 0.520 | 0.328 | 0.210 | 0.621 |
|
|
136
|
+
| Qwen2.5-7B-Instruct + AnyJev L0, zero-shot | 0.628 | 0.506 | 0.200 | 0.176 | 0.451 |
|
|
137
|
+
| Qwen2.5-7B-Instruct + AnyJev L1, temperature from 200 train cases | 0.632 | 0.452 | 0.047 | 0.149 | 0.443 |
|
|
138
|
+
| Qwen3-8B + AnyJev L0, zero-shot | 0.640 | 0.523 | 0.273 | 0.196 | 0.617 |
|
|
139
|
+
| Qwen3-8B + AnyJev L1, temperature from 200 train cases | 0.646 | 0.457 | 0.056 | 0.143 | 0.474 |
|
|
140
|
+
| Qwen3-32B + raw logits (clone baseline) | 0.684 | 0.556 | 0.206 | 0.144 | 0.488 |
|
|
141
|
+
| Qwen3-32B + AnyJev L0, zero-shot | 0.700 | 0.548 | 0.133 | 0.128 | 0.456 |
|
|
142
|
+
| Qwen3-32B + AnyJev L1, temperature from 200 train cases | 0.701 | 0.502 | 0.034 | 0.120 | 0.412 |
|
|
143
|
+
| Jev 1.13.0 (published by TypeSafe / Laya; not rerun) | 0.727 | 0.580 | 0.144 | 0.148 | 0.391 |
|
|
144
|
+
| laya-typed-decisions (fine-tuned on this set's train split), measured here | 0.768 | 0.471 | 0.215 | 0.118 | 0.243 |
|
|
145
|
+
|
|
146
|
+
Laya's headline is 0.766 on this set, above Jev's 0.727. All rows except Jev were measured here on the same 2,000 decisions; the Laya fine-tuned checkpoint reproduces its published number. Read it two ways. On argmax accuracy, Laya fine-tuned on the train split wins, and a 32B open model with zero training is 2.7 points behind Jev. On the probabilities, which is what a System One model is for, the order flips: the fine-tuned Laya's soft accuracy (0.471) is below every Qwen row, and its ECE (0.215) is six times AnyJev L1's (0.034). Laya's zero-shot checkpoints, the ones you would use on a question they were not trained for, score 0.34 to 0.36 against a 0.32 random baseline. Full table with per-workflow and per-type breakdown: [docs/results_typed.md](docs/results_typed.md); regenerate with `python -m bench.run_typed --model <model>` and `python -m bench.providers.laya`.
|
|
147
|
+
|
|
148
|
+
### Inside NanoJev's maze harness
|
|
149
|
+
|
|
150
|
+
| engine | goal test | goal ood | attempts | collisions | edge acc | majority | edge Brier | edge questions |
|
|
151
|
+
|---|---|---|---|---|---|---|---|---|
|
|
152
|
+
| Qwen3-0.6B + AnyJev L0 (batch prior) | 10/11 | 3/4 | 15616 | 6236 | 0.490 | 0.618 | 0.271 | 23156 |
|
|
153
|
+
| Qwen3-0.6B + AnyJev L0 (content_free prior) | 10/11 | 4/4 | 16278 | 6563 | 0.490 | 0.614 | 0.274 | 23284 |
|
|
154
|
+
| Qwen3-0.6B + AnyJev L0 (none prior) | 10/11 | 3/4 | 21851 | 9136 | 0.403 | 0.597 | 0.460 | 28040 |
|
|
155
|
+
| Qwen3-0.6B + AnyJev raw | 11/11 | 4/4 | 5825 | 2616 | 0.537 | 0.539 | 0.363 | 10944 |
|
|
156
|
+
| Qwen3-8B + AnyJev L0 (batch prior) | 11/11 | 3/4 | 17841 | 7171 | 0.555 | 0.600 | 0.344 | 25124 |
|
|
157
|
+
| Qwen3-0.6B native A/B readout (NanoJev's 'Untuned Qwen' protocol) | 10/11 | 3/4 | 20555 | 8496 | 0.419 | 0.607 | 0.305 | 27660 |
|
|
158
|
+
|
|
159
|
+
NanoJev's README compares its trained 0.6B model against "Untuned Qwen3-0.6B", which reads A/B logits for four Boolean questions per maze cell. We ran NanoJev's own frozen exploration code on its 15 test and out-of-distribution mazes and only swapped the engine. Two things are true at once. The untuned model's result depends heavily on how you read it: the same Qwen3-0.6B goes from 13/15 mazes and 20,555 attempts under NanoJev's A/B readout to 15/15 and 5,825 attempts under AnyJev's raw Yes/No readout. And no LLM readout, not even Qwen3-8B, answers "is one step north clear?" better than always saying the majority label (edge accuracy 0.42 to 0.56 against a 0.54 to 0.62 majority). The maze differences come from how each readout's average probability interacts with the controller's p >= 0.5 probe rule, not from map reading. We report it because it is the comparison NanoJev invites; we do not headline it. Full table: [docs/results_maze.md](docs/results_maze.md).
|
|
160
|
+
|
|
161
|
+
## Status and roadmap
|
|
162
|
+
|
|
163
|
+
v0.0.1. The library, both backends, and all three benches are real and measured; the tables above are regenerated from committed JSON. Actively developed: the plan with dates is in [ROADMAP.md](ROADMAP.md) (next up: PyPI release, span readout for more than 26 options, conformal abstention, latency column, a live demo, Llama and Gemma rows; then a Jev-compatible server, more backends, and multimodal state). Backends and bench providers are one file each; see [CONTRIBUTING.md](CONTRIBUTING.md). What landed: [CHANGELOG.md](CHANGELOG.md). Who we build on: [CREDITS.md](CREDITS.md).
|
|
164
|
+
|
|
165
|
+
## License
|
|
166
|
+
|
|
167
|
+
Apache-2.0. Datasets keep their own licenses, see `THIRD_PARTY.md`.
|
anyjev-0.0.1/README.md
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
# AnyJev
|
|
2
|
+
|
|
3
|
+
**English** | [简体中文](README.zh-CN.md)
|
|
4
|
+
|
|
5
|
+
**Turn any LLM into a Jev-style decision model. Typed decisions, real probabilities, no training.**
|
|
6
|
+
|
|
7
|
+
Give it a state and typed questions, get back a decision and a probability per question in one prefill, no generation. Works with the model you already run.
|
|
8
|
+
|
|
9
|
+
What makes it different from reading logits with `max_tokens=1`:
|
|
10
|
+
|
|
11
|
+
- **Training-free debiasing on by default (L0).** Cyclic-shift marginalization removes option-order bias; a label-free prior estimate removes the model's label bias. Zero labels.
|
|
12
|
+
- **Post-hoc calibration when you have labels (L1).** Temperature scaling per (model, question), stored as a small artifact.
|
|
13
|
+
- **Every result says which one you got.** `decision.level` is `raw`, `L0`, or `L1`. Downstream code can refuse to act on the wrong one.
|
|
14
|
+
- **A benchmark that reports calibration.** Accuracy, Brier, ECE, order-flip rate, coverage at 5% risk, from one command.
|
|
15
|
+
|
|
16
|
+
> Not affiliated with, endorsed by, or derived from TypeSafe AI or Jev. All comparisons are measured and reproducible from `bench/results/`.
|
|
17
|
+
|
|
18
|
+
## Install
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pip install -e ".[hf]" # library + transformers backend
|
|
22
|
+
pip install -e ".[hf,bench,dev]" # plus datasets and pytest
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Ten lines
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
from anyjev import Decider, Question
|
|
29
|
+
from anyjev.backends.hf import HFBackend
|
|
30
|
+
|
|
31
|
+
d = Decider(HFBackend("Qwen/Qwen3-8B"))
|
|
32
|
+
|
|
33
|
+
route = Question.choice("Which handler should process this request?",
|
|
34
|
+
["billing", "technical", "sales", "other"], name="route")
|
|
35
|
+
safe = Question.noul("Is the proposed tool call destructive or irreversible?", name="safe")
|
|
36
|
+
done = Question.score("How complete is the task on a 0 to 1 scale?", bins=5, name="done")
|
|
37
|
+
|
|
38
|
+
state = {"conversation": [...], "proposed_tool_call": {...}}
|
|
39
|
+
r = d.decide(state, [route, safe, done])
|
|
40
|
+
|
|
41
|
+
r["route"].argmax # "billing"
|
|
42
|
+
r["route"].distribution # {"billing": 0.81, "technical": 0.07, ...}
|
|
43
|
+
r["safe"].p_true # 0.12
|
|
44
|
+
r["done"].value # 0.35
|
|
45
|
+
r.level # "L0" (debiased, not calibrated)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
With labels:
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
art = d.calibrate(safe, calib_states, calib_labels) # ~100 to 500 examples -> L1 artifact
|
|
52
|
+
r = d.decide(state, [safe], level="L1")
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Why L0 is not optional
|
|
56
|
+
|
|
57
|
+
A `noul` question, "Is this email spam?". Raw readout on the email gives P(Yes) = 0.62. The same prompt with the email replaced by `N/A` gives P(Yes) = 0.70: the model leans Yes regardless of content. Divide by that prior and renormalize, and the answer is P(Yes) = 0.41. The judgment flips. Position bias does the same thing to `choice` questions when you reorder the options. Both are fixable without training, and AnyJev fixes them by default.
|
|
58
|
+
|
|
59
|
+
## Levels
|
|
60
|
+
|
|
61
|
+
Full contract in [docs/levels.md](docs/levels.md).
|
|
62
|
+
|
|
63
|
+
| Level | Needs | Does | Does not |
|
|
64
|
+
|---|---|---|---|
|
|
65
|
+
| `raw` | nothing | restricted softmax over label tokens (what the clones do) | anything about bias or calibration |
|
|
66
|
+
| `L0` | nothing | removes position bias and label-prior bias | make the model's uncertainty calibrated |
|
|
67
|
+
| `L1` | 100 to 500 labels per question | temperature scaling on top of L0 | survive distribution shift beyond the calibration set |
|
|
68
|
+
|
|
69
|
+
## Benchmark
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
python -m bench.run --model Qwen/Qwen3-8B --tasks newsgroups,injection,banking20 --n 300 --calib 200
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Results land in `bench/results/<date>/` as Markdown and JSON with hardware and library versions. `python -m bench.table bench/results/<date>` regenerates the table below; nothing is typed in by hand.
|
|
76
|
+
|
|
77
|
+
### Reorder the options and one in five answers changes
|
|
78
|
+
|
|
79
|
+
Three open models, three tasks, 300 test items each. `flip` is the fraction of items whose answer changes when the option list is reversed (`choice`) or the phrasing is swapped between "Yes or No" and "No or Yes" (`noul`). `raw` is what every logit-reading clone does. `L0` is AnyJev's default, zero labels. `L1` adds one temperature fit on 200 labels.
|
|
80
|
+
|
|
81
|
+
| model | task | K | raw flip | L0 flip | raw acc | L0 acc | raw ECE | L1 ECE |
|
|
82
|
+
|---|---|---|---|---|---|---|---|---|
|
|
83
|
+
| Qwen3-8B | banking20 | 20 | 0.227 | 0.077 | 0.750 | 0.807 | 0.235 | 0.100 |
|
|
84
|
+
| Qwen3-8B | newsgroups | 20 | 0.237 | 0.173 | 0.640 | 0.660 | 0.331 | 0.157 |
|
|
85
|
+
| Qwen3-8B | injection | 2 | 0.060 | 0.000 | 0.693 | 0.710 | 0.287 | 0.162 |
|
|
86
|
+
| Qwen2.5-7B-Instruct | banking20 | 20 | 0.197 | 0.067 | 0.723 | 0.767 | 0.236 | 0.072 |
|
|
87
|
+
| Qwen2.5-7B-Instruct | newsgroups | 20 | 0.233 | 0.123 | 0.660 | 0.707 | 0.276 | 0.082 |
|
|
88
|
+
| Qwen2.5-7B-Instruct | injection | 2 | 0.053 | 0.000 | 0.737 | 0.813 | 0.189 | 0.037 |
|
|
89
|
+
| Qwen3-30B-A3B-Instruct-2507 | banking20 | 20 | 0.143 | 0.097 | 0.733 | 0.767 | 0.246 | 0.079 |
|
|
90
|
+
| Qwen3-30B-A3B-Instruct-2507 | newsgroups | 20 | 0.133 | 0.100 | 0.730 | 0.740 | 0.249 | 0.086 |
|
|
91
|
+
| Qwen3-30B-A3B-Instruct-2507 | injection | 2 | 0.093 | 0.000 | 0.723 | 0.767 | 0.253 | 0.080 |
|
|
92
|
+
|
|
93
|
+
Full table with every ablation row (permutation only, each prior alone, Brier, coverage at 5% risk): [docs/results_bench.md](docs/results_bench.md). One H100, bf16, transformers 4.55.4; regenerate with `python -m bench.table bench/results_batchprior_v0/2026-09-20`.
|
|
94
|
+
|
|
95
|
+
### On Laya's own benchmark, zero-shot
|
|
96
|
+
|
|
97
|
+
| system | acc | soft_acc | ece | brier_mean | score_mae |
|
|
98
|
+
|---|---|---|---|---|---|
|
|
99
|
+
| laya-multilingual (zero-shot), measured here | 0.340 | 0.325 | 0.287 | 0.269 | 0.688 |
|
|
100
|
+
| laya (zero-shot), measured here | 0.359 | 0.331 | 0.177 | 0.227 | 0.694 |
|
|
101
|
+
| Qwen2.5-7B-Instruct + raw logits (clone baseline) | 0.621 | 0.514 | 0.287 | 0.209 | 0.437 |
|
|
102
|
+
| Qwen3-8B + raw logits (clone baseline) | 0.626 | 0.520 | 0.328 | 0.210 | 0.621 |
|
|
103
|
+
| Qwen2.5-7B-Instruct + AnyJev L0, zero-shot | 0.628 | 0.506 | 0.200 | 0.176 | 0.451 |
|
|
104
|
+
| Qwen2.5-7B-Instruct + AnyJev L1, temperature from 200 train cases | 0.632 | 0.452 | 0.047 | 0.149 | 0.443 |
|
|
105
|
+
| Qwen3-8B + AnyJev L0, zero-shot | 0.640 | 0.523 | 0.273 | 0.196 | 0.617 |
|
|
106
|
+
| Qwen3-8B + AnyJev L1, temperature from 200 train cases | 0.646 | 0.457 | 0.056 | 0.143 | 0.474 |
|
|
107
|
+
| Qwen3-32B + raw logits (clone baseline) | 0.684 | 0.556 | 0.206 | 0.144 | 0.488 |
|
|
108
|
+
| Qwen3-32B + AnyJev L0, zero-shot | 0.700 | 0.548 | 0.133 | 0.128 | 0.456 |
|
|
109
|
+
| Qwen3-32B + AnyJev L1, temperature from 200 train cases | 0.701 | 0.502 | 0.034 | 0.120 | 0.412 |
|
|
110
|
+
| Jev 1.13.0 (published by TypeSafe / Laya; not rerun) | 0.727 | 0.580 | 0.144 | 0.148 | 0.391 |
|
|
111
|
+
| laya-typed-decisions (fine-tuned on this set's train split), measured here | 0.768 | 0.471 | 0.215 | 0.118 | 0.243 |
|
|
112
|
+
|
|
113
|
+
Laya's headline is 0.766 on this set, above Jev's 0.727. All rows except Jev were measured here on the same 2,000 decisions; the Laya fine-tuned checkpoint reproduces its published number. Read it two ways. On argmax accuracy, Laya fine-tuned on the train split wins, and a 32B open model with zero training is 2.7 points behind Jev. On the probabilities, which is what a System One model is for, the order flips: the fine-tuned Laya's soft accuracy (0.471) is below every Qwen row, and its ECE (0.215) is six times AnyJev L1's (0.034). Laya's zero-shot checkpoints, the ones you would use on a question they were not trained for, score 0.34 to 0.36 against a 0.32 random baseline. Full table with per-workflow and per-type breakdown: [docs/results_typed.md](docs/results_typed.md); regenerate with `python -m bench.run_typed --model <model>` and `python -m bench.providers.laya`.
|
|
114
|
+
|
|
115
|
+
### Inside NanoJev's maze harness
|
|
116
|
+
|
|
117
|
+
| engine | goal test | goal ood | attempts | collisions | edge acc | majority | edge Brier | edge questions |
|
|
118
|
+
|---|---|---|---|---|---|---|---|---|
|
|
119
|
+
| Qwen3-0.6B + AnyJev L0 (batch prior) | 10/11 | 3/4 | 15616 | 6236 | 0.490 | 0.618 | 0.271 | 23156 |
|
|
120
|
+
| Qwen3-0.6B + AnyJev L0 (content_free prior) | 10/11 | 4/4 | 16278 | 6563 | 0.490 | 0.614 | 0.274 | 23284 |
|
|
121
|
+
| Qwen3-0.6B + AnyJev L0 (none prior) | 10/11 | 3/4 | 21851 | 9136 | 0.403 | 0.597 | 0.460 | 28040 |
|
|
122
|
+
| Qwen3-0.6B + AnyJev raw | 11/11 | 4/4 | 5825 | 2616 | 0.537 | 0.539 | 0.363 | 10944 |
|
|
123
|
+
| Qwen3-8B + AnyJev L0 (batch prior) | 11/11 | 3/4 | 17841 | 7171 | 0.555 | 0.600 | 0.344 | 25124 |
|
|
124
|
+
| Qwen3-0.6B native A/B readout (NanoJev's 'Untuned Qwen' protocol) | 10/11 | 3/4 | 20555 | 8496 | 0.419 | 0.607 | 0.305 | 27660 |
|
|
125
|
+
|
|
126
|
+
NanoJev's README compares its trained 0.6B model against "Untuned Qwen3-0.6B", which reads A/B logits for four Boolean questions per maze cell. We ran NanoJev's own frozen exploration code on its 15 test and out-of-distribution mazes and only swapped the engine. Two things are true at once. The untuned model's result depends heavily on how you read it: the same Qwen3-0.6B goes from 13/15 mazes and 20,555 attempts under NanoJev's A/B readout to 15/15 and 5,825 attempts under AnyJev's raw Yes/No readout. And no LLM readout, not even Qwen3-8B, answers "is one step north clear?" better than always saying the majority label (edge accuracy 0.42 to 0.56 against a 0.54 to 0.62 majority). The maze differences come from how each readout's average probability interacts with the controller's p >= 0.5 probe rule, not from map reading. We report it because it is the comparison NanoJev invites; we do not headline it. Full table: [docs/results_maze.md](docs/results_maze.md).
|
|
127
|
+
|
|
128
|
+
## Status and roadmap
|
|
129
|
+
|
|
130
|
+
v0.0.1. The library, both backends, and all three benches are real and measured; the tables above are regenerated from committed JSON. Actively developed: the plan with dates is in [ROADMAP.md](ROADMAP.md) (next up: PyPI release, span readout for more than 26 options, conformal abstention, latency column, a live demo, Llama and Gemma rows; then a Jev-compatible server, more backends, and multimodal state). Backends and bench providers are one file each; see [CONTRIBUTING.md](CONTRIBUTING.md). What landed: [CHANGELOG.md](CHANGELOG.md). Who we build on: [CREDITS.md](CREDITS.md).
|
|
131
|
+
|
|
132
|
+
## License
|
|
133
|
+
|
|
134
|
+
Apache-2.0. Datasets keep their own licenses, see `THIRD_PARTY.md`.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""AnyJev: turn any causal LLM into a Jev-style decision model.
|
|
2
|
+
|
|
3
|
+
Typed decisions (choice / score / noul) with probabilities, read from the
|
|
4
|
+
model's next-token logits in one prefill, no generation. Training-free
|
|
5
|
+
debiasing (L0) is on by default; post-hoc calibration (L1) when you have labels.
|
|
6
|
+
|
|
7
|
+
Not affiliated with, endorsed by, or derived from TypeSafe AI or Jev.
|
|
8
|
+
"""
|
|
9
|
+
from anyjev.decider import Decider
|
|
10
|
+
from anyjev.question import Question
|
|
11
|
+
from anyjev.result import Decision, DecisionSet
|
|
12
|
+
|
|
13
|
+
__all__ = ["Question", "Decision", "DecisionSet", "Decider"]
|
|
14
|
+
__version__ = "0.0.1"
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Backend protocol. A backend does exactly one thing: given rendered prompts,
|
|
2
|
+
return the next-token log-probabilities of the requested token ids.
|
|
3
|
+
Everything else (debiasing, calibration, abstention) lives above it."""
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from typing import Any, List, Protocol, Sequence
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Backend(Protocol):
|
|
12
|
+
tokenizer: Any # must provide .encode(text, add_special_tokens=False) and optionally .chat_template
|
|
13
|
+
name: str
|
|
14
|
+
|
|
15
|
+
def next_token_logprobs(self, prompts: Sequence[str],
|
|
16
|
+
token_ids: Sequence[Sequence[int]]) -> List[np.ndarray]:
|
|
17
|
+
"""For prompt i, return log p(token | prompt_i) for each id in token_ids[i],
|
|
18
|
+
taken from the full-vocabulary log-softmax at the last position.
|
|
19
|
+
Decision mode never samples; a backend that cannot expose restricted
|
|
20
|
+
next-token logits is not a supported backend."""
|
|
21
|
+
...
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""A synthetic backend with known, injectable biases. Used by the unit tests
|
|
2
|
+
and by the docs to show what L0 removes. It parses the prompts that
|
|
3
|
+
anyjev.readout builds, so it exercises the real prompt path."""
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import re
|
|
7
|
+
from typing import Callable, Dict, List, Optional, Sequence
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
from anyjev.calibrate.contextual import DEFAULT_PROBES
|
|
12
|
+
|
|
13
|
+
_OPT_LINE = re.compile(r"^([A-Z]|\d+)\. (.*)$")
|
|
14
|
+
_NOUL_LINE = re.compile(r"^Answer (Yes|No) or (Yes|No)\.$")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class FakeTokenizer:
|
|
18
|
+
chat_template = None
|
|
19
|
+
|
|
20
|
+
def __init__(self):
|
|
21
|
+
self._vocab: Dict[str, int] = {}
|
|
22
|
+
|
|
23
|
+
def encode(self, text: str, add_special_tokens: bool = False) -> List[int]:
|
|
24
|
+
# every label we care about is one token; anything else is "long"
|
|
25
|
+
if re.fullmatch(r" ?([A-Z]|\d|Yes|No)", text):
|
|
26
|
+
key = text.strip()
|
|
27
|
+
if key not in self._vocab:
|
|
28
|
+
self._vocab[key] = 1000 + len(self._vocab)
|
|
29
|
+
return [self._vocab[key]]
|
|
30
|
+
return [1, 2]
|
|
31
|
+
|
|
32
|
+
def id_to_label(self, tid: int) -> str:
|
|
33
|
+
for k, v in self._vocab.items():
|
|
34
|
+
if v == tid:
|
|
35
|
+
return k
|
|
36
|
+
raise KeyError(tid)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class FakeBackend:
|
|
40
|
+
"""logit(position j, option o) = content(state, o) + position_bias[j] + label_prior[label_j]
|
|
41
|
+
|
|
42
|
+
content is 0 on content-free probes, so the prior is exactly the bias term.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
def __init__(self, content: Callable[[str, str], float],
|
|
46
|
+
position_bias: Optional[Sequence[float]] = None,
|
|
47
|
+
label_prior: Optional[Dict[str, float]] = None,
|
|
48
|
+
temperature: float = 1.0):
|
|
49
|
+
self.name = "fake"
|
|
50
|
+
self.tokenizer = FakeTokenizer()
|
|
51
|
+
self.content = content
|
|
52
|
+
self.position_bias = list(position_bias or [])
|
|
53
|
+
self.label_prior = dict(label_prior or {})
|
|
54
|
+
self.temperature = temperature
|
|
55
|
+
self.calls = 0
|
|
56
|
+
self.prompts_seen = 0
|
|
57
|
+
|
|
58
|
+
def _parse(self, prompt: str):
|
|
59
|
+
state = prompt.split("State:\n", 1)[1].split("\n\nQuestion:", 1)[0]
|
|
60
|
+
if state == "(empty)":
|
|
61
|
+
state = ""
|
|
62
|
+
labels, options = [], []
|
|
63
|
+
for line in prompt.splitlines():
|
|
64
|
+
m = _OPT_LINE.match(line)
|
|
65
|
+
if m:
|
|
66
|
+
labels.append(m.group(1))
|
|
67
|
+
options.append(m.group(2))
|
|
68
|
+
m = _NOUL_LINE.match(line)
|
|
69
|
+
if m:
|
|
70
|
+
labels = [m.group(1), m.group(2)]
|
|
71
|
+
options = list(labels)
|
|
72
|
+
return state, labels, options
|
|
73
|
+
|
|
74
|
+
def next_token_logprobs(self, prompts: Sequence[str],
|
|
75
|
+
token_ids: Sequence[Sequence[int]]) -> List[np.ndarray]:
|
|
76
|
+
self.calls += 1
|
|
77
|
+
self.prompts_seen += len(prompts)
|
|
78
|
+
out = []
|
|
79
|
+
for prompt, ids in zip(prompts, token_ids):
|
|
80
|
+
state, labels, options = self._parse(prompt)
|
|
81
|
+
is_probe = state in DEFAULT_PROBES
|
|
82
|
+
logits = np.zeros(len(ids))
|
|
83
|
+
by_label = {self.tokenizer.id_to_label(t): k for k, t in enumerate(ids)}
|
|
84
|
+
for j, (lab, opt) in enumerate(zip(labels, options)):
|
|
85
|
+
z = 0.0 if is_probe else self.content(state, opt)
|
|
86
|
+
if j < len(self.position_bias):
|
|
87
|
+
z += self.position_bias[j]
|
|
88
|
+
z += self.label_prior.get(lab, 0.0)
|
|
89
|
+
logits[by_label[lab]] = z / self.temperature
|
|
90
|
+
# full-vocab log-softmax: pretend a bit of mass lives elsewhere
|
|
91
|
+
z = np.concatenate([logits, [-5.0]])
|
|
92
|
+
lp = z - np.log(np.exp(z - z.max()).sum()) - z.max()
|
|
93
|
+
out.append(lp[:-1])
|
|
94
|
+
return out
|