Commit ·
6d142c6
0
Parent(s):
Release ODM Mini v1 DecisionHead
Browse files- .gitattributes +35 -0
- LICENSE +176 -0
- README.md +145 -0
- config.json +11 -0
- model.safetensors +3 -0
- odm_mini.py +354 -0
.gitattributes
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
LICENSE
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
README.md
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
base_model:
|
| 4 |
+
- Qwen/Qwen3-0.6B
|
| 5 |
+
library_name: pytorch
|
| 6 |
+
tags:
|
| 7 |
+
- agent
|
| 8 |
+
- agentic-ai
|
| 9 |
+
- decision-model
|
| 10 |
+
- tool-selection
|
| 11 |
+
- system-one
|
| 12 |
+
- open-weights
|
| 13 |
+
- qwen
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
# ODM Mini v1
|
| 17 |
+
|
| 18 |
+
**Open-weight local Choice decision head for agent tool selection, built on frozen Qwen3-0.6B.**
|
| 19 |
+
|
| 20 |
+
ODM Mini takes an agent state plus candidate action descriptions and directly ranks the candidates. It produces candidate scores, grouped-softmax probabilities, a selected action, confidence, decision margin, and measured latency. It does **not** generate text.
|
| 21 |
+
|
| 22 |
+
## Model architecture
|
| 23 |
+
|
| 24 |
+
```text
|
| 25 |
+
Frozen Qwen3-0.6B
|
| 26 |
+
→ candidate-description mean pooling
|
| 27 |
+
→ Linear(1024,256)
|
| 28 |
+
→ GELU
|
| 29 |
+
→ Linear(256,1)
|
| 30 |
+
→ grouped softmax
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
Only description-token hidden states are pooled. The candidate ID, prompt headers, state tokens, and padding are excluded from the pooling mask. The Qwen backbone remains frozen.
|
| 34 |
+
|
| 35 |
+
## Size and required backbone
|
| 36 |
+
|
| 37 |
+
The ODM-specific trained DecisionHead is approximately **1.1 MB**. The complete runnable model is substantially larger because it additionally requires the separately downloaded [`Qwen/Qwen3-0.6B`](https://huggingface.co/Qwen/Qwen3-0.6B) backbone. This repository does not redistribute Qwen weights.
|
| 38 |
+
|
| 39 |
+
## Installation and usage
|
| 40 |
+
|
| 41 |
+
```bash
|
| 42 |
+
pip install torch transformers safetensors huggingface_hub
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
The code below downloads this five-file release, imports its deterministic loader without `trust_remote_code=True`, separately obtains Qwen3-0.6B, and performs a Choice:
|
| 46 |
+
|
| 47 |
+
```python
|
| 48 |
+
import sys
|
| 49 |
+
from pathlib import Path
|
| 50 |
+
|
| 51 |
+
from huggingface_hub import snapshot_download
|
| 52 |
+
|
| 53 |
+
release_dir = Path(
|
| 54 |
+
snapshot_download(
|
| 55 |
+
repo_id="samatv256/mini-Jev",
|
| 56 |
+
allow_patterns=[
|
| 57 |
+
"README.md",
|
| 58 |
+
"model.safetensors",
|
| 59 |
+
"config.json",
|
| 60 |
+
"odm_mini.py",
|
| 61 |
+
"LICENSE",
|
| 62 |
+
],
|
| 63 |
+
)
|
| 64 |
+
)
|
| 65 |
+
sys.path.insert(0, str(release_dir))
|
| 66 |
+
|
| 67 |
+
from odm_mini import ODMMiniModel
|
| 68 |
+
|
| 69 |
+
model = ODMMiniModel.from_pretrained("samatv256/mini-Jev")
|
| 70 |
+
|
| 71 |
+
state = {
|
| 72 |
+
"user_request": "Find the current weather in Boston.",
|
| 73 |
+
"available_context": "The user has not provided weather data.",
|
| 74 |
+
}
|
| 75 |
+
candidates = [
|
| 76 |
+
{
|
| 77 |
+
"id": "weather.lookup",
|
| 78 |
+
"description": "Look up current weather for a specified city.",
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"id": "calendar.list",
|
| 82 |
+
"description": "List upcoming calendar events for the user.",
|
| 83 |
+
},
|
| 84 |
+
{
|
| 85 |
+
"id": "control.finish",
|
| 86 |
+
"description": "Finish because the request has already been completed.",
|
| 87 |
+
},
|
| 88 |
+
]
|
| 89 |
+
|
| 90 |
+
choice = model.predict_choice(state=state, candidates=candidates)
|
| 91 |
+
print("selected candidate:", choice.selected)
|
| 92 |
+
print("probabilities:", choice.probabilities)
|
| 93 |
+
print("confidence:", choice.confidence)
|
| 94 |
+
print("decision margin:", choice.decision_margin)
|
| 95 |
+
print("latency (ms):", choice.latency_ms)
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
`ODMMiniModel.from_pretrained()` accepts either the Hub model ID or a local snapshot directory. On CUDA it defaults to BF16 backbone inference; on CPU it defaults to FP32. The DecisionHead is always evaluated in FP32.
|
| 99 |
+
|
| 100 |
+
## Training
|
| 101 |
+
|
| 102 |
+
- 50,000 synthetic training decisions
|
| 103 |
+
- frozen `Qwen/Qwen3-0.6B` backbone
|
| 104 |
+
- DecisionHead-only training
|
| 105 |
+
- grouped cross-entropy objective
|
| 106 |
+
- selected seed: **41**
|
| 107 |
+
|
| 108 |
+
The selected head is the seed-41 epoch-4 checkpoint. Temperature remains at `1.0`; its maximum grouped-softmax output is reported as confidence, not as a universally calibrated probability.
|
| 109 |
+
|
| 110 |
+
## Evaluation
|
| 111 |
+
|
| 112 |
+
Synthetic held-out evaluation:
|
| 113 |
+
|
| 114 |
+
| Metric | Result |
|
| 115 |
+
|---|---:|
|
| 116 |
+
| Semantic Choice accuracy | **72.97%** |
|
| 117 |
+
| Stress Choice accuracy | **67.64%** |
|
| 118 |
+
| Counterfactual pair consistency | **67.12%** |
|
| 119 |
+
|
| 120 |
+
Performance measurements used an NVIDIA GH200, BF16 backbone inference, and the shared-prefix KV-cache serving path. For short and medium contexts of approximately 256–1,024 state tokens, total latency was approximately **76–85 ms** for **3–16 candidates** (measured range: 76.11–82.36 ms). Offline representation extraction reached **831.3 candidates/second** at candidate batch size 512 while caching 430,072 candidates. These local measurements are hardware- and workload-specific and are not a direct speed comparison with Jev or any hosted service.
|
| 121 |
+
|
| 122 |
+
## Limitations and intended use
|
| 123 |
+
|
| 124 |
+
> **ODM Mini v1 is a research/hackathon prototype and is not ready for unmonitored production agent control.**
|
| 125 |
+
|
| 126 |
+
In a real shadow-agent evaluation covering **75 multi-step trajectories and 243 decisions**, ODM Mini achieved:
|
| 127 |
+
|
| 128 |
+
- action accuracy: **27.98%**
|
| 129 |
+
- controller agreement: **26.34%**
|
| 130 |
+
|
| 131 |
+
The major known failure is **high-confidence premature completion on intermediate multi-step trajectories**. After partial progress, the model can over-index on successful receipts and choose `control.finish` before remaining steps have been completed. Training used synthetic, static decision snapshots, so the published metrics should not be assumed to transfer to arbitrary tools, domains, or agent loops.
|
| 132 |
+
|
| 133 |
+
Recommended uses are research, offline evaluation, single-step Choice experiments, and shadow-mode analysis with an independent controller. Do not use this checkpoint as the sole decision-maker for consequential actions or autonomous production control.
|
| 134 |
+
|
| 135 |
+
## Released files
|
| 136 |
+
|
| 137 |
+
- `model.safetensors` — ODM Mini DecisionHead tensors only
|
| 138 |
+
- `config.json` — architecture and backbone reference
|
| 139 |
+
- `odm_mini.py` — inference-only loader
|
| 140 |
+
- `README.md` — model card and working example
|
| 141 |
+
- `LICENSE` — Apache License 2.0
|
| 142 |
+
|
| 143 |
+
## License
|
| 144 |
+
|
| 145 |
+
ODM Mini-specific code and weights in this repository are released under Apache-2.0. The separately downloaded Qwen backbone is governed by its own repository terms.
|
config.json
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": ["ODMMiniModel"],
|
| 3 |
+
"model_type": "odm_mini",
|
| 4 |
+
"base_model": "Qwen/Qwen3-0.6B",
|
| 5 |
+
"hidden_size": 1024,
|
| 6 |
+
"head_inner_size": 256,
|
| 7 |
+
"pooling": "candidate_description_mean",
|
| 8 |
+
"temperature": 1.0,
|
| 9 |
+
"max_state_length": 4096,
|
| 10 |
+
"max_suffix_length": 256
|
| 11 |
+
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:52b9cdd647edef215d64cc156be98aef5bace6c4cce1f33f10cadfad08d59b16
|
| 3 |
+
size 1050940
|
odm_mini.py
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Inference-only loader for ODM Mini v1.
|
| 2 |
+
|
| 3 |
+
The released repository contains only the trained DecisionHead. The frozen
|
| 4 |
+
Qwen/Qwen3-0.6B backbone is downloaded separately by ``from_pretrained``.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import json
|
| 10 |
+
import time
|
| 11 |
+
from dataclasses import dataclass
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import Any, Mapping, Sequence
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
from huggingface_hub import hf_hub_download
|
| 17 |
+
from safetensors.torch import load_file
|
| 18 |
+
from torch import nn
|
| 19 |
+
from transformers import AutoModel, AutoTokenizer
|
| 20 |
+
from transformers.cache_utils import DynamicCache
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
DEFAULT_REPO_ID = "samatv256/mini-Jev"
|
| 24 |
+
DEFAULT_QUESTION = "What is the best next action for the agent?"
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def canonical_state(state: Any) -> str:
|
| 28 |
+
if isinstance(state, str):
|
| 29 |
+
return state.rstrip()
|
| 30 |
+
return json.dumps(state, sort_keys=True, ensure_ascii=False)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def format_state_prefix(state: Any) -> str:
|
| 34 |
+
return f"STATE:\n{canonical_state(state)}\n\n"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def format_candidate_suffix_prefix(question: str, candidate_id: str) -> str:
|
| 38 |
+
question = question.strip() if question and question.strip() else DEFAULT_QUESTION
|
| 39 |
+
return f"QUESTION:\n{question}\n\nCANDIDATE:\n{str(candidate_id).strip()}\n\nDESCRIPTION:\n"
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def mean_pool_description(
|
| 43 |
+
hidden_states: torch.Tensor, description_mask: torch.Tensor
|
| 44 |
+
) -> torch.Tensor:
|
| 45 |
+
mask = description_mask.to(
|
| 46 |
+
dtype=hidden_states.dtype, device=hidden_states.device
|
| 47 |
+
).unsqueeze(-1)
|
| 48 |
+
return (hidden_states * mask).sum(dim=1) / mask.sum(dim=1).clamp_min(1.0)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class DecisionHead(nn.Module):
|
| 52 |
+
"""Linear(1024, 256) -> GELU -> Linear(256, 1)."""
|
| 53 |
+
|
| 54 |
+
def __init__(self, hidden_size: int = 1024, inner_size: int = 256) -> None:
|
| 55 |
+
super().__init__()
|
| 56 |
+
self.net = nn.Sequential(
|
| 57 |
+
nn.Linear(hidden_size, inner_size),
|
| 58 |
+
nn.GELU(),
|
| 59 |
+
nn.Linear(inner_size, 1),
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
def forward(self, hidden: torch.Tensor) -> torch.Tensor:
|
| 63 |
+
return self.net(hidden.to(self.net[0].weight.dtype)).squeeze(-1)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@dataclass(frozen=True)
|
| 67 |
+
class DecisionCandidate:
|
| 68 |
+
id: str
|
| 69 |
+
description: str
|
| 70 |
+
|
| 71 |
+
def __post_init__(self) -> None:
|
| 72 |
+
if not self.id.strip():
|
| 73 |
+
raise ValueError("candidate id must not be empty")
|
| 74 |
+
if not self.description.strip():
|
| 75 |
+
raise ValueError("candidate description must not be empty")
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
CandidateLike = str | Mapping[str, Any] | DecisionCandidate
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def normalize_candidates(candidates: Sequence[CandidateLike]) -> list[DecisionCandidate]:
|
| 82 |
+
normalized: list[DecisionCandidate] = []
|
| 83 |
+
for item in candidates:
|
| 84 |
+
if isinstance(item, DecisionCandidate):
|
| 85 |
+
candidate = item
|
| 86 |
+
elif isinstance(item, Mapping):
|
| 87 |
+
candidate = DecisionCandidate(
|
| 88 |
+
id=str(item["id"]), description=str(item["description"])
|
| 89 |
+
)
|
| 90 |
+
elif isinstance(item, str):
|
| 91 |
+
candidate = DecisionCandidate(id=item, description=item)
|
| 92 |
+
else:
|
| 93 |
+
raise TypeError(f"unsupported candidate type: {type(item)!r}")
|
| 94 |
+
normalized.append(candidate)
|
| 95 |
+
if not normalized:
|
| 96 |
+
raise ValueError("candidates list must not be empty")
|
| 97 |
+
ids = [candidate.id for candidate in normalized]
|
| 98 |
+
if len(ids) != len(set(ids)):
|
| 99 |
+
raise ValueError("candidate ids must be unique within a decision")
|
| 100 |
+
return normalized
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@dataclass(frozen=True)
|
| 104 |
+
class ChoiceResponse:
|
| 105 |
+
selected: str
|
| 106 |
+
probabilities: dict[str, float]
|
| 107 |
+
confidence: float
|
| 108 |
+
decision_margin: float
|
| 109 |
+
latency_ms: float
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def _resolve_file(
|
| 113 |
+
model_id_or_path: str | Path,
|
| 114 |
+
filename: str,
|
| 115 |
+
*,
|
| 116 |
+
revision: str | None,
|
| 117 |
+
token: str | bool | None,
|
| 118 |
+
) -> Path:
|
| 119 |
+
local_path = Path(model_id_or_path)
|
| 120 |
+
if local_path.is_dir():
|
| 121 |
+
artifact = local_path / filename
|
| 122 |
+
if not artifact.is_file():
|
| 123 |
+
raise FileNotFoundError(f"missing release artifact: {artifact}")
|
| 124 |
+
return artifact
|
| 125 |
+
return Path(
|
| 126 |
+
hf_hub_download(
|
| 127 |
+
repo_id=str(model_id_or_path),
|
| 128 |
+
filename=filename,
|
| 129 |
+
revision=revision,
|
| 130 |
+
token=token,
|
| 131 |
+
)
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def replicate_cache(source_cache: DynamicCache, repeats: int) -> DynamicCache:
|
| 136 |
+
new_cache = DynamicCache()
|
| 137 |
+
for layer in source_cache.layers:
|
| 138 |
+
keys = layer.keys.clone() if repeats == 1 else layer.keys.repeat(repeats, 1, 1, 1)
|
| 139 |
+
values = (
|
| 140 |
+
layer.values.clone()
|
| 141 |
+
if repeats == 1
|
| 142 |
+
else layer.values.repeat(repeats, 1, 1, 1)
|
| 143 |
+
)
|
| 144 |
+
new_cache.update(keys, values, len(new_cache.layers))
|
| 145 |
+
return new_cache
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
class ODMMiniModel(nn.Module):
|
| 149 |
+
"""Frozen Qwen3-0.6B plus the trained ODM Mini DecisionHead."""
|
| 150 |
+
|
| 151 |
+
def __init__(
|
| 152 |
+
self,
|
| 153 |
+
backbone: nn.Module,
|
| 154 |
+
tokenizer: Any,
|
| 155 |
+
head: DecisionHead,
|
| 156 |
+
*,
|
| 157 |
+
hidden_size: int = 1024,
|
| 158 |
+
head_inner_size: int = 256,
|
| 159 |
+
max_state_length: int = 4096,
|
| 160 |
+
max_suffix_length: int = 256,
|
| 161 |
+
candidate_batch_size: int = 32,
|
| 162 |
+
temperature: float = 1.0,
|
| 163 |
+
) -> None:
|
| 164 |
+
super().__init__()
|
| 165 |
+
self.backbone = backbone
|
| 166 |
+
self.tokenizer = tokenizer
|
| 167 |
+
self.head = head
|
| 168 |
+
self.hidden_size = hidden_size
|
| 169 |
+
self.head_inner_size = head_inner_size
|
| 170 |
+
self.max_state_length = max_state_length
|
| 171 |
+
self.max_suffix_length = max_suffix_length
|
| 172 |
+
self.candidate_batch_size = candidate_batch_size
|
| 173 |
+
self.temperature = float(temperature)
|
| 174 |
+
self.escalation_threshold = 0.85
|
| 175 |
+
self.backbone.eval()
|
| 176 |
+
for parameter in self.backbone.parameters():
|
| 177 |
+
parameter.requires_grad = False
|
| 178 |
+
|
| 179 |
+
@classmethod
|
| 180 |
+
def from_pretrained(
|
| 181 |
+
cls,
|
| 182 |
+
model_id_or_path: str | Path = DEFAULT_REPO_ID,
|
| 183 |
+
*,
|
| 184 |
+
revision: str | None = None,
|
| 185 |
+
device: str | torch.device | None = None,
|
| 186 |
+
dtype: torch.dtype | None = None,
|
| 187 |
+
token: str | bool | None = None,
|
| 188 |
+
candidate_batch_size: int = 32,
|
| 189 |
+
) -> "ODMMiniModel":
|
| 190 |
+
device = device or ("cuda:0" if torch.cuda.is_available() else "cpu")
|
| 191 |
+
dtype = dtype or (torch.bfloat16 if torch.cuda.is_available() else torch.float32)
|
| 192 |
+
config_path = _resolve_file(
|
| 193 |
+
model_id_or_path, "config.json", revision=revision, token=token
|
| 194 |
+
)
|
| 195 |
+
weights_path = _resolve_file(
|
| 196 |
+
model_id_or_path, "model.safetensors", revision=revision, token=token
|
| 197 |
+
)
|
| 198 |
+
config = json.loads(config_path.read_text(encoding="utf-8"))
|
| 199 |
+
|
| 200 |
+
base_model = str(config["base_model"])
|
| 201 |
+
tokenizer = AutoTokenizer.from_pretrained(base_model)
|
| 202 |
+
backbone = AutoModel.from_pretrained(base_model, dtype=dtype)
|
| 203 |
+
backbone.to(device)
|
| 204 |
+
backbone.eval()
|
| 205 |
+
|
| 206 |
+
hidden_size = int(config["hidden_size"])
|
| 207 |
+
actual_hidden_size = int(getattr(backbone.config, "hidden_size", hidden_size))
|
| 208 |
+
if actual_hidden_size != hidden_size:
|
| 209 |
+
raise ValueError(
|
| 210 |
+
f"backbone hidden size {actual_hidden_size} does not match release config {hidden_size}"
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
head = DecisionHead(
|
| 214 |
+
hidden_size=hidden_size,
|
| 215 |
+
inner_size=int(config["head_inner_size"]),
|
| 216 |
+
)
|
| 217 |
+
head.load_state_dict(load_file(str(weights_path), device="cpu"), strict=True)
|
| 218 |
+
head.to(device=device, dtype=torch.float32)
|
| 219 |
+
head.eval()
|
| 220 |
+
|
| 221 |
+
return cls(
|
| 222 |
+
backbone=backbone,
|
| 223 |
+
tokenizer=tokenizer,
|
| 224 |
+
head=head,
|
| 225 |
+
hidden_size=hidden_size,
|
| 226 |
+
head_inner_size=int(config["head_inner_size"]),
|
| 227 |
+
max_state_length=int(config["max_state_length"]),
|
| 228 |
+
max_suffix_length=int(config["max_suffix_length"]),
|
| 229 |
+
candidate_batch_size=candidate_batch_size,
|
| 230 |
+
temperature=float(config["temperature"]),
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
@property
|
| 234 |
+
def device(self) -> torch.device:
|
| 235 |
+
return next(self.backbone.parameters()).device
|
| 236 |
+
|
| 237 |
+
@torch.inference_mode()
|
| 238 |
+
def encode_state(self, state: Any) -> tuple[DynamicCache, int]:
|
| 239 |
+
prefix_ids = self.tokenizer.encode(
|
| 240 |
+
format_state_prefix(state),
|
| 241 |
+
add_special_tokens=False,
|
| 242 |
+
truncation=True,
|
| 243 |
+
max_length=self.max_state_length,
|
| 244 |
+
)
|
| 245 |
+
if not prefix_ids:
|
| 246 |
+
prefix_ids = [self.tokenizer.pad_token_id or 0]
|
| 247 |
+
input_ids = torch.tensor([prefix_ids], dtype=torch.long, device=self.device)
|
| 248 |
+
output = self.backbone(input_ids=input_ids, use_cache=True)
|
| 249 |
+
return output.past_key_values, len(prefix_ids)
|
| 250 |
+
|
| 251 |
+
@torch.inference_mode()
|
| 252 |
+
def score_candidates_cached(
|
| 253 |
+
self,
|
| 254 |
+
past_key_values: DynamicCache,
|
| 255 |
+
prefix_length: int,
|
| 256 |
+
candidates: Sequence[DecisionCandidate],
|
| 257 |
+
question: str = DEFAULT_QUESTION,
|
| 258 |
+
candidate_batch_size: int | None = None,
|
| 259 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 260 |
+
batch_size_limit = candidate_batch_size or self.candidate_batch_size
|
| 261 |
+
all_representations: list[torch.Tensor] = []
|
| 262 |
+
|
| 263 |
+
for start in range(0, len(candidates), batch_size_limit):
|
| 264 |
+
batch = candidates[start : start + batch_size_limit]
|
| 265 |
+
suffixes: list[list[int]] = []
|
| 266 |
+
description_spans: list[tuple[int, int]] = []
|
| 267 |
+
for candidate in batch:
|
| 268 |
+
suffix_prefix = format_candidate_suffix_prefix(question, candidate.id)
|
| 269 |
+
prefix_ids = self.tokenizer.encode(
|
| 270 |
+
suffix_prefix,
|
| 271 |
+
add_special_tokens=False,
|
| 272 |
+
truncation=True,
|
| 273 |
+
max_length=self.max_suffix_length // 2,
|
| 274 |
+
)
|
| 275 |
+
description_ids = self.tokenizer.encode(
|
| 276 |
+
candidate.description.strip(),
|
| 277 |
+
add_special_tokens=False,
|
| 278 |
+
truncation=True,
|
| 279 |
+
max_length=max(1, self.max_suffix_length - len(prefix_ids)),
|
| 280 |
+
)
|
| 281 |
+
suffix = prefix_ids + description_ids
|
| 282 |
+
suffixes.append(suffix)
|
| 283 |
+
description_spans.append((len(prefix_ids), len(suffix)))
|
| 284 |
+
|
| 285 |
+
max_length = max(len(suffix) for suffix in suffixes)
|
| 286 |
+
pad_id = int(self.tokenizer.pad_token_id or 0)
|
| 287 |
+
input_ids = torch.full(
|
| 288 |
+
(len(batch), max_length), pad_id, dtype=torch.long, device=self.device
|
| 289 |
+
)
|
| 290 |
+
attention_mask = torch.ones(
|
| 291 |
+
(len(batch), prefix_length + max_length),
|
| 292 |
+
dtype=torch.long,
|
| 293 |
+
device=self.device,
|
| 294 |
+
)
|
| 295 |
+
for index, suffix in enumerate(suffixes):
|
| 296 |
+
input_ids[index, : len(suffix)] = torch.tensor(
|
| 297 |
+
suffix, dtype=torch.long, device=self.device
|
| 298 |
+
)
|
| 299 |
+
if len(suffix) < max_length:
|
| 300 |
+
attention_mask[index, prefix_length + len(suffix) :] = 0
|
| 301 |
+
|
| 302 |
+
output = self.backbone(
|
| 303 |
+
input_ids=input_ids,
|
| 304 |
+
attention_mask=attention_mask,
|
| 305 |
+
past_key_values=replicate_cache(past_key_values, len(batch)),
|
| 306 |
+
use_cache=False,
|
| 307 |
+
)
|
| 308 |
+
description_mask = torch.zeros(
|
| 309 |
+
(len(batch), max_length), dtype=torch.bool, device=self.device
|
| 310 |
+
)
|
| 311 |
+
for index, (description_start, description_end) in enumerate(description_spans):
|
| 312 |
+
description_mask[index, description_start:description_end] = True
|
| 313 |
+
all_representations.append(
|
| 314 |
+
mean_pool_description(output.last_hidden_state, description_mask)
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
representations = torch.cat(all_representations, dim=0)
|
| 318 |
+
return self.head(representations), representations
|
| 319 |
+
|
| 320 |
+
@torch.inference_mode()
|
| 321 |
+
def predict_choice(
|
| 322 |
+
self,
|
| 323 |
+
state: Any,
|
| 324 |
+
candidates: Sequence[CandidateLike],
|
| 325 |
+
question: str = DEFAULT_QUESTION,
|
| 326 |
+
temperature: float | None = None,
|
| 327 |
+
) -> ChoiceResponse:
|
| 328 |
+
started = time.perf_counter()
|
| 329 |
+
normalized = normalize_candidates(candidates)
|
| 330 |
+
cache, prefix_length = self.encode_state(state)
|
| 331 |
+
logits, _ = self.score_candidates_cached(
|
| 332 |
+
cache, prefix_length, normalized, question=question
|
| 333 |
+
)
|
| 334 |
+
float_logits = logits.float()
|
| 335 |
+
sorted_logits, _ = torch.sort(float_logits, descending=True)
|
| 336 |
+
margin = float(
|
| 337 |
+
(sorted_logits[0] - sorted_logits[1]).item()
|
| 338 |
+
if len(sorted_logits) > 1
|
| 339 |
+
else sorted_logits[0].item()
|
| 340 |
+
)
|
| 341 |
+
effective_temperature = self.temperature if temperature is None else float(temperature)
|
| 342 |
+
probabilities = torch.softmax(float_logits / max(effective_temperature, 1e-4), dim=-1)
|
| 343 |
+
selected_index = int(probabilities.argmax().item())
|
| 344 |
+
probability_map = {
|
| 345 |
+
candidate.id: float(probability.item())
|
| 346 |
+
for candidate, probability in zip(normalized, probabilities, strict=True)
|
| 347 |
+
}
|
| 348 |
+
return ChoiceResponse(
|
| 349 |
+
selected=normalized[selected_index].id,
|
| 350 |
+
probabilities=probability_map,
|
| 351 |
+
confidence=float(probabilities[selected_index].item()),
|
| 352 |
+
decision_margin=margin,
|
| 353 |
+
latency_ms=(time.perf_counter() - started) * 1000.0,
|
| 354 |
+
)
|