Text Classification
Transformers
ONNX
Safetensors
English
Portuguese
modernbert
feature-extraction
encoder
typed-decisions
decision-index
cpu
decision-model
text-embeddings-inference
Instructions to use Lukitaduarte/dinah-0-apache with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Lukitaduarte/dinah-0-apache with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="Lukitaduarte/dinah-0-apache")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModel tokenizer = AutoTokenizer.from_pretrained("Lukitaduarte/dinah-0-apache") model = AutoModel.from_pretrained("Lukitaduarte/dinah-0-apache", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Add Dinah-0 Apache: Dinah-0 retrained without non-commercial data
Browse files- LICENSE +202 -0
- README.md +175 -0
- config.json +93 -0
- decision_ai.json +39 -0
- decision_index_engine.py +59 -0
- dinah.py +256 -0
- model.safetensors +3 -0
- onnx/model_8bit.onnx +3 -0
- onnx/model_int8.onnx +3 -0
- special_tokens_map.json +8 -0
- tokenizer.json +0 -0
- tokenizer_config.json +12 -0
LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Apache License
|
| 3 |
+
Version 2.0, January 2004
|
| 4 |
+
http://www.apache.org/licenses/
|
| 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
| 178 |
+
|
| 179 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 180 |
+
|
| 181 |
+
To apply the Apache License to your work, attach the following
|
| 182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 183 |
+
replaced with your own identifying information. (Don't include
|
| 184 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 185 |
+
comment syntax for the file format. We also recommend that a
|
| 186 |
+
file or class name and description of purpose be included on the
|
| 187 |
+
same "printed page" as the copyright notice for easier
|
| 188 |
+
identification within third-party archives.
|
| 189 |
+
|
| 190 |
+
Copyright [yyyy] [name of copyright owner]
|
| 191 |
+
|
| 192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 193 |
+
you may not use this file except in compliance with the License.
|
| 194 |
+
You may obtain a copy of the License at
|
| 195 |
+
|
| 196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 197 |
+
|
| 198 |
+
Unless required by applicable law or agreed to in writing, software
|
| 199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 201 |
+
See the License for the specific language governing permissions and
|
| 202 |
+
limitations under the License.
|
README.md
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
- pt
|
| 6 |
+
base_model: Tropic-AI/moBERTo
|
| 7 |
+
library_name: transformers
|
| 8 |
+
pipeline_tag: text-classification
|
| 9 |
+
tags:
|
| 10 |
+
- modernbert
|
| 11 |
+
- encoder
|
| 12 |
+
- typed-decisions
|
| 13 |
+
- decision-index
|
| 14 |
+
- onnx
|
| 15 |
+
- cpu
|
| 16 |
+
- decision-model
|
| 17 |
+
---
|
| 18 |
+
|
| 19 |
+
# Dinah-0 Apache
|
| 20 |
+
|
| 21 |
+
**The same Dinah-0, retrained without non-commercial data and released under Apache-2.0: a 150M-parameter encoder that makes typed decisions, in English and Portuguese, on a CPU.**
|
| 22 |
+
|
| 23 |
+
This is not a new version. It is [Dinah-0](https://huggingface.co/Lukitaduarte/dinah-0) rebuilt for commercial use. Dinah-0 was trained on a few thousand items from RACE and MCTest and is therefore released under CC BY-NC 4.0. Dinah-0 Apache starts from a lineage with no non-commercial source and drops those items. Same architecture, same question format (`choice`, `noul`, `score`, with probabilities and confidence), same 8,192-token context. It scores about 0.2 points lower on the Decision Index than Dinah-0, which is the price of the clean license. Not affiliated with TypeSafe.
|
| 24 |
+
|
| 25 |
+
- Apache-2.0 weights, ONNX files (int8 and 8-bit) and inference code
|
| 26 |
+
- Decision Index 0.3 public index **25.86** (official kit run), against 26.06 for Dinah-0
|
| 27 |
+
- On par with Dinah-0 on English, Portuguese and chess guard sets
|
| 28 |
+
|
| 29 |
+
## What it does
|
| 30 |
+
|
| 31 |
+
It reads a question (instructions, state and a set of options) and returns a probability distribution over the options. The same model answers three question types:
|
| 32 |
+
|
| 33 |
+
| Type | Output |
|
| 34 |
+
|---|---|
|
| 35 |
+
| `choice` | the chosen label, a confidence and the probability of every label |
|
| 36 |
+
| `noul` | the probability that a statement is true |
|
| 37 |
+
| `score` | the expected value on an ordered rubric, plus confidence and probabilities |
|
| 38 |
+
|
| 39 |
+
It does not generate text. It is built for classification, routing, tool selection, extraction checks and similar decisions where a small, fast and cheap model is enough.
|
| 40 |
+
|
| 41 |
+
## Results
|
| 42 |
+
|
| 43 |
+
### Decision Index 0.3
|
| 44 |
+
|
| 45 |
+
Official run of the [Decision Index](https://github.com/apolinario/decision-index) kit with the engine in this repository (`decision_index_engine.py`), edition 0.3, on one NVIDIA RTX 5090, one process per variant. 140,620 requests run; 140,178 are scoreable after the kit's exclusions, all with a result except 8 refused as unsupported. In total 324 requests do not fit in 8,192 tokens and are refused (nothing is truncated).
|
| 46 |
+
|
| 47 |
+
| | Public index (balanced skill) | Raw index |
|
| 48 |
+
|---|---:|---:|
|
| 49 |
+
| **Dinah-0 Apache** | **25.86** | 44.50 |
|
| 50 |
+
| Dinah-0 (CC BY-NC 4.0, from the live board) | 26.06 | n/d |
|
| 51 |
+
|
| 52 |
+
The calibration described below changes probabilities and confidence but not a single chosen option, so the index is identical with and without it (25.86 both ways, checked on all 314,940 answers).
|
| 53 |
+
|
| 54 |
+
The raw results of this run are published for auditing in [Lukitaduarte/dinah-0-decision-index-results](https://huggingface.co/datasets/Lukitaduarte/dinah-0-decision-index-results) under `runs/dinah-0-apache/`.
|
| 55 |
+
|
| 56 |
+
### Guard sets
|
| 57 |
+
|
| 58 |
+
Held-out sets of 1,000 items each, accuracy:
|
| 59 |
+
|
| 60 |
+
| Set | Dinah-0 | Dinah-0 Apache |
|
| 61 |
+
|---|---:|---:|
|
| 62 |
+
| Typed decisions, English | 0.78 | 0.789 |
|
| 63 |
+
| Typed decisions, Portuguese | 0.784 | 0.786 |
|
| 64 |
+
| Chess puzzles | 0.59 | 0.587 |
|
| 65 |
+
|
| 66 |
+
Dinah-0 Apache is a weight average (50/50) of two checkpoints trained in sequence from the same starting point, one favoring tools and new domains and one restoring Portuguese. No benchmark test row was used for training.
|
| 67 |
+
|
| 68 |
+
## Calibration
|
| 69 |
+
|
| 70 |
+
Two numbers come out of each answer and they mean different things:
|
| 71 |
+
|
| 72 |
+
- **`probabilities`** estimate the distribution of the label. The typed-decision labels are distributions (the mean mass of the top option is about 0.66), so the top probability is not the chance of being right and is usually lower than the accuracy.
|
| 73 |
+
- **`confidence`** estimates the chance that the chosen option is right.
|
| 74 |
+
|
| 75 |
+
Both are calibrated inside `dinah.py` (settings in `config.json`, key `dinah.calibration`): one temperature per question type and number of options (2 to 9) for the probabilities, and a Platt map for the confidence. They were fit on the even-indexed half of the English and Portuguese typed-decision test sets. On the other half, which was not used for fitting, the expected calibration error of `confidence` is 0.069 (English) and 0.060 (Portuguese). Treat that as the figure for in-distribution questions and measure again on your own domain before relying on it.
|
| 76 |
+
|
| 77 |
+
## Usage
|
| 78 |
+
|
| 79 |
+
```python
|
| 80 |
+
from dinah import Dinah, DinahONNX
|
| 81 |
+
|
| 82 |
+
model = Dinah.from_pretrained("Lukitaduarte/dinah-0-apache") # PyTorch, fp32 weights
|
| 83 |
+
model = DinahONNX.from_pretrained("Lukitaduarte/dinah-0-apache") # onnxruntime, int8, CPU
|
| 84 |
+
|
| 85 |
+
model.choice(state="The package arrived broken.",
|
| 86 |
+
criteria={"refund": "Customer wants money back", "replace": "Customer wants a new unit"},
|
| 87 |
+
instructions="What does the customer want?")
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
Files:
|
| 91 |
+
|
| 92 |
+
| File | What it is |
|
| 93 |
+
|---|---|
|
| 94 |
+
| `model.safetensors` | fp32 weights for the PyTorch backend |
|
| 95 |
+
| `onnx/model_int8.onnx` | int8, 151 MB, the default CPU backend of `dinah.py` |
|
| 96 |
+
| `onnx/model_8bit.onnx` | 8-bit weights, 165 MB, listed in `decision_ai.json` |
|
| 97 |
+
| `dinah.py` | minimal inference code (PyTorch and ONNX backends) |
|
| 98 |
+
| `decision_index_engine.py` | engine used to run the Decision Index kit |
|
| 99 |
+
| `decision_ai.json` | manifest for the Decision AI runtime |
|
| 100 |
+
|
| 101 |
+
ONNX parity with PyTorch on real items: identical argmax in 100% of 64 items, maximum probability difference 2e-5.
|
| 102 |
+
|
| 103 |
+
## Training data and licenses
|
| 104 |
+
|
| 105 |
+
Dinah-0 Apache was trained in stages from [Tropic-AI/moBERTo](https://huggingface.co/Tropic-AI/moBERTo) (Apache-2.0). Each dataset is listed with the license its own card declares.
|
| 106 |
+
|
| 107 |
+
| Source | License |
|
| 108 |
+
|---|---|
|
| 109 |
+
| ZefanCai/Open-Jev | CC0-1.0 |
|
| 110 |
+
| LocalLLaMA/typed-decisions | Apache-2.0 |
|
| 111 |
+
| typed-decisions-pt (translated with Qwen3-4B, Apache-2.0) | Apache-2.0 |
|
| 112 |
+
| Lichess puzzles | CC0-1.0 |
|
| 113 |
+
| google-deepmind/searchless_chess (ChessBench) | Apache-2.0 |
|
| 114 |
+
| AmazonScience/massive | CC BY 4.0 |
|
| 115 |
+
| Bitext customer support | CDLA-Sharing-1.0 |
|
| 116 |
+
| ESCI | Apache-2.0 |
|
| 117 |
+
| WANLI | CC BY 4.0 |
|
| 118 |
+
| SNLI | CC BY-SA 4.0 |
|
| 119 |
+
| HoVer | CC BY-SA 4.0 |
|
| 120 |
+
| CommonsenseQA | MIT |
|
| 121 |
+
| Cosmos QA | CC BY 4.0 |
|
| 122 |
+
| BoolQ | CC BY-SA 3.0 |
|
| 123 |
+
| HellaSwag | MIT |
|
| 124 |
+
| WinoGrande | Apache-2.0 |
|
| 125 |
+
| ARC (train split) | CC BY-SA 4.0 |
|
| 126 |
+
| QASC | CC BY 4.0 |
|
| 127 |
+
| StrategyQA | MIT |
|
| 128 |
+
| bAbI-NLI | BSD |
|
| 129 |
+
| BIG-bench tasks (tasksource, BBH tasks excluded) | Apache-2.0 |
|
| 130 |
+
| MMLU auxiliary train (ARC and OpenBookQA parts only) | MIT |
|
| 131 |
+
| PubMedQA | MIT |
|
| 132 |
+
| MedMCQA | Apache-2.0 |
|
| 133 |
+
| GoEmotions | Apache-2.0 |
|
| 134 |
+
| Civil Comments | CC0-1.0 |
|
| 135 |
+
| twitter-financial-news-sentiment | MIT |
|
| 136 |
+
| financial-tweets-sentiment | MIT |
|
| 137 |
+
| NOSIBLE financial-sentiment | ODC-By |
|
| 138 |
+
| FinQA hallucination detection | MIT |
|
| 139 |
+
| CUAD | CC BY 4.0 |
|
| 140 |
+
| BANKING77 | CC BY 4.0 |
|
| 141 |
+
| CLINC150 | CC BY 3.0 |
|
| 142 |
+
| ContractNLI | CC BY 4.0 |
|
| 143 |
+
| IBM Claim Stance | CC BY 3.0 |
|
| 144 |
+
| HaluEval | Apache-2.0 |
|
| 145 |
+
| GSM8K | MIT |
|
| 146 |
+
| CLadder | MIT |
|
| 147 |
+
| iSarcasmEval | MIT |
|
| 148 |
+
| B2W-Reviews01 | CC BY 4.0 |
|
| 149 |
+
| multilingual-sentiments (pt) | Apache-2.0 |
|
| 150 |
+
| jurisprudencias_br | CC BY 4.0 |
|
| 151 |
+
| FaQuAD-NLI | CC BY 4.0 |
|
| 152 |
+
| FAQ_BACEN | Apache-2.0 |
|
| 153 |
+
| ExtraGLUE (RTE and COPA, pt) | MIT |
|
| 154 |
+
| glaiveai/glaive-function-calling-v2 | Apache-2.0 |
|
| 155 |
+
| Team-ACE/ToolACE | Apache-2.0 |
|
| 156 |
+
| NousResearch/hermes-function-calling-v1 | Apache-2.0 |
|
| 157 |
+
| nvidia/When2Call | CC BY 4.0 |
|
| 158 |
+
| Dizzzy0x00/LLMGen-Phishing-Email-Dataset | Apache-2.0 |
|
| 159 |
+
| kudzaiprichard/aura-phishing-email-corpus (SpamAssassin part) | CC BY 4.0 |
|
| 160 |
+
| Synthetic phishing emails, written with openai/gpt-oss-120b (signals and labels set by code) | Apache-2.0 |
|
| 161 |
+
| English to Portuguese translations of NLI, HellaSwag, Cosmos QA, CommonsenseQA and BoolQ items, made with Helsinki-NLP/opus-mt-tc-big-en-pt | CC BY 4.0 |
|
| 162 |
+
| Programmatic skills (arithmetic, dates, units, sorting, graphs, code output): generated by our own scripts | Apache-2.0 |
|
| 163 |
+
|
| 164 |
+
Datasets under CC BY-SA and CDLA-Sharing are used for training only and are not redistributed here.
|
| 165 |
+
|
| 166 |
+
## Limits
|
| 167 |
+
|
| 168 |
+
- 8,192-token context. Nothing is truncated: a longer request raises `RequestTooLong`.
|
| 169 |
+
- English and Portuguese only. Other languages work to the extent the base model saw them, and were not evaluated.
|
| 170 |
+
- It does not generate text and it does not know facts beyond its training: on knowledge-heavy benchmarks (MMLU, GPQA, HLE) it is far behind decoder models with billions of parameters.
|
| 171 |
+
- Confidence is calibrated on the training distribution. On a new domain, measure it before trusting it.
|
| 172 |
+
|
| 173 |
+
## License
|
| 174 |
+
|
| 175 |
+
Apache-2.0. See `LICENSE`.
|
config.json
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"ModernBertModel"
|
| 4 |
+
],
|
| 5 |
+
"attention_bias": false,
|
| 6 |
+
"attention_dropout": 0.0,
|
| 7 |
+
"bos_token_id": 50281,
|
| 8 |
+
"classifier_activation": "silu",
|
| 9 |
+
"classifier_bias": false,
|
| 10 |
+
"classifier_dropout": 0.0,
|
| 11 |
+
"classifier_pooling": "mean",
|
| 12 |
+
"cls_token_id": 50281,
|
| 13 |
+
"decoder_bias": true,
|
| 14 |
+
"deterministic_flash_attn": false,
|
| 15 |
+
"embedding_dropout": 0.0,
|
| 16 |
+
"eos_token_id": 50282,
|
| 17 |
+
"global_attn_every_n_layers": 3,
|
| 18 |
+
"global_rope_theta": 160000.0,
|
| 19 |
+
"gradient_checkpointing": false,
|
| 20 |
+
"hidden_activation": "gelu",
|
| 21 |
+
"hidden_size": 768,
|
| 22 |
+
"initializer_cutoff_factor": 2.0,
|
| 23 |
+
"initializer_range": 0.02,
|
| 24 |
+
"intermediate_size": 1152,
|
| 25 |
+
"layer_norm_eps": 1e-05,
|
| 26 |
+
"local_attention": 128,
|
| 27 |
+
"local_rope_theta": 10000.0,
|
| 28 |
+
"max_position_embeddings": 8192,
|
| 29 |
+
"mlp_bias": false,
|
| 30 |
+
"mlp_dropout": 0.0,
|
| 31 |
+
"model_type": "modernbert",
|
| 32 |
+
"norm_bias": false,
|
| 33 |
+
"norm_eps": 1e-05,
|
| 34 |
+
"num_attention_heads": 12,
|
| 35 |
+
"num_hidden_layers": 22,
|
| 36 |
+
"pad_token_id": 50283,
|
| 37 |
+
"position_embedding_type": "absolute",
|
| 38 |
+
"sep_token_id": 50282,
|
| 39 |
+
"tie_word_embeddings": true,
|
| 40 |
+
"torch_dtype": "float32",
|
| 41 |
+
"transformers_version": "4.48.0",
|
| 42 |
+
"vocab_size": 50369,
|
| 43 |
+
"dinah": {
|
| 44 |
+
"opt_token": "[OPT]",
|
| 45 |
+
"opt_token_id": 50368,
|
| 46 |
+
"question_types": {
|
| 47 |
+
"noul": 0,
|
| 48 |
+
"choice": 1,
|
| 49 |
+
"score": 2
|
| 50 |
+
},
|
| 51 |
+
"max_length": 8192,
|
| 52 |
+
"pad_multiple": 64,
|
| 53 |
+
"calibration": {
|
| 54 |
+
"temperature": [
|
| 55 |
+
[
|
| 56 |
+
1.3,
|
| 57 |
+
1.0,
|
| 58 |
+
1.0,
|
| 59 |
+
1.0,
|
| 60 |
+
1.0,
|
| 61 |
+
1.0,
|
| 62 |
+
1.0,
|
| 63 |
+
1.0
|
| 64 |
+
],
|
| 65 |
+
[
|
| 66 |
+
1.0,
|
| 67 |
+
1.0,
|
| 68 |
+
1.4,
|
| 69 |
+
1.35,
|
| 70 |
+
1.0,
|
| 71 |
+
1.0,
|
| 72 |
+
1.0,
|
| 73 |
+
1.0
|
| 74 |
+
],
|
| 75 |
+
[
|
| 76 |
+
1.0,
|
| 77 |
+
1.0,
|
| 78 |
+
1.3,
|
| 79 |
+
1.3,
|
| 80 |
+
1.0,
|
| 81 |
+
1.0,
|
| 82 |
+
1.0,
|
| 83 |
+
1.0
|
| 84 |
+
]
|
| 85 |
+
],
|
| 86 |
+
"platt": [
|
| 87 |
+
0.7,
|
| 88 |
+
-0.1
|
| 89 |
+
],
|
| 90 |
+
"note": "temperature[question_type][min(max(k,2),9)-2] divides the logits (fit on soft-label NLL); platt maps the confidence logit: sigmoid(a*z+b). Fit on half of the typed-decisions test sets (even indices); the other half is held out."
|
| 91 |
+
}
|
| 92 |
+
}
|
| 93 |
+
}
|
decision_ai.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"format": "decision-ai/option-reader@1",
|
| 3 |
+
"name": "Dinah-0 Apache",
|
| 4 |
+
"license": "apache-2.0",
|
| 5 |
+
"homepage": "https://huggingface.co/Lukitaduarte/dinah-0-apache",
|
| 6 |
+
"files": {
|
| 7 |
+
"model": "onnx/model_8bit.onnx",
|
| 8 |
+
"tokenizer": "tokenizer.json"
|
| 9 |
+
},
|
| 10 |
+
"sha256": {
|
| 11 |
+
"onnx/model_8bit.onnx": "412e14a95c7cb8eb8a95feb9b0cbf4c05f9177418233be5010590d73923c7cf6",
|
| 12 |
+
"tokenizer.json": "edeac9e7b2f170022cefd1c7b396ebca3ac9c57f2f93604844cb7fb16b1a71ca"
|
| 13 |
+
},
|
| 14 |
+
"max_length": 8192,
|
| 15 |
+
"pad_multiple": 64,
|
| 16 |
+
"tokens": {
|
| 17 |
+
"cls": "[CLS]",
|
| 18 |
+
"sep": "[SEP]",
|
| 19 |
+
"pad": "[PAD]",
|
| 20 |
+
"option": "[OPT]"
|
| 21 |
+
},
|
| 22 |
+
"question_types": {
|
| 23 |
+
"noul": 0,
|
| 24 |
+
"choice": 1,
|
| 25 |
+
"score": 2
|
| 26 |
+
},
|
| 27 |
+
"noul_false_default": "The statement above is false.",
|
| 28 |
+
"inputs": {
|
| 29 |
+
"ids": "ids",
|
| 30 |
+
"pad_mask": "pad_mask",
|
| 31 |
+
"option_positions": "opt_positions",
|
| 32 |
+
"option_mask": "opt_mask",
|
| 33 |
+
"question_type": "qtype"
|
| 34 |
+
},
|
| 35 |
+
"outputs": {
|
| 36 |
+
"logits": "logits",
|
| 37 |
+
"confidence_logit": "conf_logit"
|
| 38 |
+
}
|
| 39 |
+
}
|
decision_index_engine.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Decision Index engine for Dinah-0 (https://github.com/apolinario/decision-index).
|
| 2 |
+
|
| 3 |
+
python -m decision_index run --engine decision_index_engine:DinahEngine \
|
| 4 |
+
--option revision=<commit> --edition 0.2.1 --suite-dir suite-0.2 --out runs/dinah-0-apache
|
| 5 |
+
|
| 6 |
+
Put this file next to `dinah.py` (both are in the model repository) and on PYTHONPATH.
|
| 7 |
+
Kit rules: nothing is truncated and no option is dropped. A request that does not fit in 8,192 tokens,
|
| 8 |
+
or a question type the model does not support, raises `Unsupported`.
|
| 9 |
+
|
| 10 |
+
One call = one request (a state and several questions); all questions of a request go through the
|
| 11 |
+
encoder together, 16 at a time. Probabilities are the softmax over the option logits; the confidence
|
| 12 |
+
of a `choice` answer comes from the confidence head.
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import sys
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
from decision_index.engines import Engine, Unsupported
|
| 20 |
+
|
| 21 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 22 |
+
from dinah import Dinah, RequestTooLong # noqa: E402
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class DinahEngine(Engine):
|
| 26 |
+
name = "dinah-0-apache"
|
| 27 |
+
latency = ("In-process request wall time: tokenization plus one encoder pass per request "
|
| 28 |
+
"(all questions of the request batched together); excludes model loading.")
|
| 29 |
+
|
| 30 |
+
def __init__(self, repo: str = "Lukitaduarte/dinah-0-apache", revision: str | None = None, device: str | None = None,
|
| 31 |
+
dtype: str | None = None, batch_size: int = 16, calibrate: str | bool = True, **options):
|
| 32 |
+
super().__init__(**options)
|
| 33 |
+
self.model = Dinah.from_pretrained(repo, device=device, dtype=dtype, revision=revision)
|
| 34 |
+
self.calibrated = str(calibrate).lower() not in ("0", "false", "no", "off")
|
| 35 |
+
if not self.calibrated: # raw logits and raw confidence head, for comparison with the calibrated run
|
| 36 |
+
self.model.temperature, self.model.platt = None, None
|
| 37 |
+
self.batch_size = int(batch_size)
|
| 38 |
+
self.provenance = {"repo": repo, "revision": revision or "main", "device": self.model.device,
|
| 39 |
+
"dtype": self.model.dtype, "max_length": self.model.max_length, "calibrated": self.calibrated,
|
| 40 |
+
"truncation": "none: requests above 8,192 tokens raise Unsupported"}
|
| 41 |
+
|
| 42 |
+
def __call__(self, state, questions):
|
| 43 |
+
keys = list(questions)
|
| 44 |
+
batch = []
|
| 45 |
+
for key in keys:
|
| 46 |
+
q = questions[key]
|
| 47 |
+
if q["type"] not in ("choice", "noul"):
|
| 48 |
+
raise Unsupported(f"question type {q['type']}")
|
| 49 |
+
batch.append({"type": q["type"], "state": state, "instructions": q.get("instructions"),
|
| 50 |
+
"criteria": q.get("criteria")})
|
| 51 |
+
try:
|
| 52 |
+
answers = self.model.predict(batch, batch_size=self.batch_size)
|
| 53 |
+
except RequestTooLong as e:
|
| 54 |
+
raise Unsupported(f"context window: {e}")
|
| 55 |
+
return {"model": "dinah-0-apache", "answers": dict(zip(keys, answers))}, None
|
| 56 |
+
|
| 57 |
+
def synchronize(self):
|
| 58 |
+
if self.model.device.startswith("cuda"):
|
| 59 |
+
self.model.torch.cuda.synchronize()
|
dinah.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Minimal inference code for Dinah-0 Apache.
|
| 2 |
+
|
| 3 |
+
Dinah-0 Apache is a 150M-parameter encoder (ModernBERT architecture) that answers typed decisions:
|
| 4 |
+
|
| 5 |
+
choice pick one label out of a set -> {"choice", "confidence", "probabilities"}
|
| 6 |
+
noul probability that a statement is true -> {"noul"}
|
| 7 |
+
score expected value on an ordered rubric -> {"score", "confidence", "probabilities"}
|
| 8 |
+
|
| 9 |
+
Every question is read as one sequence
|
| 10 |
+
|
| 11 |
+
[CLS] instructions [SEP] state [SEP] [OPT] option_1 [OPT] option_2 ... [OPT] option_n
|
| 12 |
+
|
| 13 |
+
and each option is scored from the hidden state at its [OPT] marker. Nothing is truncated: a request
|
| 14 |
+
longer than `max_length` (8,192 tokens) raises `RequestTooLong`.
|
| 15 |
+
|
| 16 |
+
Two backends with the same API:
|
| 17 |
+
|
| 18 |
+
from dinah import Dinah, DinahONNX
|
| 19 |
+
model = Dinah.from_pretrained("Lukitaduarte/dinah-0-apache") # PyTorch, fp32 weights
|
| 20 |
+
model = DinahONNX.from_pretrained("Lukitaduarte/dinah-0-apache") # onnxruntime, int8, CPU
|
| 21 |
+
|
| 22 |
+
model.choice(state="The package arrived broken.",
|
| 23 |
+
criteria={"refund": "Customer wants money back", "replace": "Customer wants a new unit"},
|
| 24 |
+
instructions="What does the customer want?")
|
| 25 |
+
"""
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
|
| 28 |
+
import json
|
| 29 |
+
import math
|
| 30 |
+
from pathlib import Path
|
| 31 |
+
from typing import Any
|
| 32 |
+
|
| 33 |
+
import numpy as np
|
| 34 |
+
|
| 35 |
+
QUESTION_TYPES = {"noul": 0, "choice": 1, "score": 2}
|
| 36 |
+
NEG = -1e4
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class RequestTooLong(ValueError):
|
| 40 |
+
"""The request does not fit in `max_length` tokens. Nothing is ever truncated."""
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def render(content: Any) -> str:
|
| 44 |
+
"""Strings are stripped; objects and arrays become compact JSON with sorted keys (as in training)."""
|
| 45 |
+
if content is None:
|
| 46 |
+
return ""
|
| 47 |
+
if isinstance(content, str):
|
| 48 |
+
return content.strip()
|
| 49 |
+
return json.dumps(content, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _resolve(path_or_repo: str | Path, files: list[str], revision: str | None = None) -> Path:
|
| 53 |
+
path = Path(path_or_repo)
|
| 54 |
+
if path.is_dir():
|
| 55 |
+
return path
|
| 56 |
+
from huggingface_hub import snapshot_download
|
| 57 |
+
return Path(snapshot_download(str(path_or_repo), allow_patterns=files, revision=revision))
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class _Base:
|
| 61 |
+
"""Tokenization, batching and the typed-decision API shared by both backends."""
|
| 62 |
+
|
| 63 |
+
def __init__(self, directory: Path):
|
| 64 |
+
from transformers import AutoTokenizer
|
| 65 |
+
self.config = json.loads((directory / "config.json").read_text())
|
| 66 |
+
extra = self.config["dinah"]
|
| 67 |
+
self.tokenizer = AutoTokenizer.from_pretrained(str(directory))
|
| 68 |
+
self.opt_id = self.tokenizer.convert_tokens_to_ids(extra["opt_token"])
|
| 69 |
+
assert self.opt_id == extra["opt_token_id"], "tokenizer does not match the model"
|
| 70 |
+
self.max_length = extra["max_length"]
|
| 71 |
+
self.pad_multiple = extra["pad_multiple"]
|
| 72 |
+
cal = extra.get("calibration")
|
| 73 |
+
self.temperature = np.array(cal["temperature"], dtype=np.float64) if cal else None
|
| 74 |
+
self.platt = tuple(cal["platt"]) if cal else None
|
| 75 |
+
|
| 76 |
+
def _ids(self, text: str) -> list[int]:
|
| 77 |
+
return self.tokenizer(text, add_special_tokens=False)["input_ids"] if text else []
|
| 78 |
+
|
| 79 |
+
def _encode(self, instructions: Any, state: Any, options: list[Any]) -> tuple[list[int], list[int]]:
|
| 80 |
+
t = self.tokenizer
|
| 81 |
+
ids = [t.cls_token_id, *self._ids(render(instructions)), t.sep_token_id, *self._ids(render(state)), t.sep_token_id]
|
| 82 |
+
positions = []
|
| 83 |
+
for option in options:
|
| 84 |
+
positions.append(len(ids))
|
| 85 |
+
ids += [self.opt_id, *self._ids(render(option))]
|
| 86 |
+
if len(ids) > self.max_length:
|
| 87 |
+
raise RequestTooLong(f"request needs {len(ids)} tokens, above max_length={self.max_length} (no truncation)")
|
| 88 |
+
return ids, positions
|
| 89 |
+
|
| 90 |
+
def _batch(self, items: list[tuple[list[int], list[int], int]]) -> dict[str, np.ndarray]:
|
| 91 |
+
b = len(items)
|
| 92 |
+
length = max(len(ids) for ids, _, _ in items)
|
| 93 |
+
length = -(-length // self.pad_multiple) * self.pad_multiple
|
| 94 |
+
n = max(len(pos) for _, pos, _ in items)
|
| 95 |
+
batch = {"ids": np.full((b, length), self.tokenizer.pad_token_id, dtype=np.int64),
|
| 96 |
+
"pad_mask": np.zeros((b, length), dtype=bool),
|
| 97 |
+
"opt_positions": np.zeros((b, n), dtype=np.int64), # padding points at [CLS], masked below
|
| 98 |
+
"opt_mask": np.zeros((b, n), dtype=bool),
|
| 99 |
+
"qtype": np.array([q for _, _, q in items], dtype=np.int64)}
|
| 100 |
+
for i, (ids, pos, _) in enumerate(items):
|
| 101 |
+
batch["ids"][i, :len(ids)] = ids
|
| 102 |
+
batch["pad_mask"][i, :len(ids)] = True
|
| 103 |
+
batch["opt_positions"][i, :len(pos)] = pos
|
| 104 |
+
batch["opt_mask"][i, :len(pos)] = True
|
| 105 |
+
return batch
|
| 106 |
+
|
| 107 |
+
def _forward(self, batch: dict[str, np.ndarray]) -> tuple[np.ndarray, np.ndarray]:
|
| 108 |
+
raise NotImplementedError
|
| 109 |
+
|
| 110 |
+
def predict(self, questions: list[dict[str, Any]], batch_size: int = 16) -> list[dict[str, Any]]:
|
| 111 |
+
"""Answer a list of questions. Each question is a dict with `type` ("choice", "noul" or "score"),
|
| 112 |
+
`state`, optional `instructions`, and `criteria`:
|
| 113 |
+
choice: {label: description or None} (None means the label is its own description)
|
| 114 |
+
noul: {"true": ..., "false": ...} describing both poles (strongly recommended)
|
| 115 |
+
score: list of descriptions, ordered from lowest (0) to highest
|
| 116 |
+
"""
|
| 117 |
+
encoded, meta = [], []
|
| 118 |
+
for q in questions:
|
| 119 |
+
kind = q["type"]
|
| 120 |
+
if kind == "choice":
|
| 121 |
+
labels = list(q["criteria"])
|
| 122 |
+
options = [d if d is not None else label for label, d in q["criteria"].items()]
|
| 123 |
+
elif kind == "noul":
|
| 124 |
+
c = q.get("criteria") or {}
|
| 125 |
+
options = [c.get("false") or "The statement above is false.", c.get("true") or q.get("instructions")]
|
| 126 |
+
labels = None
|
| 127 |
+
elif kind == "score":
|
| 128 |
+
options, labels = list(q["criteria"]), None
|
| 129 |
+
else:
|
| 130 |
+
raise ValueError(f"unknown question type {kind!r}")
|
| 131 |
+
if len(options) < 2:
|
| 132 |
+
raise ValueError("a question needs at least 2 options")
|
| 133 |
+
ids, pos = self._encode(q.get("instructions"), q.get("state"), options)
|
| 134 |
+
encoded.append((ids, pos, QUESTION_TYPES[kind]))
|
| 135 |
+
meta.append((kind, labels, options))
|
| 136 |
+
|
| 137 |
+
answers = []
|
| 138 |
+
for start in range(0, len(encoded), batch_size):
|
| 139 |
+
logits, conf_logits = self._forward(self._batch(encoded[start:start + batch_size]))
|
| 140 |
+
for j, (kind, labels, options) in enumerate(meta[start:start + batch_size]):
|
| 141 |
+
z = logits[j, :len(options)].astype(np.float64)
|
| 142 |
+
if self.temperature is not None: # one temperature per (question type, number of options 2..9)
|
| 143 |
+
z = z / self.temperature[QUESTION_TYPES[kind], min(max(len(options), 2), 9) - 2]
|
| 144 |
+
p = np.exp(z - z.max()); p /= p.sum()
|
| 145 |
+
c = float(conf_logits[j])
|
| 146 |
+
if self.platt is not None:
|
| 147 |
+
c = self.platt[0] * c + self.platt[1]
|
| 148 |
+
confidence = 1.0 / (1.0 + math.exp(-max(min(c, 30.0), -30.0)))
|
| 149 |
+
if kind == "noul":
|
| 150 |
+
answers.append({"type": "noul", "noul": float(p[1])})
|
| 151 |
+
elif kind == "choice":
|
| 152 |
+
best = int(p.argmax())
|
| 153 |
+
answers.append({"type": "choice", "choice": labels[best], "confidence": confidence,
|
| 154 |
+
"probabilities": {l: float(x) for l, x in zip(labels, p)}})
|
| 155 |
+
else:
|
| 156 |
+
answers.append({"type": "score", "score": float(sum(i * x for i, x in enumerate(p))),
|
| 157 |
+
"confidence": confidence, "probabilities": {str(i): float(x) for i, x in enumerate(p)}})
|
| 158 |
+
return answers
|
| 159 |
+
|
| 160 |
+
def choice(self, state: Any, criteria: dict[str, Any], instructions: Any = None) -> dict[str, Any]:
|
| 161 |
+
return self.predict([{"type": "choice", "state": state, "criteria": criteria, "instructions": instructions}])[0]
|
| 162 |
+
|
| 163 |
+
def noul(self, state: Any, instructions: Any, true: Any = None, false: Any = None) -> dict[str, Any]:
|
| 164 |
+
return self.predict([{"type": "noul", "state": state, "instructions": instructions,
|
| 165 |
+
"criteria": {"true": true, "false": false}}])[0]
|
| 166 |
+
|
| 167 |
+
def score(self, state: Any, criteria: list[Any], instructions: Any = None) -> dict[str, Any]:
|
| 168 |
+
return self.predict([{"type": "score", "state": state, "criteria": criteria, "instructions": instructions}])[0]
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def _confidence_features(probs, mask, qtype):
|
| 172 |
+
"""Shape of the option distribution: top-1, margin, normalized entropy, 1/k and the question type."""
|
| 173 |
+
import torch
|
| 174 |
+
k = mask.sum(-1).clamp(min=2).float()
|
| 175 |
+
top2 = torch.where(mask, probs, torch.zeros_like(probs)).sort(dim=-1, descending=True).values[:, :2]
|
| 176 |
+
entropy = -(probs * probs.clamp(min=1e-9).log()).sum(-1) / k.log()
|
| 177 |
+
onehot = (qtype[:, None] == torch.arange(len(QUESTION_TYPES), device=qtype.device)[None, :]).float()
|
| 178 |
+
return torch.cat([top2[:, :1], top2[:, :1] - top2[:, 1:2], entropy[:, None], (1.0 / k)[:, None], onehot], dim=-1)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
class Dinah(_Base):
|
| 182 |
+
"""PyTorch backend (fp32 weights, model.safetensors). On CUDA it runs under bfloat16 autocast by default."""
|
| 183 |
+
|
| 184 |
+
FILES = ["config.json", "model.safetensors", "tokenizer.json", "tokenizer_config.json", "special_tokens_map.json"]
|
| 185 |
+
|
| 186 |
+
def __init__(self, directory: Path, device: str | None = None, dtype: str | None = None):
|
| 187 |
+
super().__init__(directory)
|
| 188 |
+
import torch
|
| 189 |
+
import torch.nn as nn
|
| 190 |
+
from safetensors.torch import load_file
|
| 191 |
+
from transformers import ModernBertConfig, ModernBertModel
|
| 192 |
+
|
| 193 |
+
cfg = ModernBertConfig(**{k: v for k, v in self.config.items() if k not in ("dinah", "architectures")})
|
| 194 |
+
hidden = cfg.hidden_size
|
| 195 |
+
net = nn.Module()
|
| 196 |
+
net.encoder = ModernBertModel(cfg)
|
| 197 |
+
net.type_embedding = nn.Embedding(len(QUESTION_TYPES), hidden)
|
| 198 |
+
net.scorer = nn.Sequential(nn.LayerNorm(hidden), nn.Dropout(0.0), nn.Linear(hidden, hidden), nn.GELU(), nn.Linear(hidden, 1))
|
| 199 |
+
net.confidence = nn.Module()
|
| 200 |
+
net.confidence.net = nn.Sequential(nn.Linear(7, 64), nn.GELU(), nn.Linear(64, 64), nn.GELU(), nn.Linear(64, 1))
|
| 201 |
+
net.load_state_dict(load_file(str(directory / "model.safetensors")), strict=True)
|
| 202 |
+
self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
|
| 203 |
+
self.dtype = dtype or ("bfloat16" if self.device == "cuda" else "float32")
|
| 204 |
+
self.net = net.to(self.device).eval()
|
| 205 |
+
self.torch = torch
|
| 206 |
+
|
| 207 |
+
@classmethod
|
| 208 |
+
def from_pretrained(cls, path_or_repo: str | Path = "Lukitaduarte/dinah-0-apache", device: str | None = None,
|
| 209 |
+
dtype: str | None = None, revision: str | None = None) -> "Dinah":
|
| 210 |
+
return cls(_resolve(path_or_repo, cls.FILES, revision), device, dtype)
|
| 211 |
+
|
| 212 |
+
def _forward(self, batch):
|
| 213 |
+
torch = self.torch
|
| 214 |
+
t = {k: torch.as_tensor(v, device=self.device) for k, v in batch.items()}
|
| 215 |
+
autocast = self.dtype != "float32" and self.device.startswith("cuda")
|
| 216 |
+
with torch.no_grad(), torch.autocast("cuda", dtype=getattr(torch, self.dtype), enabled=autocast):
|
| 217 |
+
h = self.net.encoder(input_ids=t["ids"], attention_mask=t["pad_mask"]).last_hidden_state
|
| 218 |
+
h = h + self.net.type_embedding(t["qtype"])[:, None, :]
|
| 219 |
+
idx = t["opt_positions"].unsqueeze(-1).expand(-1, -1, h.size(-1))
|
| 220 |
+
logits = self.net.scorer(h.gather(1, idx)).squeeze(-1).float()
|
| 221 |
+
logits = torch.where(t["opt_mask"], logits, torch.full_like(logits, NEG))
|
| 222 |
+
probs = logits.log_softmax(-1).exp() * t["opt_mask"]
|
| 223 |
+
conf = self.net.confidence.net(_confidence_features(probs, t["opt_mask"], t["qtype"])).squeeze(-1)
|
| 224 |
+
return logits.float().cpu().numpy(), conf.float().cpu().numpy()
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
class DinahONNX(_Base):
|
| 228 |
+
"""onnxruntime backend (int8 weights, block-local attention). Made for CPU."""
|
| 229 |
+
|
| 230 |
+
FILES = ["config.json", "onnx/model_int8.onnx", "tokenizer.json", "tokenizer_config.json", "special_tokens_map.json"]
|
| 231 |
+
|
| 232 |
+
def __init__(self, directory: Path, threads: int | None = None):
|
| 233 |
+
super().__init__(directory)
|
| 234 |
+
import onnxruntime as ort
|
| 235 |
+
options = ort.SessionOptions()
|
| 236 |
+
if threads:
|
| 237 |
+
options.intra_op_num_threads = threads
|
| 238 |
+
self.session = ort.InferenceSession(str(directory / "onnx/model_int8.onnx"), options, providers=["CPUExecutionProvider"])
|
| 239 |
+
|
| 240 |
+
@classmethod
|
| 241 |
+
def from_pretrained(cls, path_or_repo: str | Path = "Lukitaduarte/dinah-0-apache", threads: int | None = None,
|
| 242 |
+
revision: str | None = None) -> "DinahONNX":
|
| 243 |
+
return cls(_resolve(path_or_repo, cls.FILES, revision), threads)
|
| 244 |
+
|
| 245 |
+
def _forward(self, batch):
|
| 246 |
+
logits, conf = self.session.run(["logits", "conf_logit"], batch)
|
| 247 |
+
return logits, conf
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
if __name__ == "__main__":
|
| 251 |
+
model = DinahONNX.from_pretrained(".")
|
| 252 |
+
print(model.choice(state="The package arrived broken and I need it for tomorrow.",
|
| 253 |
+
criteria={"refund": "The customer wants their money back",
|
| 254 |
+
"replacement": "The customer wants a new unit sent",
|
| 255 |
+
"complaint": "The customer only wants to complain"},
|
| 256 |
+
instructions="What does the customer want?"))
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7cdb65b6ae003c79188ce7d0fcbe4db63cd247fc632c36a16fd797fb448e6a80
|
| 3 |
+
size 598475136
|
onnx/model_8bit.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:412e14a95c7cb8eb8a95feb9b0cbf4c05f9177418233be5010590d73923c7cf6
|
| 3 |
+
size 164506374
|
onnx/model_int8.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5499edd7b6d0e76c55aef7e89df216fc577686d913ec1a856738a7aad3942f09
|
| 3 |
+
size 150722915
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cls_token": "[CLS]",
|
| 3 |
+
"sep_token": "[SEP]",
|
| 4 |
+
"pad_token": "[PAD]",
|
| 5 |
+
"mask_token": "[MASK]",
|
| 6 |
+
"unk_token": "[UNK]",
|
| 7 |
+
"additional_special_tokens": ["[OPT]"]
|
| 8 |
+
}
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"tokenizer_class": "PreTrainedTokenizerFast",
|
| 3 |
+
"clean_up_tokenization_spaces": true,
|
| 4 |
+
"cls_token": "[CLS]",
|
| 5 |
+
"sep_token": "[SEP]",
|
| 6 |
+
"pad_token": "[PAD]",
|
| 7 |
+
"mask_token": "[MASK]",
|
| 8 |
+
"unk_token": "[UNK]",
|
| 9 |
+
"additional_special_tokens": ["[OPT]"],
|
| 10 |
+
"model_input_names": ["input_ids", "attention_mask"],
|
| 11 |
+
"model_max_length": 8192
|
| 12 |
+
}
|