Add verified MagicEightBall portable model and animated card
Browse files- .gitattributes +2 -0
- LICENSE +226 -0
- NOTICE.txt +9 -0
- README.md +39 -0
- SHA256SUMS.txt +15 -0
- assets/workbench-motion.webp +3 -0
- assets/workbench.webp +3 -0
- blob_layout.py +84 -0
- compact_tokenizer.py +142 -0
- model.gguf +0 -0
- needle3-tokenizer.m8t.xz +3 -0
- policy.py +308 -0
- portable_runtime.py +111 -0
- radix.py +31 -0
- release.py +71 -0
- runtime.py +455 -0
- verification.json +34 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,5 @@ saved_model/**/* 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
|
|
|
|
|
|
|
|
|
| 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
|
| 36 |
+
assets/workbench-motion.webp filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
assets/workbench.webp filter=lfs diff=lfs merge=lfs -text
|
LICENSE
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 Chad St. Thomas
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
| 22 |
+
|
| 23 |
+
Needle 3 tokenizer
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
Apache License
|
| 27 |
+
Version 2.0, January 2004
|
| 28 |
+
http://www.apache.org/licenses/
|
| 29 |
+
|
| 30 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 31 |
+
|
| 32 |
+
1. Definitions.
|
| 33 |
+
|
| 34 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 35 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 36 |
+
|
| 37 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 38 |
+
the copyright owner that is granting the License.
|
| 39 |
+
|
| 40 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 41 |
+
other entities that control, are controlled by, or are under common
|
| 42 |
+
control with that entity. For the purposes of this definition,
|
| 43 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 44 |
+
direction or management of such entity, whether by contract or
|
| 45 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 46 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 47 |
+
|
| 48 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 49 |
+
exercising permissions granted by this License.
|
| 50 |
+
|
| 51 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 52 |
+
including but not limited to software source code, documentation
|
| 53 |
+
source, and configuration files.
|
| 54 |
+
|
| 55 |
+
"Object" form shall mean any form resulting from mechanical
|
| 56 |
+
transformation or translation of a Source form, including but
|
| 57 |
+
not limited to compiled object code, generated documentation,
|
| 58 |
+
and conversions to other media types.
|
| 59 |
+
|
| 60 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 61 |
+
Object form, made available under the License, as indicated by a
|
| 62 |
+
copyright notice that is included in or attached to the work
|
| 63 |
+
(an example is provided in the Appendix below).
|
| 64 |
+
|
| 65 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 66 |
+
form, that is based on (or derived from) the Work and for which the
|
| 67 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 68 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 69 |
+
of this License, Derivative Works shall not include works that remain
|
| 70 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 71 |
+
the Work and Derivative Works thereof.
|
| 72 |
+
|
| 73 |
+
"Contribution" shall mean any work of authorship, including
|
| 74 |
+
the original version of the Work and any modifications or additions
|
| 75 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 76 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 77 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 78 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 79 |
+
means any form of electronic, verbal, or written communication sent
|
| 80 |
+
to the Licensor or its representatives, including but not limited to
|
| 81 |
+
communication on electronic mailing lists, source code control systems,
|
| 82 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 83 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 84 |
+
excluding communication that is conspicuously marked or otherwise
|
| 85 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 86 |
+
|
| 87 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 88 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 89 |
+
subsequently incorporated within the Work.
|
| 90 |
+
|
| 91 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 92 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 93 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 94 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 95 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 96 |
+
Work and such Derivative Works in Source or Object form.
|
| 97 |
+
|
| 98 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 99 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 100 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 101 |
+
(except as stated in this section) patent license to make, have made,
|
| 102 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 103 |
+
where such license applies only to those patent claims licensable
|
| 104 |
+
by such Contributor that are necessarily infringed by their
|
| 105 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 106 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 107 |
+
institute patent litigation against any entity (including a
|
| 108 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 109 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 110 |
+
or contributory patent infringement, then any patent licenses
|
| 111 |
+
granted to You under this License for that Work shall terminate
|
| 112 |
+
as of the date such litigation is filed.
|
| 113 |
+
|
| 114 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 115 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 116 |
+
modifications, and in Source or Object form, provided that You
|
| 117 |
+
meet the following conditions:
|
| 118 |
+
|
| 119 |
+
(a) You must give any other recipients of the Work or
|
| 120 |
+
Derivative Works a copy of this License; and
|
| 121 |
+
|
| 122 |
+
(b) You must cause any modified files to carry prominent notices
|
| 123 |
+
stating that You changed the files; and
|
| 124 |
+
|
| 125 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 126 |
+
that You distribute, all copyright, patent, trademark, and
|
| 127 |
+
attribution notices from the Source form of the Work,
|
| 128 |
+
excluding those notices that do not pertain to any part of
|
| 129 |
+
the Derivative Works; and
|
| 130 |
+
|
| 131 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 132 |
+
distribution, then any Derivative Works that You distribute must
|
| 133 |
+
include a readable copy of the attribution notices contained
|
| 134 |
+
within such NOTICE file, excluding those notices that do not
|
| 135 |
+
pertain to any part of the Derivative Works, in at least one
|
| 136 |
+
of the following places: within a NOTICE text file distributed
|
| 137 |
+
as part of the Derivative Works; within the Source form or
|
| 138 |
+
documentation, if provided along with the Derivative Works; or,
|
| 139 |
+
within a display generated by the Derivative Works, if and
|
| 140 |
+
wherever such third-party notices normally appear. The contents
|
| 141 |
+
of the NOTICE file are for informational purposes only and
|
| 142 |
+
do not modify the License. You may add Your own attribution
|
| 143 |
+
notices within Derivative Works that You distribute, alongside
|
| 144 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 145 |
+
that such additional attribution notices cannot be construed
|
| 146 |
+
as modifying the License.
|
| 147 |
+
|
| 148 |
+
You may add Your own copyright statement to Your modifications and
|
| 149 |
+
may provide additional or different license terms and conditions
|
| 150 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 151 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 152 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 153 |
+
the conditions stated in this License.
|
| 154 |
+
|
| 155 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 156 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 157 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 158 |
+
this License, without any additional terms or conditions.
|
| 159 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 160 |
+
the terms of any separate license agreement you may have executed
|
| 161 |
+
with Licensor regarding such Contributions.
|
| 162 |
+
|
| 163 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 164 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 165 |
+
except as required for reasonable and customary use in describing the
|
| 166 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 167 |
+
|
| 168 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 169 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 170 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 171 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 172 |
+
implied, including, without limitation, any warranties or conditions
|
| 173 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 174 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 175 |
+
appropriateness of using or redistributing the Work and assume any
|
| 176 |
+
risks associated with Your exercise of permissions under this License.
|
| 177 |
+
|
| 178 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 179 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 180 |
+
unless required by applicable law (such as deliberate and grossly
|
| 181 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 182 |
+
liable to You for damages, including any direct, indirect, special,
|
| 183 |
+
incidental, or consequential damages of any character arising as a
|
| 184 |
+
result of this License or out of the use or inability to use the
|
| 185 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 186 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 187 |
+
other commercial damages or losses), even if such Contributor
|
| 188 |
+
has been advised of the possibility of such damages.
|
| 189 |
+
|
| 190 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 191 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 192 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 193 |
+
or other liability obligations and/or rights consistent with this
|
| 194 |
+
License. However, in accepting such obligations, You may act only
|
| 195 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 196 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 197 |
+
defend, and hold each Contributor harmless for any liability
|
| 198 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 199 |
+
of your accepting any such warranty or additional liability.
|
| 200 |
+
|
| 201 |
+
END OF TERMS AND CONDITIONS
|
| 202 |
+
|
| 203 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 204 |
+
|
| 205 |
+
To apply the Apache License to your work, attach the following
|
| 206 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 207 |
+
replaced with your own identifying information. (Don't include
|
| 208 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 209 |
+
comment syntax for the file format. We also recommend that a
|
| 210 |
+
file or class name and description of purpose be included on the
|
| 211 |
+
same "printed page" as the copyright notice for easier
|
| 212 |
+
identification within third-party archives.
|
| 213 |
+
|
| 214 |
+
Copyright [yyyy] [name of copyright owner]
|
| 215 |
+
|
| 216 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 217 |
+
you may not use this file except in compliance with the License.
|
| 218 |
+
You may obtain a copy of the License at
|
| 219 |
+
|
| 220 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 221 |
+
|
| 222 |
+
Unless required by applicable law or agreed to in writing, software
|
| 223 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 224 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 225 |
+
See the License for the specific language governing permissions and
|
| 226 |
+
limitations under the License.
|
NOTICE.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MagicEightBall
|
| 2 |
+
MyriadForge source and policy are distributed under the MIT License.
|
| 3 |
+
|
| 4 |
+
The Needle 3 tokenizer is distributed under the Apache License, Version 2.0.
|
| 5 |
+
Source: Cactus Compute, Cactus-Compute/needle3
|
| 6 |
+
Revision: d6c7d6a2e9655505e0f8e23339356dd1705900eb
|
| 7 |
+
URL: https://huggingface.co/Cactus-Compute/needle3/blob/d6c7d6a2e9655505e0f8e23339356dd1705900eb/tokenizer/tokenizer.model
|
| 8 |
+
Source SHA-256: 97dfd5666620b19875deba9e55953d312364e7763bd08bee428b94f1b9491b25
|
| 9 |
+
The tokenizer is repackaged losslessly. The loader restores and verifies the source bytes.
|
README.md
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
language:
|
| 3 |
+
- en
|
| 4 |
+
license: other
|
| 5 |
+
license_name: mit-and-apache-2.0
|
| 6 |
+
license_link: LICENSE
|
| 7 |
+
tags:
|
| 8 |
+
- magiceightball
|
| 9 |
+
- decision-model
|
| 10 |
+
- rule-engine
|
| 11 |
+
- gguf
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
# MagicEightBall GGUF
|
| 15 |
+
|
| 16 |
+

|
| 17 |
+
|
| 18 |
+
MagicEightBall evaluates a fixed support policy and returns a Boolean answer, a category, and a proposed action. This private CPU preview accepts up to **131,072 Needle 3 tokens** through its included runtime. The [GGUF model](./model.gguf) is **1,024 bytes**. The shared tokenizer, runner, and artwork have separate sizes.
|
| 19 |
+
|
| 20 |
+
GGUF container with a custom `magiceightball` architecture. Its I8 decision table stores one packed byte for each of the 128 fact assignments. The included CPU reader evaluates it. Use that reader for this architecture. It has no `llama.cpp` loader.
|
| 21 |
+
|
| 22 |
+
CPU verification passed all **128 fact assignments**, **128 short text fixtures**, two exact-limit documents, and rejection at 131,073 tokens. [Verification report](./verification.json)
|
| 23 |
+
|
| 24 |
+
## Try the policy
|
| 25 |
+
|
| 26 |
+
Download the files together and run the provided CLI from that directory.
|
| 27 |
+
|
| 28 |
+
```bash
|
| 29 |
+
python -m pip install numpy sentencepiece gguf
|
| 30 |
+
python portable_runtime.py model.gguf --text "Duplicate charge. Review authorized."
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
Expect `may_route=true`, `category=billing`, and `action=review_billing`. Try appending `Do not route.` to the same input. The answer becomes false and the action becomes empty. The category remains `billing`. An unrelated request has no category or action.
|
| 34 |
+
|
| 35 |
+
The model finds the policy's declared phrases. The caller receives the proposed action as data for review. For physical Intel NCS1 execution and industry starter packs, use the native model page. [Native NCS1 and industry packs](https://huggingface.co/chadstthomas/MagicEightBall) · [ONNX](https://huggingface.co/chadstthomas/MagicEightBall-ONNX) · [FP32 Base](https://huggingface.co/chadstthomas/MagicEightBall-FP32) · [Still banner](./assets/workbench.webp)
|
| 36 |
+
|
| 37 |
+
## License
|
| 38 |
+
|
| 39 |
+
The decision rules and runner are MIT-licensed. The losslessly repackaged Cactus Compute Needle 3 tokenizer is Apache-2.0. [License](./LICENSE) · [Tokenizer provenance](./NOTICE.txt) · [Checksums](./SHA256SUMS.txt)
|
SHA256SUMS.txt
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
ce832023f7b0fba6662a82388976c76e649015e00ccd6ba6323b1b888e8999d2 assets/workbench-motion.webp
|
| 2 |
+
e9775806f7bdc8b8d68c3dad5c83b289503110bed04a4596bf9662ee9ef801a1 assets/workbench.webp
|
| 3 |
+
9e1666a0c8ebf5478f3bfd720be24636b26110b73bcb653ab77f3f0675c4a984 blob_layout.py
|
| 4 |
+
81b1fa3936a84bf8736ad900d35754b5166a2fa129aac2c0b83818c3a0e4a5fe compact_tokenizer.py
|
| 5 |
+
203236fdd657233e98015692bec78bc49452896f268b22c75b5d9ccb12e59100 LICENSE
|
| 6 |
+
04d3b8df61cca763eee906f1c6bd116b69e59eaae56e90e1179193d19f108117 model.gguf
|
| 7 |
+
97405c9a70aca43a4a3a2604203ff4b4a749eceef69493792f2d81c25abc7fd9 needle3-tokenizer.m8t.xz
|
| 8 |
+
ece5848c64d031c0e17952cda3232d805cb5841f3a8c06ac009f399b57b266d1 NOTICE.txt
|
| 9 |
+
52ef0bb07e52712d16073c73030790e5d6a746c0291492e03917e13749dccdc2 policy.py
|
| 10 |
+
b58a2a75c2da4d71685f168a527f98b25f8e4b682dd65b88c316c1d8ac0be179 portable_runtime.py
|
| 11 |
+
1f530b66213e4c46939580856dcb4ccf57516b7f55202516bb7128ea4414110a radix.py
|
| 12 |
+
ccc633d65b6c7c66733f496fa96c9553f0e166bea45c818f0bbf80abf8fa34b9 README.md
|
| 13 |
+
9f435e1a91da46d3b294048da148f1e7a2820923d3896ed3d7fe9549d0c45eea release.py
|
| 14 |
+
ee797b0ff94fbf99117cf0c580f118f447f0dd0100d1a19f64c6e7e4ffdfef8f runtime.py
|
| 15 |
+
502adf6f9a3231423ceb7f41d2a8e24bf427ab85fdc793ffa504eb4ed484c7b5 verification.json
|
assets/workbench-motion.webp
ADDED
|
Git LFS Details
|
assets/workbench.webp
ADDED
|
Git LFS Details
|
blob_layout.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Read the documented section layout of an OpenVINO 2020.3 MYRIAD blob."""
|
| 2 |
+
import argparse
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import struct
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
# OpenVINO 2020.3.2 blob_format.hpp and backend/serialize.cpp.
|
| 10 |
+
ELF_HEADER_SIZE = 52
|
| 11 |
+
HEADER = struct.Struct("<20I")
|
| 12 |
+
SECTION_NAMES = ("headers", "input_descriptor", "output_descriptor", "stages", "constants")
|
| 13 |
+
GATHER_WORDS = struct.Struct("<32I")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _gather_coefficient_bytes(data, fields):
|
| 17 |
+
"""Verify the stock rank-one Gather stage before trusting its table extent."""
|
| 18 |
+
if fields[2:7] != (5, 0, 1, 1, 1) or fields[16:] != (192, 256, 320, 448):
|
| 19 |
+
raise ValueError("Compact terminal storage requires a canonical rank-one Gather")
|
| 20 |
+
words = GATHER_WORDS.unpack_from(data, fields[18])
|
| 21 |
+
slots, remainder = divmod(fields[7], 4)
|
| 22 |
+
# The three descriptors are FP16 table, FP16 output and signed I32 index.
|
| 23 |
+
# Their rank, element stride, location, port and offset come from data.cpp.
|
| 24 |
+
table = (0, 3, 1, words[8], 2, 3, 0)
|
| 25 |
+
output = (0, 3, 1, slots, 2, 2, 0, slots * 2, 0)
|
| 26 |
+
indices = (2, 3, 1, slots, 4, 1, 0, slots * 4, 0)
|
| 27 |
+
if (not slots or remainder or fields[8] != slots * 2 or not words[8]
|
| 28 |
+
or words[:2] != (128, 100) or words[3:5] != (8, 0)
|
| 29 |
+
or words[5:12] != table or words[12:21] != output or words[21:30] != indices
|
| 30 |
+
or words[30:] != (100, 2139356953)):
|
| 31 |
+
raise ValueError("Unexpected rank-one Gather descriptors")
|
| 32 |
+
return words[8] * 2
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def inspect_blob(data, compact_coefficients=None):
|
| 36 |
+
if not data.startswith(b"\x7felf") or len(data) < ELF_HEADER_SIZE + HEADER.size:
|
| 37 |
+
raise ValueError("Expected an OpenVINO 2020.3 MYRIAD blob")
|
| 38 |
+
fields = HEADER.unpack_from(data, ELF_HEADER_SIZE)
|
| 39 |
+
magic, size, major, minor = fields[:4]
|
| 40 |
+
boundaries = (0, *fields[16:], size)
|
| 41 |
+
if (magic != 9709 or major != 5 or size != len(data)
|
| 42 |
+
or list(boundaries) != sorted(boundaries) or any(n % 64 for n in boundaries[:-1])):
|
| 43 |
+
raise ValueError("Invalid legacy MYRIAD header or section layout")
|
| 44 |
+
layout = {name: end - start for name, start, end in zip(SECTION_NAMES, boundaries, boundaries[1:])}
|
| 45 |
+
if size % 64:
|
| 46 |
+
if type(compact_coefficients) is not int or compact_coefficients != layout["constants"]:
|
| 47 |
+
raise ValueError("Invalid compact Gather constant extent")
|
| 48 |
+
if _gather_coefficient_bytes(data, fields) != compact_coefficients:
|
| 49 |
+
raise ValueError("Compact Gather stage and manifest disagree on the constant extent")
|
| 50 |
+
stage_count = fields[6]
|
| 51 |
+
stage = None
|
| 52 |
+
if stage_count == 1:
|
| 53 |
+
if layout["stages"] < 12:
|
| 54 |
+
raise ValueError("Invalid MYRIAD stage")
|
| 55 |
+
length, operation, shaves = struct.unpack_from("<3I", data, fields[18])
|
| 56 |
+
if not 12 <= length <= layout["stages"]:
|
| 57 |
+
raise ValueError("Invalid legacy MYRIAD stage length")
|
| 58 |
+
stage = {"length": length, "type": operation, "shaves_field": shaves}
|
| 59 |
+
return dict(bytes=size, sha256=hashlib.sha256(data).hexdigest(), version=[major, minor],
|
| 60 |
+
inputs=fields[4], outputs=fields[5], stage_count=stage_count,
|
| 61 |
+
input_bytes=fields[7], output_bytes=fields[8], sections=layout, sole_stage=stage)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def compact_gather_blob(data, coefficient_bytes):
|
| 65 |
+
"""Drop only the terminal zero padding after a stock Gather's FP16 table."""
|
| 66 |
+
inspect_blob(data)
|
| 67 |
+
fields = HEADER.unpack_from(data, ELF_HEADER_SIZE)
|
| 68 |
+
if type(coefficient_bytes) is not int or _gather_coefficient_bytes(data, fields) != coefficient_bytes:
|
| 69 |
+
raise ValueError("Gather stage and manifest disagree on the constant extent")
|
| 70 |
+
end = fields[19] + coefficient_bytes
|
| 71 |
+
if not 0 <= len(data) - end < 64 or any(data[end:]):
|
| 72 |
+
raise ValueError("Expected zero padding in the final Gather section")
|
| 73 |
+
compact = bytearray(data[:end])
|
| 74 |
+
struct.pack_into("<I", compact, ELF_HEADER_SIZE + 4, end)
|
| 75 |
+
return bytes(compact)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
if __name__ == "__main__":
|
| 79 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 80 |
+
parser.add_argument("blobs", nargs="+", type=Path)
|
| 81 |
+
parser.add_argument("--compact-coefficients", type=int)
|
| 82 |
+
args = parser.parse_args()
|
| 83 |
+
print(json.dumps({str(path): inspect_blob(path.read_bytes(), args.compact_coefficients)
|
| 84 |
+
for path in args.blobs}, indent=2))
|
compact_tokenizer.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Lossless storage for the pinned Needle 3 SentencePiece model."""
|
| 2 |
+
import argparse
|
| 3 |
+
from collections import Counter
|
| 4 |
+
import hashlib
|
| 5 |
+
import lzma
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import struct
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
TOKENIZER_HASH = "97dfd5666620b19875deba9e55953d312364e7763bd08bee428b94f1b9491b25"
|
| 11 |
+
LEGACY_MAGIC = b"M8T1"
|
| 12 |
+
MAGIC = b"M8T2"
|
| 13 |
+
HEADER = struct.Struct("<4s3H")
|
| 14 |
+
SPECIAL_PIECES = 284
|
| 15 |
+
MAX_SHORT_PIECE = 120
|
| 16 |
+
METASPACE = "\u2581".encode("utf8")
|
| 17 |
+
HAS_METASPACE = 128
|
| 18 |
+
LENGTH_TABLE = bytes(range(HAS_METASPACE)) * 2
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _varint(number):
|
| 22 |
+
encoded = bytearray()
|
| 23 |
+
while number >= 128:
|
| 24 |
+
encoded.append((number & 127) | 128)
|
| 25 |
+
number >>= 7
|
| 26 |
+
encoded.append(number)
|
| 27 |
+
return bytes(encoded)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _field(tag, contents):
|
| 31 |
+
return bytes([tag]) + _varint(len(contents)) + contents
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _byte_fallback():
|
| 35 |
+
# SentencePiece BYTE messages are the same except for the hex spelling.
|
| 36 |
+
return b"".join(b"\x0a\x0f\x0a\x06<0x%02X>\x15\0\0\0\0\x18\x06" % value
|
| 37 |
+
for value in range(256))
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _restore(data):
|
| 41 |
+
if len(data) < HEADER.size:
|
| 42 |
+
raise ValueError("Missing compact tokenizer header")
|
| 43 |
+
magic, prefix_size, suffix_size, count = HEADER.unpack_from(data)
|
| 44 |
+
prefix_end = HEADER.size + prefix_size
|
| 45 |
+
suffix_end = prefix_end + suffix_size
|
| 46 |
+
lengths_end = suffix_end + count
|
| 47 |
+
descriptors = data[suffix_end:lengths_end]
|
| 48 |
+
if magic not in (MAGIC, LEGACY_MAGIC) or count == 0 or len(descriptors) != count:
|
| 49 |
+
raise ValueError("Invalid compact tokenizer layout")
|
| 50 |
+
bucketed = magic == MAGIC
|
| 51 |
+
lengths = descriptors.translate(LENGTH_TABLE) if bucketed else descriptors
|
| 52 |
+
if sum(lengths) != len(data) - lengths_end:
|
| 53 |
+
raise ValueError("Invalid compact tokenizer layout")
|
| 54 |
+
original = bytearray(data[HEADER.size:prefix_end])
|
| 55 |
+
# The outer length is piece length plus the two string bytes and five score bytes.
|
| 56 |
+
prefixes = [None] * 256
|
| 57 |
+
for desc in set(descriptors):
|
| 58 |
+
marker = METASPACE if bucketed and desc & HAS_METASPACE else b""
|
| 59 |
+
length = (LENGTH_TABLE[desc] if bucketed else desc) + len(marker)
|
| 60 |
+
if not 1 <= length <= MAX_SHORT_PIECE:
|
| 61 |
+
raise ValueError("Invalid compact tokenizer piece length")
|
| 62 |
+
prefixes[desc] = bytes([10, length + 7, 10, length]) + marker
|
| 63 |
+
scores = struct.pack("<%df" % count, *(-float(rank) for rank in range(count)))
|
| 64 |
+
offset = lengths_end
|
| 65 |
+
score_offset = 0
|
| 66 |
+
# NORMAL is the protobuf default. Rank zero has the original -0.0 bit pattern.
|
| 67 |
+
if bucketed:
|
| 68 |
+
original.extend(_byte_fallback())
|
| 69 |
+
positions = [0] * HAS_METASPACE
|
| 70 |
+
for length, amount in sorted(Counter(lengths).items()):
|
| 71 |
+
positions[length] = offset
|
| 72 |
+
offset += length * amount
|
| 73 |
+
for desc in descriptors:
|
| 74 |
+
length = desc & (HAS_METASPACE - 1)
|
| 75 |
+
start = positions[length]
|
| 76 |
+
end = start + length
|
| 77 |
+
positions[length] = end
|
| 78 |
+
original.extend(prefixes[desc] + data[start:end] + b"\x15" + scores[score_offset:score_offset + 4])
|
| 79 |
+
score_offset += 4
|
| 80 |
+
else:
|
| 81 |
+
for length in lengths:
|
| 82 |
+
end = offset + length
|
| 83 |
+
original.extend(prefixes[length] + data[offset:end] + b"\x15" + scores[score_offset:score_offset + 4])
|
| 84 |
+
offset = end
|
| 85 |
+
score_offset += 4
|
| 86 |
+
original.extend(data[prefix_end:suffix_end])
|
| 87 |
+
return bytes(original)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def read_tokenizer(path):
|
| 91 |
+
data = path.read_bytes()
|
| 92 |
+
if path.suffix == ".xz":
|
| 93 |
+
data = lzma.decompress(data)
|
| 94 |
+
if data.startswith((MAGIC, LEGACY_MAGIC)):
|
| 95 |
+
data = _restore(data)
|
| 96 |
+
if hashlib.sha256(data).hexdigest() != TOKENIZER_HASH:
|
| 97 |
+
raise ValueError("Unexpected Needle 3 tokenizer hash")
|
| 98 |
+
return data
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def pack_tokenizer(original):
|
| 102 |
+
# Only the build tool uses protobuf. Runtime reconstruction is stdlib-only.
|
| 103 |
+
from sentencepiece import sentencepiece_model_pb2
|
| 104 |
+
|
| 105 |
+
if hashlib.sha256(original).hexdigest() != TOKENIZER_HASH:
|
| 106 |
+
raise ValueError("Expected the pinned Needle 3 tokenizer")
|
| 107 |
+
model = sentencepiece_model_pb2.ModelProto.FromString(original)
|
| 108 |
+
prefix = b"".join(_field(10, piece.SerializeToString(deterministic=True))
|
| 109 |
+
for piece in model.pieces[:SPECIAL_PIECES])
|
| 110 |
+
fallback = _byte_fallback()
|
| 111 |
+
if not prefix.endswith(fallback):
|
| 112 |
+
raise ValueError("Unexpected Needle 3 byte fallback ordering")
|
| 113 |
+
prefix = prefix[:-len(fallback)]
|
| 114 |
+
words = []
|
| 115 |
+
descriptors = bytearray()
|
| 116 |
+
for piece in model.pieces[SPECIAL_PIECES:]:
|
| 117 |
+
word = piece.piece.encode("utf8")
|
| 118 |
+
has_metaspace = word.startswith(METASPACE)
|
| 119 |
+
if has_metaspace:
|
| 120 |
+
word = word[len(METASPACE):]
|
| 121 |
+
words.append(word)
|
| 122 |
+
descriptors.append(len(word) | (HAS_METASPACE if has_metaspace else 0))
|
| 123 |
+
del model.pieces[:]
|
| 124 |
+
suffix = model.SerializeToString(deterministic=True)
|
| 125 |
+
header = HEADER.pack(MAGIC, len(prefix), len(suffix), len(words))
|
| 126 |
+
# Stable grouping by length keeps each bucket in vocabulary rank order.
|
| 127 |
+
packed = header + prefix + suffix + descriptors + b"".join(sorted(words, key=len))
|
| 128 |
+
if _restore(packed) != original:
|
| 129 |
+
raise ValueError("Compact format failed to reproduce the exact SentencePiece bytes")
|
| 130 |
+
filters = [{"id": lzma.FILTER_LZMA2, "preset": 9, "dict_size": 65536, "pb": 0}]
|
| 131 |
+
return lzma.compress(packed, filters=filters)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
if __name__ == "__main__":
|
| 135 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 136 |
+
parser.add_argument("source", type=Path)
|
| 137 |
+
parser.add_argument("output", type=Path)
|
| 138 |
+
args = parser.parse_args()
|
| 139 |
+
original = read_tokenizer(args.source)
|
| 140 |
+
compressed = pack_tokenizer(original)
|
| 141 |
+
args.output.write_bytes(compressed)
|
| 142 |
+
print("%d original bytes, %d compact bytes" % (len(original), len(compressed)))
|
model.gguf
ADDED
|
Binary file (1.02 kB). View file
|
|
|
needle3-tokenizer.m8t.xz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:97405c9a70aca43a4a3a2604203ff4b4a749eceef69493792f2d81c25abc7fd9
|
| 3 |
+
size 23412
|
policy.py
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Boolean expressions, evidence extraction and a reference independent of OpenVINO."""
|
| 2 |
+
import json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import re
|
| 5 |
+
from collections import Counter, OrderedDict
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
from compact_tokenizer import read_tokenizer
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
LIMIT = 131072
|
| 13 |
+
PARTS = re.compile(r'"(?:[^"\\]|\\.)*"|@[a-zA-Z_][a-zA-Z_0-9]*|AND\b|OR\b|NOT\b|[()]')
|
| 14 |
+
LEXEME = re.compile(r"\w+|[^\w\s]", re.UNICODE)
|
| 15 |
+
GROUPS = ("answers", "categories", "actions")
|
| 16 |
+
RULE_NAME = re.compile(r"[a-zA-Z_][a-zA-Z_0-9]*")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class Expression:
|
| 20 |
+
def __init__(self, text, named):
|
| 21 |
+
self.tokens = []
|
| 22 |
+
self.named = named
|
| 23 |
+
pos = 0
|
| 24 |
+
while pos < len(text):
|
| 25 |
+
if text[pos].isspace():
|
| 26 |
+
pos += 1
|
| 27 |
+
continue
|
| 28 |
+
match = PARTS.match(text, pos)
|
| 29 |
+
if not match:
|
| 30 |
+
raise ValueError("Unrecognized expression near %r" % text[pos:pos+20])
|
| 31 |
+
self.tokens.append(match.group())
|
| 32 |
+
pos = match.end()
|
| 33 |
+
self.i = 0
|
| 34 |
+
|
| 35 |
+
def take(self, token):
|
| 36 |
+
if self.i < len(self.tokens) and self.tokens[self.i] == token:
|
| 37 |
+
self.i += 1
|
| 38 |
+
return True
|
| 39 |
+
return False
|
| 40 |
+
|
| 41 |
+
def parse(self):
|
| 42 |
+
expr = self.either()
|
| 43 |
+
if self.i != len(self.tokens):
|
| 44 |
+
raise ValueError("Unexpected trailing expression")
|
| 45 |
+
return expr
|
| 46 |
+
|
| 47 |
+
def either(self):
|
| 48 |
+
expr = self.both()
|
| 49 |
+
while self.take("OR"):
|
| 50 |
+
expr = ("or", expr, self.both())
|
| 51 |
+
return expr
|
| 52 |
+
|
| 53 |
+
def both(self):
|
| 54 |
+
expr = self.term()
|
| 55 |
+
while self.take("AND"):
|
| 56 |
+
expr = ("and", expr, self.term())
|
| 57 |
+
return expr
|
| 58 |
+
|
| 59 |
+
def term(self):
|
| 60 |
+
if self.take("NOT"):
|
| 61 |
+
return ("not", self.term())
|
| 62 |
+
if self.take("("):
|
| 63 |
+
expr = self.either()
|
| 64 |
+
if not self.take(")"):
|
| 65 |
+
raise ValueError("Missing closing parenthesis")
|
| 66 |
+
return expr
|
| 67 |
+
if self.i >= len(self.tokens):
|
| 68 |
+
raise ValueError("Missing expression")
|
| 69 |
+
token = self.tokens[self.i]
|
| 70 |
+
self.i += 1
|
| 71 |
+
if token.startswith("@") and token[1:] in self.named:
|
| 72 |
+
return self.named[token[1:]]
|
| 73 |
+
if token.startswith('"'):
|
| 74 |
+
words = tuple(LEXEME.findall(json.loads(token).casefold()))
|
| 75 |
+
if words:
|
| 76 |
+
return ("literal", words)
|
| 77 |
+
raise ValueError("Expected a nonempty literal or earlier rule: " + token)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def value(node, facts):
|
| 81 |
+
op = node[0]
|
| 82 |
+
if op == "literal":
|
| 83 |
+
return facts[node[1]]
|
| 84 |
+
if op == "not":
|
| 85 |
+
return not value(node[1], facts)
|
| 86 |
+
if op == "and":
|
| 87 |
+
return value(node[1], facts) and value(node[2], facts)
|
| 88 |
+
return value(node[1], facts) or value(node[2], facts)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def word_character(character):
|
| 92 |
+
return character == "_" or character.isalnum()
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def token_at(text, token, start):
|
| 96 |
+
if start < 0 or not text.startswith(token, start):
|
| 97 |
+
return False
|
| 98 |
+
if not word_character(token[0]):
|
| 99 |
+
return True
|
| 100 |
+
end = start + len(token)
|
| 101 |
+
return ((start == 0 or not word_character(text[start - 1]))
|
| 102 |
+
and (end == len(text) or not word_character(text[end])))
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def anchored_match(text, phrase, anchor):
|
| 106 |
+
offset = 0
|
| 107 |
+
word = phrase[anchor]
|
| 108 |
+
# A dense adversarial anchor is cheaper to check with the full projection.
|
| 109 |
+
for _ in range(64):
|
| 110 |
+
match = text.find(word, offset)
|
| 111 |
+
if match < 0:
|
| 112 |
+
return False
|
| 113 |
+
offset = match + 1
|
| 114 |
+
if not token_at(text, word, match):
|
| 115 |
+
continue
|
| 116 |
+
left = match
|
| 117 |
+
for token in reversed(phrase[:anchor]):
|
| 118 |
+
while left and text[left - 1].isspace():
|
| 119 |
+
left -= 1
|
| 120 |
+
left -= len(token)
|
| 121 |
+
if not token_at(text, token, left):
|
| 122 |
+
break
|
| 123 |
+
else:
|
| 124 |
+
right = match + len(word)
|
| 125 |
+
for token in phrase[anchor + 1:]:
|
| 126 |
+
while right < len(text) and text[right].isspace():
|
| 127 |
+
right += 1
|
| 128 |
+
if not token_at(text, token, right):
|
| 129 |
+
break
|
| 130 |
+
right += len(token)
|
| 131 |
+
else:
|
| 132 |
+
return True
|
| 133 |
+
return None
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class Policy:
|
| 137 |
+
def __init__(self, spec):
|
| 138 |
+
if not isinstance(spec, dict):
|
| 139 |
+
raise ValueError("Expected a JSON policy object")
|
| 140 |
+
for group in ("rules",) + GROUPS:
|
| 141 |
+
items = spec.get(group, {})
|
| 142 |
+
if not isinstance(items, dict) or any(not isinstance(expr, str) for expr in items.values()):
|
| 143 |
+
raise ValueError("Expected an object of Boolean strings for " + group)
|
| 144 |
+
rules = {}
|
| 145 |
+
for name, expression in spec.get("rules", {}).items():
|
| 146 |
+
if not RULE_NAME.fullmatch(name):
|
| 147 |
+
raise ValueError("Invalid rule name: " + name)
|
| 148 |
+
rules[name] = Expression(expression, rules).parse()
|
| 149 |
+
self.rules = rules
|
| 150 |
+
self.names, self.outputs = [], []
|
| 151 |
+
self.literals = []
|
| 152 |
+
def visit(node, found):
|
| 153 |
+
if node[0] == "literal":
|
| 154 |
+
if node[1] not in found:
|
| 155 |
+
found.append(node[1])
|
| 156 |
+
else:
|
| 157 |
+
for child in node[1:]:
|
| 158 |
+
visit(child, found)
|
| 159 |
+
for group in GROUPS:
|
| 160 |
+
for name, expression in spec.get(group, {}).items():
|
| 161 |
+
node = Expression(expression, rules).parse()
|
| 162 |
+
self.names.append((group, name))
|
| 163 |
+
self.outputs.append(node)
|
| 164 |
+
visit(node, self.literals)
|
| 165 |
+
if not self.literals:
|
| 166 |
+
raise ValueError("At least one evidence literal is required")
|
| 167 |
+
words = sorted({w for phrase in self.literals for w in phrase})
|
| 168 |
+
if len(words) > 255:
|
| 169 |
+
raise ValueError("The byte projection supports up to 255 different literal lexemes")
|
| 170 |
+
self.word_ids = {w: i+1 for i, w in enumerate(words)}
|
| 171 |
+
self.patterns = [bytes(self.word_ids[w] for w in p) for p in self.literals]
|
| 172 |
+
self.text_patterns = [self.literal_regex(words) for words in self.literals]
|
| 173 |
+
self.anchors = [max(range(len(words)), key=lambda i: len(words[i])) for words in self.literals]
|
| 174 |
+
explained = list(self.literals)
|
| 175 |
+
for node in self.rules.values():
|
| 176 |
+
visit(node, explained)
|
| 177 |
+
self.explanation_patterns = {words: self.literal_regex(words)
|
| 178 |
+
for words in explained[len(self.literals):]}
|
| 179 |
+
|
| 180 |
+
@staticmethod
|
| 181 |
+
def literal_regex(words):
|
| 182 |
+
# Place the left boundary check after the fixed prefix so the regex
|
| 183 |
+
# engine can use its native substring search on long documents.
|
| 184 |
+
first = re.escape(words[0])
|
| 185 |
+
def is_word(w):
|
| 186 |
+
return bool(re.fullmatch(r"\w+", w))
|
| 187 |
+
expr = first + (r"(?<!\w" + first + ")" if is_word(words[0]) else "")
|
| 188 |
+
for left, right in zip(words, words[1:]):
|
| 189 |
+
expr += (r"\s+" if is_word(left) and is_word(right) else r"\s*") + re.escape(right)
|
| 190 |
+
if is_word(words[-1]):
|
| 191 |
+
expr += r"(?!\w)"
|
| 192 |
+
return re.compile(expr)
|
| 193 |
+
|
| 194 |
+
def text_atoms(self, text):
|
| 195 |
+
folded = text.casefold()
|
| 196 |
+
return np.array([pattern.search(folded) is not None for pattern in self.text_patterns],
|
| 197 |
+
dtype=np.float32)
|
| 198 |
+
|
| 199 |
+
def anchored_atoms(self, text):
|
| 200 |
+
"""Independently verify literal evidence, with a bounded projection fallback."""
|
| 201 |
+
folded = text.casefold()
|
| 202 |
+
flags = []
|
| 203 |
+
for phrase, anchor in zip(self.literals, self.anchors):
|
| 204 |
+
matched = anchored_match(folded, phrase, anchor)
|
| 205 |
+
if matched is None:
|
| 206 |
+
return self.atoms(self.project(text))
|
| 207 |
+
flags.append(matched)
|
| 208 |
+
return np.asarray(flags, dtype=np.float32)
|
| 209 |
+
|
| 210 |
+
def project(self, text):
|
| 211 |
+
# 0 represents every lexeme unused by this policy. Preserve occurrences
|
| 212 |
+
# and their order, including punctuation between adjacent phrase words.
|
| 213 |
+
return bytes(self.word_ids.get(w, 0) for w in LEXEME.findall(text.casefold()))
|
| 214 |
+
|
| 215 |
+
def atoms(self, encoded):
|
| 216 |
+
return np.array([p in encoded for p in self.patterns], dtype=np.float32)
|
| 217 |
+
|
| 218 |
+
def reference(self, atoms):
|
| 219 |
+
facts = dict(zip(self.literals, map(bool, atoms)))
|
| 220 |
+
return np.array([value(node, facts) for node in self.outputs], dtype=np.float32)
|
| 221 |
+
|
| 222 |
+
def result(self, bits):
|
| 223 |
+
out = {"answers": {}, "category": None, "action": None}
|
| 224 |
+
singular = {"categories": "category", "actions": "action"}
|
| 225 |
+
for (group, name), bit in zip(self.names, bits):
|
| 226 |
+
if group == "answers":
|
| 227 |
+
out[group][name] = bool(bit)
|
| 228 |
+
elif bit and out[singular[group]] is None:
|
| 229 |
+
out[singular[group]] = name
|
| 230 |
+
return out
|
| 231 |
+
|
| 232 |
+
def explain(self, text, atoms):
|
| 233 |
+
facts = dict(zip(self.literals, map(bool, atoms)))
|
| 234 |
+
if self.explanation_patterns:
|
| 235 |
+
folded = text.casefold()
|
| 236 |
+
facts.update({words: pattern.search(folded) is not None
|
| 237 |
+
for words, pattern in self.explanation_patterns.items()})
|
| 238 |
+
return {"matched": [" ".join(p) for p, present in facts.items() if present],
|
| 239 |
+
"named_rules": {key: bool(value(node, facts)) for key,node in self.rules.items()}}
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def load_tokenizer(path=None):
|
| 243 |
+
import sentencepiece as spm
|
| 244 |
+
path = Path(path) if path else Path(__file__).with_name("needle3-tokenizer.m8t.xz")
|
| 245 |
+
return spm.SentencePieceProcessor(model_proto=read_tokenizer(path))
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def needle_count(tokenizer, text, fast=True, memo=None):
|
| 249 |
+
if not fast or len(text) < 4096 or " " not in text:
|
| 250 |
+
return len(tokenizer.encode(text, out_type=int))
|
| 251 |
+
# The SHA-pinned BPE has identity normalization, no added leading space,
|
| 252 |
+
# byte fallback, and no regular piece with a non-initial metaspace. No
|
| 253 |
+
# user-defined symbol spans ASCII space. Thus merges cannot span these
|
| 254 |
+
# boundaries. Count each distinct space-prefixed segment once per request.
|
| 255 |
+
first, _, rest = text.partition(" ")
|
| 256 |
+
frequency = Counter(rest.split(" "))
|
| 257 |
+
total = len(tokenizer.encode(first, out_type=int))
|
| 258 |
+
if memo is not None:
|
| 259 |
+
missing = {}
|
| 260 |
+
for segment, repetitions in frequency.items():
|
| 261 |
+
count = memo.prior.get(segment)
|
| 262 |
+
if count is None:
|
| 263 |
+
count = memo.counts.get(segment)
|
| 264 |
+
if count is None:
|
| 265 |
+
missing[segment] = repetitions
|
| 266 |
+
else:
|
| 267 |
+
total += repetitions * count
|
| 268 |
+
frequency = missing
|
| 269 |
+
if not frequency:
|
| 270 |
+
return total
|
| 271 |
+
segments = list(frequency)
|
| 272 |
+
encodings = tokenizer.encode([" " + s for s in segments], out_type=int, num_threads=4)
|
| 273 |
+
for segment, ids in zip(segments, encodings):
|
| 274 |
+
count = len(ids)
|
| 275 |
+
total += frequency[segment] * count
|
| 276 |
+
if memo is not None and len(segment) <= 96:
|
| 277 |
+
memo.counts[segment] = count
|
| 278 |
+
if len(memo.counts) > memo.capacity:
|
| 279 |
+
memo.counts.popitem(last=False)
|
| 280 |
+
return total
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
class SegmentMemo:
|
| 284 |
+
"""Bounded, process-local counts of exact space-prefixed segments."""
|
| 285 |
+
|
| 286 |
+
def __init__(self, capacity=8192, prior=None):
|
| 287 |
+
self.counts = OrderedDict()
|
| 288 |
+
self.capacity = capacity
|
| 289 |
+
self.prior = prior if prior is not None else {}
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def tokenizer_prior(tokenizer):
|
| 293 |
+
"""Seed reusable counts from the pinned vocabulary itself."""
|
| 294 |
+
metaspace = "\u2581"
|
| 295 |
+
words = (tokenizer.id_to_piece(i) for i in range(tokenizer.get_piece_size()))
|
| 296 |
+
# The pinned model encodes each of these 4,200 segments as one token.
|
| 297 |
+
# The differential test checks the entire set against SentencePiece.
|
| 298 |
+
return {word[1:]: 1 for word in words if word.startswith(metaspace)}
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def validate_count(count):
|
| 302 |
+
if count > LIMIT:
|
| 303 |
+
raise ValueError("Input has %d Needle tokens; maximum is %d" % (count, LIMIT))
|
| 304 |
+
return count
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def count_tokens(tokenizer, text, fast=False):
|
| 308 |
+
return validate_count(needle_count(tokenizer, text, fast=fast))
|
portable_runtime.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run the MagicEightBall portable ONNX or GGUF profile on CPU."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import hashlib
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
from policy import LIMIT, load_tokenizer
|
| 11 |
+
from runtime import Runtime
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
ARCHITECTURE = "magiceightball"
|
| 15 |
+
PROFILE_REVISION = 1
|
| 16 |
+
TABLE = "decision.table"
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class OnnxRequest:
|
| 20 |
+
def __init__(self, model):
|
| 21 |
+
from onnxruntime import InferenceSession, SessionOptions
|
| 22 |
+
|
| 23 |
+
options = SessionOptions()
|
| 24 |
+
options.intra_op_num_threads = 1
|
| 25 |
+
self.session = InferenceSession(model, sess_options=options, providers=["CPUExecutionProvider"])
|
| 26 |
+
self.outputs = [item.name for item in self.session.get_outputs()]
|
| 27 |
+
|
| 28 |
+
def infer(self, tensors):
|
| 29 |
+
return dict(zip(self.outputs, self.session.run(self.outputs, tensors)))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def read_gguf(path):
|
| 33 |
+
from gguf import GGMLQuantizationType, GGUFReader
|
| 34 |
+
|
| 35 |
+
model = GGUFReader(path)
|
| 36 |
+
|
| 37 |
+
def metadata(key):
|
| 38 |
+
field = model.get_field(key)
|
| 39 |
+
if field is None:
|
| 40 |
+
raise ValueError("Missing MagicEightBall GGUF metadata: " + key)
|
| 41 |
+
return field.contents()
|
| 42 |
+
|
| 43 |
+
if (metadata("general.architecture") != ARCHITECTURE
|
| 44 |
+
or metadata("magiceightball.profile_revision") != PROFILE_REVISION
|
| 45 |
+
or metadata("magiceightball.max_tokens") != LIMIT):
|
| 46 |
+
raise ValueError("Unsupported MagicEightBall GGUF profile")
|
| 47 |
+
manifest = {"name": ARCHITECTURE, "variant": "gguf",
|
| 48 |
+
"policy": json.loads(metadata("magiceightball.policy_json"))}
|
| 49 |
+
if len(model.tensors) != 1:
|
| 50 |
+
raise ValueError("MagicEightBall GGUF needs exactly one decision tensor")
|
| 51 |
+
tensor = model.tensors[0]
|
| 52 |
+
if tensor.name != TABLE or tensor.tensor_type != GGMLQuantizationType.I8 or tensor.data.ndim != 1:
|
| 53 |
+
raise ValueError("Expected a rank-one I8 decision.table tensor")
|
| 54 |
+
return manifest, tensor.data.copy()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class PortableRuntime(Runtime):
|
| 58 |
+
def __init__(self, artifact):
|
| 59 |
+
path = Path(artifact).resolve()
|
| 60 |
+
self.folder = path.parent
|
| 61 |
+
self.lane = "cpu"
|
| 62 |
+
self.target = "CPU"
|
| 63 |
+
self.fast_count = True
|
| 64 |
+
self.tokenizer = load_tokenizer()
|
| 65 |
+
suffix = path.suffix.lower()
|
| 66 |
+
if suffix == ".gguf":
|
| 67 |
+
self.bundle_info, self.table = read_gguf(path)
|
| 68 |
+
self._use_bank(None)
|
| 69 |
+
outputs = len(self.policy.outputs)
|
| 70 |
+
if (not 1 <= outputs <= 7 or len(self.table) != 1 << len(self.policy.literals)
|
| 71 |
+
or np.any(self.table < 0) or np.any(self.table >= 1 << outputs)):
|
| 72 |
+
raise ValueError("Decision tensor does not match the embedded policy")
|
| 73 |
+
elif suffix == ".onnx":
|
| 74 |
+
self.bundle_info = json.loads(path.with_name("model.json").read_text(encoding="utf8"))
|
| 75 |
+
self._use_bank(None)
|
| 76 |
+
model = path.read_bytes()
|
| 77 |
+
if self.info["variant"] not in ("gather", "dense") or (
|
| 78 |
+
hashlib.sha256(model).hexdigest() != self.info["onnx_sha256"]):
|
| 79 |
+
raise ValueError("Unexpected MagicEightBall ONNX artifact")
|
| 80 |
+
self.output = self.info["decisions"]
|
| 81 |
+
self.request = OnnxRequest(model)
|
| 82 |
+
else:
|
| 83 |
+
raise ValueError("Choose a MagicEightBall .onnx or .gguf file")
|
| 84 |
+
|
| 85 |
+
def head(self, atoms):
|
| 86 |
+
if self.info["variant"] != "gguf":
|
| 87 |
+
return super().head(atoms)
|
| 88 |
+
address = sum(int(bit) << index for index, bit in enumerate(atoms))
|
| 89 |
+
word = int(self.table[address])
|
| 90 |
+
return np.array([(word >> index) & 1 for index in range(len(self.policy.outputs))], dtype=np.float32)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def main():
|
| 94 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 95 |
+
parser.add_argument("artifact", type=Path)
|
| 96 |
+
parser.add_argument("--explain", action="store_true")
|
| 97 |
+
source = parser.add_mutually_exclusive_group(required=True)
|
| 98 |
+
source.add_argument("--text")
|
| 99 |
+
source.add_argument("--file", type=Path)
|
| 100 |
+
args = parser.parse_args()
|
| 101 |
+
text = args.text if args.file is None else args.file.read_bytes().decode("utf-8-sig")
|
| 102 |
+
runtime = PortableRuntime(args.artifact)
|
| 103 |
+
try:
|
| 104 |
+
outcome = runtime.decide(text, explain=args.explain)
|
| 105 |
+
except ValueError as error:
|
| 106 |
+
parser.error(str(error))
|
| 107 |
+
print(json.dumps(dict(outcome, backend=runtime.target, format=args.artifact.suffix.lower()[1:])))
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
if __name__ == "__main__":
|
| 111 |
+
main()
|
radix.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Lossless integer words stored in the normal finite FP16 encodings."""
|
| 2 |
+
import numpy as np
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
SIGN_BIT = 0x8000
|
| 6 |
+
FIRST_NORMAL = 0x0400
|
| 7 |
+
NORMAL_PER_SIGN = 0x7800
|
| 8 |
+
CAPACITY = 2 * NORMAL_PER_SIGN
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def encode_ranks(ranks):
|
| 12 |
+
ranks = np.asarray(ranks, dtype=np.int32)
|
| 13 |
+
if np.any((ranks < 0) | (ranks >= CAPACITY)):
|
| 14 |
+
raise ValueError("Radix word is outside the finite FP16 code space")
|
| 15 |
+
bits = FIRST_NORMAL + ranks + np.where(ranks < NORMAL_PER_SIGN, 0, SIGN_BIT - NORMAL_PER_SIGN)
|
| 16 |
+
return bits.astype(np.uint16).view(np.float16)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def decode_ranks(words):
|
| 20 |
+
halves = words
|
| 21 |
+
if words.dtype != np.float16:
|
| 22 |
+
if not np.isfinite(words).all() or np.any(np.abs(words) > 65504):
|
| 23 |
+
raise RuntimeError("Radix head returned an invalid FP16 word")
|
| 24 |
+
halves = words.astype(np.float16)
|
| 25 |
+
if not np.array_equal(halves, words):
|
| 26 |
+
raise RuntimeError("Radix head returned an inexact FP16 word")
|
| 27 |
+
bits = halves.view(np.uint16).astype(np.int32)
|
| 28 |
+
magnitude = bits & (SIGN_BIT - 1)
|
| 29 |
+
if np.any((magnitude < FIRST_NORMAL) | (magnitude >= FIRST_NORMAL + NORMAL_PER_SIGN)):
|
| 30 |
+
raise RuntimeError("Radix head returned a non-normal FP16 word")
|
| 31 |
+
return magnitude - FIRST_NORMAL + np.where(bits & SIGN_BIT, NORMAL_PER_SIGN, 0)
|
release.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Transport a Gather manifest and both native 2020.3 blobs losslessly."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import struct
|
| 6 |
+
import zlib
|
| 7 |
+
|
| 8 |
+
from blob_layout import compact_gather_blob, inspect_blob
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
MAGIC = b"M8B1"
|
| 12 |
+
HEADER = struct.Struct("<4s3I")
|
| 13 |
+
TARGETS = {"ncs1": ("ncs1-native.blob", "VPU_MYRIAD_2450"),
|
| 14 |
+
"ncs2": ("ncs2-2020.3.blob", "VPU_MYRIAD_2480")}
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _validate(manifest, blobs):
|
| 18 |
+
if not isinstance(manifest, dict) or manifest.get("variant") != "gather":
|
| 19 |
+
raise ValueError("Release requires a Gather manifest")
|
| 20 |
+
inputs = manifest.get("input_shapes")
|
| 21 |
+
shape = inputs.get("features") if isinstance(inputs, dict) else None
|
| 22 |
+
if not isinstance(shape, list) or len(shape) != 1 or type(shape[0]) is not int or shape[0] < 1:
|
| 23 |
+
raise ValueError("Release has invalid Gather geometry")
|
| 24 |
+
for stick, blob in blobs.items():
|
| 25 |
+
count = manifest.get("fp16_coefficient_bytes") if stick == "ncs1" else None
|
| 26 |
+
layout = inspect_blob(blob, compact_coefficients=count)
|
| 27 |
+
if (layout["input_bytes"] != shape[0] * 4 or layout["output_bytes"] != shape[0] * 2
|
| 28 |
+
or layout["stage_count"] != 1 or layout["sole_stage"]["type"] != 100):
|
| 29 |
+
raise ValueError("Native Gather blob does not match the release geometry")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def pack_bundle(directory, compact_ncs1=False):
|
| 33 |
+
manifest = (directory / "model.json").read_bytes()
|
| 34 |
+
blobs = {stick: (directory / filename).read_bytes()
|
| 35 |
+
for stick, (filename, _) in TARGETS.items()}
|
| 36 |
+
model = json.loads(manifest)
|
| 37 |
+
_validate(model, blobs)
|
| 38 |
+
if compact_ncs1:
|
| 39 |
+
blobs["ncs1"] = compact_gather_blob(blobs["ncs1"], model.get("fp16_coefficient_bytes"))
|
| 40 |
+
manifest = json.dumps(model, ensure_ascii=False, separators=(",", ":")).encode("utf8")
|
| 41 |
+
fields = (manifest, blobs["ncs1"], blobs["ncs2"])
|
| 42 |
+
return zlib.compress(HEADER.pack(MAGIC, *(len(field) for field in fields)) + b"".join(fields), 9)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def read_release(path):
|
| 46 |
+
try:
|
| 47 |
+
data = zlib.decompress(path.read_bytes())
|
| 48 |
+
except zlib.error as exc:
|
| 49 |
+
raise ValueError("Unreadable MagicEightBall release") from exc
|
| 50 |
+
if len(data) < HEADER.size:
|
| 51 |
+
raise ValueError("Missing MagicEightBall release header")
|
| 52 |
+
magic, manifest_size, ncs1_size, ncs2_size = HEADER.unpack_from(data)
|
| 53 |
+
boundary = HEADER.size + manifest_size
|
| 54 |
+
split = boundary + ncs1_size
|
| 55 |
+
if magic != MAGIC or split + ncs2_size != len(data):
|
| 56 |
+
raise ValueError("Invalid MagicEightBall release layout")
|
| 57 |
+
manifest = json.loads(data[HEADER.size:boundary])
|
| 58 |
+
blobs = {"ncs1": data[boundary:split], "ncs2": data[split:]}
|
| 59 |
+
_validate(manifest, blobs)
|
| 60 |
+
return manifest, blobs
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
if __name__ == "__main__":
|
| 64 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 65 |
+
parser.add_argument("bundle", type=Path)
|
| 66 |
+
parser.add_argument("output", type=Path)
|
| 67 |
+
parser.add_argument("--compact-ncs1", action="store_true", help="Remove verified NCS1 terminal zero padding")
|
| 68 |
+
args = parser.parse_args()
|
| 69 |
+
archive = pack_bundle(args.bundle, args.compact_ncs1)
|
| 70 |
+
args.output.write_bytes(archive)
|
| 71 |
+
print("%d bytes" % len(archive))
|
runtime.py
ADDED
|
@@ -0,0 +1,455 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Persistent MYRIAD runner for document-wide Boolean policies."""
|
| 2 |
+
import argparse
|
| 3 |
+
from copy import copy
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
import hashlib
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import subprocess
|
| 10 |
+
import sys
|
| 11 |
+
import tempfile
|
| 12 |
+
import time
|
| 13 |
+
from typing import Optional
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
from policy import Policy, count_tokens, load_tokenizer, validate_count
|
| 17 |
+
from radix import decode_ranks
|
| 18 |
+
from release import TARGETS, read_release
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@dataclass
|
| 22 |
+
class Prepared:
|
| 23 |
+
tokens: int
|
| 24 |
+
atoms: Optional[np.ndarray]
|
| 25 |
+
projected: Optional[bytes]
|
| 26 |
+
started: float
|
| 27 |
+
counted: float
|
| 28 |
+
ready: float
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class Runtime:
|
| 32 |
+
def __init__(self, bundle, toolchain=None, fast_count=True, lane="ncs1", target=None, blob=None, bank=None,
|
| 33 |
+
release_stick="ncs1"):
|
| 34 |
+
self.folder = Path(bundle).resolve()
|
| 35 |
+
native_release = None
|
| 36 |
+
if self.folder.suffix.lower() == ".m8b":
|
| 37 |
+
if lane != "ncs1" or blob is not None:
|
| 38 |
+
raise ValueError("Release archives use the 2020.3 runtime and contain their own native blobs")
|
| 39 |
+
if release_stick not in TARGETS:
|
| 40 |
+
raise ValueError("Choose ncs1 or ncs2 for the native release")
|
| 41 |
+
self.bundle_info, blobs = read_release(self.folder)
|
| 42 |
+
native_release = blobs[release_stick]
|
| 43 |
+
else:
|
| 44 |
+
self.bundle_info = json.loads((self.folder/"model.json").read_text(encoding="utf8"))
|
| 45 |
+
self._use_bank(bank)
|
| 46 |
+
self.tokenizer = load_tokenizer()
|
| 47 |
+
self.fast_count = fast_count
|
| 48 |
+
self.lane = lane
|
| 49 |
+
self.output = self.info["decisions"]
|
| 50 |
+
if lane == "ncs1":
|
| 51 |
+
if toolchain is None:
|
| 52 |
+
toolchain = Path(__file__).resolve().parents[3] / "tools" / "ncs1"
|
| 53 |
+
sys.path.insert(0, str(Path(toolchain).resolve()))
|
| 54 |
+
import ncs1_paths
|
| 55 |
+
ncs1_paths.setup()
|
| 56 |
+
from openvino.inference_engine import IECore, get_version
|
| 57 |
+
self.core = IECore()
|
| 58 |
+
elif lane == "ncs2":
|
| 59 |
+
from openvino.runtime import Core, get_version
|
| 60 |
+
self.core = Core()
|
| 61 |
+
else:
|
| 62 |
+
raise ValueError("Unknown MYRIAD lane: " + lane)
|
| 63 |
+
self.openvino_version = get_version()
|
| 64 |
+
self.devices = list(self.core.available_devices)
|
| 65 |
+
myriad = [name for name in self.devices if name.split(".", 1)[0] == "MYRIAD"]
|
| 66 |
+
if not myriad:
|
| 67 |
+
raise RuntimeError("No physical MYRIAD device visible to %s (%s)" % (lane, self.openvino_version))
|
| 68 |
+
if target is None and len(myriad) != 1:
|
| 69 |
+
raise ValueError("Choose --target from %s" % myriad)
|
| 70 |
+
self.target = target if target is not None else myriad[0]
|
| 71 |
+
if self.target not in myriad:
|
| 72 |
+
raise ValueError("Expected a visible MYRIAD device from %s" % myriad)
|
| 73 |
+
|
| 74 |
+
self.ir = None if blob is not None or native_release is not None else self.resolve_ir()
|
| 75 |
+
start = time.perf_counter()
|
| 76 |
+
if lane == "ncs1":
|
| 77 |
+
if native_release is not None:
|
| 78 |
+
platform = TARGETS[release_stick][1]
|
| 79 |
+
config = {"VPU_MYRIAD_PLATFORM": platform, "VPU_MYRIAD_PROTOCOL": "VPU_MYRIAD_USB"}
|
| 80 |
+
with tempfile.TemporaryDirectory(prefix="magiceightball-") as directory:
|
| 81 |
+
native = Path(directory) / "network.blob"
|
| 82 |
+
native.write_bytes(native_release)
|
| 83 |
+
self.compiled = self.core.import_network(str(native), self.target, config=config, num_requests=1)
|
| 84 |
+
elif blob is not None:
|
| 85 |
+
self.compiled = self.core.import_network(str(blob), self.target, num_requests=1)
|
| 86 |
+
else:
|
| 87 |
+
net = self.core.read_network(model=str(self.ir), weights=str(self.ir.with_suffix(".bin")))
|
| 88 |
+
if self.output not in net.outputs and not (self.info["variant"] == "gather" and len(net.outputs) == 1):
|
| 89 |
+
raise ValueError("Unexpected IR outputs: %s" % list(net.outputs))
|
| 90 |
+
if self.info["variant"] == "gather":
|
| 91 |
+
net.outputs[next(iter(net.outputs))].precision = "FP16"
|
| 92 |
+
self.compiled = self.core.load_network(network=net, device_name=self.target, num_requests=1)
|
| 93 |
+
self.request = self.compiled
|
| 94 |
+
else:
|
| 95 |
+
self.compiled = (self.core.import_model(blob.read_bytes(), self.target) if blob is not None
|
| 96 |
+
else self.core.compile_model(str(self.ir), self.target))
|
| 97 |
+
self.output = self.compiled.output(0 if self.info["variant"] == "gather" else self.output)
|
| 98 |
+
self.request = self.compiled.create_infer_request()
|
| 99 |
+
self.load_ms = 1000*(time.perf_counter()-start)
|
| 100 |
+
|
| 101 |
+
def _use_bank(self, bank):
|
| 102 |
+
banks = self.bundle_info.get("banks", {})
|
| 103 |
+
self.bank = self.bundle_info.get("default_bank") if bank is None else bank
|
| 104 |
+
if self.bank is not None and (not isinstance(self.bank, str) or self.bank not in banks):
|
| 105 |
+
raise ValueError("Unknown policy bank: %r" % (self.bank,))
|
| 106 |
+
self.info = dict(self.bundle_info, **banks.get(self.bank, {}))
|
| 107 |
+
self.policy = Policy(self.info["policy"])
|
| 108 |
+
self.model_name = self.bundle_info.get("name", self.info["policy"].get("name", self.folder.name))
|
| 109 |
+
|
| 110 |
+
def policy_view(self, bank):
|
| 111 |
+
if bank is None or bank == self.bank:
|
| 112 |
+
return self
|
| 113 |
+
view = copy(self)
|
| 114 |
+
view._use_bank(bank)
|
| 115 |
+
return view
|
| 116 |
+
|
| 117 |
+
def resolve_ir(self):
|
| 118 |
+
source = self.folder/"model.onnx"
|
| 119 |
+
model_hash = hashlib.sha256(source.read_bytes()).hexdigest()
|
| 120 |
+
if model_hash != self.info["onnx_sha256"]:
|
| 121 |
+
raise ValueError("Unexpected ONNX artifact")
|
| 122 |
+
ir = self.folder/"ir"/model_hash
|
| 123 |
+
xml = ir/"model.xml"
|
| 124 |
+
binary = ir/"model.bin"
|
| 125 |
+
if not xml.exists() or not binary.exists():
|
| 126 |
+
if self.lane == "ncs1":
|
| 127 |
+
import ncs1_paths
|
| 128 |
+
ir.mkdir(exist_ok=True, parents=True)
|
| 129 |
+
subprocess.run([sys.executable, str(ncs1_paths.MO/"mo_onnx.py"),
|
| 130 |
+
"--input_model", str(source), "--data_type", "FP16",
|
| 131 |
+
"--output_dir", str(ir)], timeout=120, check=True,
|
| 132 |
+
env=dict(os.environ, PYTHONPATH=str(ncs1_paths.MO)))
|
| 133 |
+
else:
|
| 134 |
+
from openvino.runtime import serialize
|
| 135 |
+
from openvino.tools.mo import convert_model
|
| 136 |
+
# Cache separately so a new toolchain never overwrites the IR10 pair.
|
| 137 |
+
xml = ir / "2022.3" / "model.xml"
|
| 138 |
+
if not xml.exists() or not xml.with_suffix(".bin").exists():
|
| 139 |
+
xml.parent.mkdir(exist_ok=True, parents=True)
|
| 140 |
+
serialize(convert_model(str(source), compress_to_fp16=True), str(xml))
|
| 141 |
+
return xml
|
| 142 |
+
|
| 143 |
+
def export_blob(self, path):
|
| 144 |
+
if self.lane == "ncs1":
|
| 145 |
+
self.compiled.export(str(path))
|
| 146 |
+
else:
|
| 147 |
+
path.write_bytes(self.compiled.export_model())
|
| 148 |
+
|
| 149 |
+
def head(self, atoms):
|
| 150 |
+
variant = self.info["variant"]
|
| 151 |
+
if variant == "gather":
|
| 152 |
+
return self.gather_heads([atoms])[0]
|
| 153 |
+
if variant in ("lookup", "packed"):
|
| 154 |
+
mask = sum(int(bit) << j for j, bit in enumerate(atoms))
|
| 155 |
+
features = np.zeros(self.info["input_shapes"]["features"], dtype=np.float32)
|
| 156 |
+
features[0, mask >> self.info.get("lane_bits", 0), 0, 0] = 1
|
| 157 |
+
packed = self.request.infer({"features": features})[self.output].reshape(-1)
|
| 158 |
+
self.validate_words(packed)
|
| 159 |
+
if variant == "packed":
|
| 160 |
+
return self.unpack(packed[0], mask)
|
| 161 |
+
return np.array([(int(packed[k//10]) >> (k%10)) & 1
|
| 162 |
+
for k in range(len(self.policy.outputs))],dtype=np.float32)
|
| 163 |
+
result = self.request.infer({"features": atoms.reshape(1,-1,1,1)})
|
| 164 |
+
return result[self.output].reshape(-1).copy()
|
| 165 |
+
|
| 166 |
+
@property
|
| 167 |
+
def batch_capacity(self):
|
| 168 |
+
return self.info["input_shapes"]["features"][0] if self.info["variant"] == "gather" else 1
|
| 169 |
+
|
| 170 |
+
@staticmethod
|
| 171 |
+
def validate_words(packed):
|
| 172 |
+
if not np.isfinite(packed).all() or not np.array_equal(packed, packed.round()):
|
| 173 |
+
raise RuntimeError("Invalid output from exact lookup head")
|
| 174 |
+
|
| 175 |
+
def unpack(self, number, mask):
|
| 176 |
+
lane = mask & ((1 << self.info["lane_bits"]) - 1)
|
| 177 |
+
width = self.info["code_width"]
|
| 178 |
+
offset = self.info["offset"]
|
| 179 |
+
word = int(number) + offset
|
| 180 |
+
code = (word >> (lane * width)) & ((1 << width) - 1)
|
| 181 |
+
codebook = self.info["codebook"]
|
| 182 |
+
if not 0 <= word < 2 * offset or code >= len(codebook):
|
| 183 |
+
raise RuntimeError("Invalid codeword from exact packed head")
|
| 184 |
+
return np.asarray(codebook[code], dtype=np.float32)
|
| 185 |
+
|
| 186 |
+
def _gather_indices(self, facts):
|
| 187 |
+
pair_order = self.info.get("pair_fact_order")
|
| 188 |
+
if pair_order is None:
|
| 189 |
+
masks = [sum(int(bit) << j for j, bit in enumerate(row)) for row in facts]
|
| 190 |
+
else:
|
| 191 |
+
masks = [sum(int(row[fact]) << bit for bit, fact in enumerate(pair_order)) for row in facts]
|
| 192 |
+
radix_digits = self.info.get("radix_digits")
|
| 193 |
+
offset = self.info.get("bank_offset", 0)
|
| 194 |
+
if radix_digits is None:
|
| 195 |
+
addresses = [offset + (mask >> self.info["lane_bits"]) for mask in masks]
|
| 196 |
+
else:
|
| 197 |
+
addresses = [offset + mask // radix_digits for mask in masks]
|
| 198 |
+
return addresses, masks
|
| 199 |
+
|
| 200 |
+
def _gather_words(self, addresses):
|
| 201 |
+
if not 1 <= len(addresses) <= self.batch_capacity:
|
| 202 |
+
raise ValueError("Gather needs 1–%d decisions per request" % self.batch_capacity)
|
| 203 |
+
features = np.zeros(self.batch_capacity, dtype=np.int32)
|
| 204 |
+
features[:len(addresses)] = addresses
|
| 205 |
+
outputs = self.request.infer({"features": features})
|
| 206 |
+
# The legacy ONNX converter renames the sole Gather output.
|
| 207 |
+
if len(outputs) != 1:
|
| 208 |
+
raise RuntimeError("Expected exactly one packed Gather result")
|
| 209 |
+
words = next(iter(outputs.values())).reshape(-1)
|
| 210 |
+
if words.size != self.batch_capacity:
|
| 211 |
+
raise RuntimeError("Unexpected Gather result width")
|
| 212 |
+
if self.lane == "ncs1" and words.dtype == np.int16:
|
| 213 |
+
# IECore 2020.3 exposes native FP16 buffers as signed words.
|
| 214 |
+
words = words.view(np.float16)
|
| 215 |
+
return words[:len(addresses)]
|
| 216 |
+
|
| 217 |
+
def _gather_decode(self, used, masks):
|
| 218 |
+
radix_digits = self.info.get("radix_digits")
|
| 219 |
+
if radix_digits is not None:
|
| 220 |
+
ranks = decode_ranks(used)
|
| 221 |
+
codebook = np.asarray(self.info["codebook"], dtype=np.float32)
|
| 222 |
+
base = len(codebook)
|
| 223 |
+
if "pair_fact_order" in self.info:
|
| 224 |
+
if np.any(ranks >= base * base * 256):
|
| 225 |
+
raise RuntimeError("Radix head returned an invalid policy pair")
|
| 226 |
+
results = []
|
| 227 |
+
for rank, mask in zip(ranks, masks):
|
| 228 |
+
pair, selectors = divmod(int(rank), 256)
|
| 229 |
+
low, high = divmod(pair, base)
|
| 230 |
+
if high < low:
|
| 231 |
+
raise RuntimeError("Radix head returned an unordered policy pair")
|
| 232 |
+
results.append(codebook[high if selectors & (1 << (mask & 7)) else low])
|
| 233 |
+
return results
|
| 234 |
+
if np.any(ranks >= base ** radix_digits):
|
| 235 |
+
raise RuntimeError("Radix head returned an invalid policy word")
|
| 236 |
+
return [codebook[(int(rank) // base ** (mask % radix_digits)) % base]
|
| 237 |
+
for rank, mask in zip(ranks, masks)]
|
| 238 |
+
self.validate_words(used)
|
| 239 |
+
return [self.unpack(word, mask) for word, mask in zip(used, masks)]
|
| 240 |
+
|
| 241 |
+
def gather_heads(self, facts):
|
| 242 |
+
addresses, masks = self._gather_indices(facts)
|
| 243 |
+
return self._gather_decode(self._gather_words(addresses), masks)
|
| 244 |
+
|
| 245 |
+
def scan(self, projected):
|
| 246 |
+
side = self.info["tile_side"]
|
| 247 |
+
halo = max(map(len, self.policy.patterns))-1
|
| 248 |
+
count = max(1, (len(projected)+side*side-1)//(side*side))
|
| 249 |
+
storage = np.zeros(halo + count*side*side, dtype=np.float32)
|
| 250 |
+
storage[halo:halo+len(projected)] = np.frombuffer(projected, dtype=np.uint8)
|
| 251 |
+
prior = np.zeros((1,len(self.policy.literals),1,1), dtype=np.float32)
|
| 252 |
+
# Each row includes the real preceding lexemes. A phrase can cross either
|
| 253 |
+
# a row or a USB request boundary. Padding code 0 matches no literal.
|
| 254 |
+
rows = np.lib.stride_tricks.as_strided(storage, shape=(count*side, side+halo),
|
| 255 |
+
strides=(side*storage.itemsize,storage.itemsize),
|
| 256 |
+
writeable=False)
|
| 257 |
+
for i in range(count):
|
| 258 |
+
tile = np.ascontiguousarray(rows[i*side:(i+1)*side])[None,None]
|
| 259 |
+
result = self.request.infer({"lexemes": tile, "prior": prior})
|
| 260 |
+
values = result[self.output].reshape(-1)
|
| 261 |
+
n = self.info["state_channels"]
|
| 262 |
+
prior = values[:n].reshape(1,n,1,1).copy()
|
| 263 |
+
return values[n:].copy(), prior.reshape(-1), count
|
| 264 |
+
|
| 265 |
+
def prepare_decision(self, text, prepare=None):
|
| 266 |
+
start = time.perf_counter()
|
| 267 |
+
projected = atoms = None
|
| 268 |
+
scanning = self.info["variant"] == "scan"
|
| 269 |
+
if prepare is not None:
|
| 270 |
+
if scanning:
|
| 271 |
+
raise ValueError("Batch lane selection needs a decision head that accepts fact bits")
|
| 272 |
+
tokens, atoms, counted = prepare(text)
|
| 273 |
+
validate_count(tokens)
|
| 274 |
+
else:
|
| 275 |
+
tokens = count_tokens(self.tokenizer, text, fast=self.fast_count)
|
| 276 |
+
counted = time.perf_counter()
|
| 277 |
+
if scanning or not self.fast_count:
|
| 278 |
+
projected = self.policy.project(text)
|
| 279 |
+
if not scanning:
|
| 280 |
+
atoms = self.policy.atoms(projected)
|
| 281 |
+
else:
|
| 282 |
+
atoms = self.policy.text_atoms(text)
|
| 283 |
+
return Prepared(tokens, atoms, projected, start, counted, time.perf_counter())
|
| 284 |
+
|
| 285 |
+
def decide_prepared(self, documents):
|
| 286 |
+
if not 1 <= len(documents) <= self.batch_capacity:
|
| 287 |
+
raise ValueError("Unexpected number of prepared documents")
|
| 288 |
+
start = time.perf_counter()
|
| 289 |
+
variant = self.info["variant"]
|
| 290 |
+
if variant == "scan":
|
| 291 |
+
document = documents[0]
|
| 292 |
+
bits, atoms, calls = self.scan(document.projected)
|
| 293 |
+
decisions = [(bits, atoms)]
|
| 294 |
+
elif variant == "gather":
|
| 295 |
+
facts = [document.atoms for document in documents]
|
| 296 |
+
decisions = list(zip(self.gather_heads(facts), facts))
|
| 297 |
+
calls = 1
|
| 298 |
+
else:
|
| 299 |
+
atoms = documents[0].atoms
|
| 300 |
+
decisions = [(self.head(atoms), atoms)]
|
| 301 |
+
calls = 1
|
| 302 |
+
return [self._record(doc, bits, atoms, calls, len(documents), start)
|
| 303 |
+
for doc, (bits, atoms) in zip(documents, decisions)]
|
| 304 |
+
|
| 305 |
+
def _record(self, doc, bits, atoms, calls, group_size, start):
|
| 306 |
+
result = self.policy.result(bits > 0.5)
|
| 307 |
+
end = time.perf_counter()
|
| 308 |
+
record = dict(
|
| 309 |
+
model=self.model_name, result=result, bits=bits.tolist(), atoms=atoms.tolist(),
|
| 310 |
+
needle_tokens=doc.tokens, lexemes=len(doc.projected) if doc.projected is not None else None,
|
| 311 |
+
requests=calls, request_documents=group_size, tokenization_ms=(doc.counted-doc.started)*1000,
|
| 312 |
+
host_projection_ms=(doc.ready-doc.counted)*1000,
|
| 313 |
+
inference_path_ms=(end-start)*1000, total_ms=(end-doc.started)*1000,
|
| 314 |
+
)
|
| 315 |
+
if getattr(self, "bank", None) is not None:
|
| 316 |
+
record["bank"] = self.bank
|
| 317 |
+
return record
|
| 318 |
+
|
| 319 |
+
def decide_mixed(self, documents, explain=False):
|
| 320 |
+
"""Submit documents from several policy banks in the same Gather request."""
|
| 321 |
+
if self.info["variant"] != "gather" or not isinstance(documents, list) or not documents:
|
| 322 |
+
raise ValueError("A Gather batch needs a nonempty documents array")
|
| 323 |
+
results, pending, views = [None] * len(documents), [], {}
|
| 324 |
+
requests = 0
|
| 325 |
+
|
| 326 |
+
def flush():
|
| 327 |
+
nonlocal requests
|
| 328 |
+
if not pending:
|
| 329 |
+
return
|
| 330 |
+
start = time.perf_counter()
|
| 331 |
+
groups = {}
|
| 332 |
+
for position, (_, view, _, doc) in enumerate(pending):
|
| 333 |
+
groups.setdefault(view, []).append((position, doc.atoms))
|
| 334 |
+
addresses = np.empty(len(pending), dtype=np.int32)
|
| 335 |
+
indices = {}
|
| 336 |
+
for view, entries in groups.items():
|
| 337 |
+
positions, facts = zip(*entries)
|
| 338 |
+
bank_addresses, masks = view._gather_indices(facts)
|
| 339 |
+
addresses[list(positions)] = bank_addresses
|
| 340 |
+
indices[view] = (list(positions), masks)
|
| 341 |
+
words = self._gather_words(addresses)
|
| 342 |
+
requests += 1
|
| 343 |
+
for view, (positions, masks) in indices.items():
|
| 344 |
+
for position, bits in zip(positions, view._gather_decode(words[positions], masks)):
|
| 345 |
+
index, _, text, doc = pending[position]
|
| 346 |
+
record = view._record(doc, bits, doc.atoms, 1, len(pending), start)
|
| 347 |
+
if explain:
|
| 348 |
+
record["explanation"] = view.policy.explain(text, doc.atoms)
|
| 349 |
+
results[index] = dict(record, id=documents[index].get("id"))
|
| 350 |
+
pending.clear()
|
| 351 |
+
|
| 352 |
+
for index, row in enumerate(documents):
|
| 353 |
+
request_id = row.get("id") if isinstance(row, dict) else None
|
| 354 |
+
try:
|
| 355 |
+
if not isinstance(row, dict) or not isinstance(row.get("text"), str):
|
| 356 |
+
raise ValueError("Each document needs a text string")
|
| 357 |
+
bank = row.get("bank")
|
| 358 |
+
if bank is not None and not isinstance(bank, str):
|
| 359 |
+
raise ValueError("Policy bank must be a string")
|
| 360 |
+
if bank not in views:
|
| 361 |
+
views[bank] = self.policy_view(bank)
|
| 362 |
+
view = views[bank]
|
| 363 |
+
pending.append((index, view, row["text"], view.prepare_decision(row["text"])))
|
| 364 |
+
except ValueError as exc:
|
| 365 |
+
results[index] = {"id": request_id, "error": str(exc)}
|
| 366 |
+
continue
|
| 367 |
+
if len(pending) == self.batch_capacity:
|
| 368 |
+
flush()
|
| 369 |
+
flush()
|
| 370 |
+
return {"documents": results, "device_requests": requests}
|
| 371 |
+
|
| 372 |
+
def decide(self, text, explain=False, prepare=None):
|
| 373 |
+
record = self.decide_prepared([self.prepare_decision(text, prepare)])[0]
|
| 374 |
+
if explain:
|
| 375 |
+
record["explanation"] = self.policy.explain(text, record["atoms"])
|
| 376 |
+
return record
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def json_output_stream():
|
| 380 |
+
# Legacy MYRIAD prints firmware messages to native stdout, including
|
| 381 |
+
# during teardown. Save the caller's stream and redirect diagnostics
|
| 382 |
+
# before loading the plugin so stdout remains a clean JSON protocol.
|
| 383 |
+
sys.stdout.flush()
|
| 384 |
+
stdout_fd = sys.stdout.fileno()
|
| 385 |
+
output = os.fdopen(os.dup(stdout_fd), "w", encoding="utf8")
|
| 386 |
+
os.dup2(sys.stderr.fileno(), stdout_fd)
|
| 387 |
+
if os.name == "nt":
|
| 388 |
+
import ctypes
|
| 389 |
+
from ctypes import wintypes
|
| 390 |
+
import msvcrt
|
| 391 |
+
set_handle = ctypes.windll.kernel32.SetStdHandle
|
| 392 |
+
set_handle.argtypes = (wintypes.DWORD, wintypes.HANDLE)
|
| 393 |
+
set_handle.restype = wintypes.BOOL
|
| 394 |
+
if not set_handle(0xFFFFFFF5, msvcrt.get_osfhandle(stdout_fd)): # STD_OUTPUT_HANDLE
|
| 395 |
+
output.close()
|
| 396 |
+
raise OSError("Could not redirect native stdout")
|
| 397 |
+
return output
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
def main():
|
| 401 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 402 |
+
parser.add_argument("bundle", type=Path)
|
| 403 |
+
parser.add_argument("--toolchain", type=Path, help="Override the NCS1 toolchain directory")
|
| 404 |
+
parser.add_argument("--lane", choices=["ncs1", "ncs2"], default="ncs1")
|
| 405 |
+
parser.add_argument("--target", help="Explicit OpenVINO name when several MYRIAD devices are visible")
|
| 406 |
+
parser.add_argument("--blob", type=Path, help="Load a binary exported by the matching device/toolchain")
|
| 407 |
+
parser.add_argument("--bank", help="Default policy bank for a banked bundle")
|
| 408 |
+
parser.add_argument("--release-stick", choices=list(TARGETS), default="ncs1",
|
| 409 |
+
help="Physical target for a .m8b archive on OpenVINO 2020.3")
|
| 410 |
+
parser.add_argument("--explain", action="store_true")
|
| 411 |
+
source = parser.add_mutually_exclusive_group(required=True)
|
| 412 |
+
source.add_argument("--text")
|
| 413 |
+
source.add_argument("--file", type=Path)
|
| 414 |
+
source.add_argument("--serve", action="store_true", help="Read one JSON request with text and optional id per line")
|
| 415 |
+
source.add_argument("--stream", action="store_true", help="Append JSONL fragments to one resident document")
|
| 416 |
+
args = parser.parse_args()
|
| 417 |
+
with json_output_stream() as output:
|
| 418 |
+
engine = Runtime(args.bundle, args.toolchain, lane=args.lane, target=args.target, blob=args.blob, bank=args.bank,
|
| 419 |
+
release_stick=args.release_stick)
|
| 420 |
+
if args.serve or args.stream:
|
| 421 |
+
stream = None
|
| 422 |
+
if args.stream:
|
| 423 |
+
from stream import DecisionStream
|
| 424 |
+
stream = DecisionStream(engine, args.explain)
|
| 425 |
+
for line in sys.stdin.buffer:
|
| 426 |
+
request_id = None
|
| 427 |
+
try:
|
| 428 |
+
request = json.loads(line)
|
| 429 |
+
if not isinstance(request, dict):
|
| 430 |
+
raise ValueError("Expected an object with a text string")
|
| 431 |
+
request_id = request.get("id")
|
| 432 |
+
if stream is not None:
|
| 433 |
+
if "append" not in request and request.get("reset") is not True:
|
| 434 |
+
raise ValueError("Expected an append string or reset=true")
|
| 435 |
+
response = stream.append(request.get("append", ""), request.get("reset", False))
|
| 436 |
+
elif "documents" in request:
|
| 437 |
+
response = engine.decide_mixed(request["documents"], args.explain)
|
| 438 |
+
elif not isinstance(request.get("text"), str):
|
| 439 |
+
raise ValueError("Expected an object with a text string")
|
| 440 |
+
else:
|
| 441 |
+
response = engine.policy_view(request.get("bank")).decide(request["text"], args.explain)
|
| 442 |
+
except ValueError as exc:
|
| 443 |
+
response = {"error": str(exc)}
|
| 444 |
+
except RuntimeError as exc:
|
| 445 |
+
if stream is None:
|
| 446 |
+
raise
|
| 447 |
+
response = {"error": str(exc)}
|
| 448 |
+
print(json.dumps(dict(response, id=request_id)), file=output, flush=True)
|
| 449 |
+
else:
|
| 450 |
+
document = args.text if args.text is not None else args.file.read_bytes().decode("utf8")
|
| 451 |
+
print(json.dumps(engine.decide(document, args.explain)), file=output)
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
if __name__ == "__main__":
|
| 455 |
+
main()
|
verification.json
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"fact_assignments": 128,
|
| 3 |
+
"short_documents": 128,
|
| 4 |
+
"context_cases": [
|
| 5 |
+
{
|
| 6 |
+
"name": "full_authorized",
|
| 7 |
+
"tokens": 131072,
|
| 8 |
+
"result": {
|
| 9 |
+
"answers": {
|
| 10 |
+
"may_route": true
|
| 11 |
+
},
|
| 12 |
+
"category": "billing",
|
| 13 |
+
"action": "review_billing"
|
| 14 |
+
}
|
| 15 |
+
},
|
| 16 |
+
{
|
| 17 |
+
"name": "full_late_veto",
|
| 18 |
+
"tokens": 131072,
|
| 19 |
+
"result": {
|
| 20 |
+
"answers": {
|
| 21 |
+
"may_route": false
|
| 22 |
+
},
|
| 23 |
+
"category": "billing",
|
| 24 |
+
"action": null
|
| 25 |
+
}
|
| 26 |
+
}
|
| 27 |
+
],
|
| 28 |
+
"first_rejected_length": 131073,
|
| 29 |
+
"artifact_bytes": 1024,
|
| 30 |
+
"artifact_sha256": "04d3b8df61cca763eee906f1c6bd116b69e59eaae56e90e1179193d19f108117",
|
| 31 |
+
"backend": "CPU",
|
| 32 |
+
"gguf_architecture": "magiceightball",
|
| 33 |
+
"decision_tensor_bytes": 128
|
| 34 |
+
}
|