Token Classification
ONNX
GLiNER2
English
onnxruntime
named-entity-recognition
zero-shot
natural-language-inference
deberta-v3
on-device
iris
Instructions to use iris-hq/iris-names with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- GLiNER2
How to use iris-hq/iris-names with GLiNER2:
from gliner2 import AutoExtractor extractor = AutoExtractor.from_pretrained("iris-hq/iris-names") # Extract entities text = "Apple CEO Tim Cook announced iPhone 15 in Cupertino yesterday." result = extractor.extract_entities(text, ["company", "person", "product", "location"]) print(result) - Notebooks
- Google Colab
- Kaggle
Rewrite the model card, correct the notices, add an example and a rebuild script
Browse files- LICENSE-APACHE-2.0.txt +202 -0
- LICENSES.md +23 -32
- README.md +124 -159
- SHA256SUMS +11 -0
- examples/extract.py +250 -0
- scripts/build_bundle.py +254 -0
LICENSE-APACHE-2.0.txt
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Apache License
|
| 3 |
+
Version 2.0, January 2004
|
| 4 |
+
http://www.apache.org/licenses/
|
| 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
| 178 |
+
|
| 179 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 180 |
+
|
| 181 |
+
To apply the Apache License to your work, attach the following
|
| 182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 183 |
+
replaced with your own identifying information. (Don't include
|
| 184 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 185 |
+
comment syntax for the file format. We also recommend that a
|
| 186 |
+
file or class name and description of purpose be included on the
|
| 187 |
+
same "printed page" as the copyright notice for easier
|
| 188 |
+
identification within third-party archives.
|
| 189 |
+
|
| 190 |
+
Copyright [yyyy] [name of copyright owner]
|
| 191 |
+
|
| 192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 193 |
+
you may not use this file except in compliance with the License.
|
| 194 |
+
You may obtain a copy of the License at
|
| 195 |
+
|
| 196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 197 |
+
|
| 198 |
+
Unless required by applicable law or agreed to in writing, software
|
| 199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 201 |
+
See the License for the specific language governing permissions and
|
| 202 |
+
limitations under the License.
|
LICENSES.md
CHANGED
|
@@ -1,46 +1,29 @@
|
|
| 1 |
-
#
|
| 2 |
|
| 3 |
-
|
| 4 |
|
| 5 |
-
|
| 6 |
-
- **Pinned Revision:** `07d99c0ba5d15cb3b24e0a236fa99bdd4ef87a5c`
|
| 7 |
-
- **Author:** Fastino AI (`fastino-ai/GLiNER2`)
|
| 8 |
-
- **Base Encoder:** [`microsoft/deberta-v3-base`](https://huggingface.co/microsoft/deberta-v3-base) (MIT License)
|
| 9 |
-
- **License:** Apache License 2.0
|
| 10 |
|
| 11 |
-
``
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
you may not use this file except in compliance with the License.
|
| 16 |
-
You may obtain a copy of the License at
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
Unless required by applicable law or agreed to in writing, software
|
| 21 |
-
distributed under the License is distributed on an "AS IS" BASIS,
|
| 22 |
-
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 23 |
-
See the License for the specific language governing permissions and
|
| 24 |
-
limitations under the License.
|
| 25 |
-
```
|
| 26 |
|
| 27 |
-
---
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
-
|
| 30 |
|
| 31 |
-
|
| 32 |
-
- **Pinned Revision (Xenova):** `72a1ce83a0144efaf828b3c3844320a61197a53d`
|
| 33 |
-
- **Upstream PyTorch Checkpoint:** [`MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli`](https://huggingface.co/MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli) (revision `ef67fd0301dd3eebc5eed7fd3fae0ef2fc0bbd0a`)
|
| 34 |
-
- **Author:** Moritz Laurer (ONNX conversion and Q4F16 quantization by Joshua Lochner / Xenova; base model `microsoft/deberta-v3-base` by Microsoft)
|
| 35 |
-
- **Model License:** MIT License
|
| 36 |
-
- **Training Data Notice (ANLI):** This checkpoint was fine-tuned on MultiNLI, FEVER-NLI, and Adversarial NLI (ANLI). The ANLI dataset is licensed under **CC BY-NC 4.0** (Creative Commons Attribution-NonCommercial 4.0 International; Nie et al., 2020).
|
| 37 |
|
| 38 |
```text
|
| 39 |
MIT License
|
| 40 |
|
| 41 |
-
Copyright (c) Microsoft Corporation
|
| 42 |
-
Copyright (c) Moritz Laurer (MNLI/FEVER/ANLI fine-tuned checkpoint)
|
| 43 |
-
Copyright (c) Joshua Lochner / Xenova (ONNX export and Q4F16 quantization)
|
| 44 |
|
| 45 |
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 46 |
of this software and associated documentation files (the "Software"), to deal
|
|
@@ -60,3 +43,11 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
| 60 |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 61 |
SOFTWARE.
|
| 62 |
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licences and notices
|
| 2 |
|
| 3 |
+
This repository redistributes two third-party models in converted form. Their licences apply to their files. Nothing here was trained.
|
| 4 |
|
| 5 |
+
## `gliner25/`: GLiNER 2.5 Base
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
+
- **Source:** [fastino/gliner2.5-base-v1](https://huggingface.co/fastino/gliner2.5-base-v1), commit `07d99c0ba5d15cb3b24e0a236fa99bdd4ef87a5c`, by Fastino AI.
|
| 8 |
+
- **Licence:** Apache License 2.0, as declared on the model card. The full text is in [LICENSE-APACHE-2.0.txt](LICENSE-APACHE-2.0.txt). The source has no LICENSE or NOTICE file.
|
| 9 |
+
- **Encoder it builds on:** [microsoft/deberta-v3-base](https://huggingface.co/microsoft/deberta-v3-base), by Microsoft (MIT, notice below).
|
| 10 |
+
- **Changes:** the weights were exported from PyTorch to ONNX in FP32, entity spans only, as `encoder/model.onnx`, `encoder/model.onnx_data` and `boundary_head.onnx`. The exporter uses modified functions from `gliner2` 2.1.0 (Apache-2.0). `tokenizer.json` and `tokenizer_config.json` were edited. `config.json` is unchanged.
|
|
|
|
|
|
|
| 11 |
|
| 12 |
+
## `deberta-nli/`: DeBERTa-v3 Base MNLI-FEVER-ANLI
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
- **Original model:** [MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli](https://huggingface.co/MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli), by Moritz Laurer. Licence: MIT, as declared on the model card; it publishes no LICENSE file.
|
| 15 |
+
- **ONNX conversion and Q4F16 quantisation:** [Xenova/DeBERTa-v3-base-mnli-fever-anli](https://huggingface.co/Xenova/DeBERTa-v3-base-mnli-fever-anli), commit `72a1ce83a0144efaf828b3c3844320a61197a53d`, file `onnx/model_q4f16.onnx`. That repository declares no licence of its own and names the original model as its base. It does not record which commit of the original it converted.
|
| 16 |
+
- **Base model:** [microsoft/deberta-v3-base](https://huggingface.co/microsoft/deberta-v3-base), by Microsoft (MIT, notice below).
|
| 17 |
+
- **Changes:** the weights were moved to `model.onnx_data` without changing their values. `tokenizer.json` and `tokenizer_config.json` were edited. `config.json` is unchanged.
|
| 18 |
|
| 19 |
+
**Training data.** The original model was trained on MultiNLI, FEVER-NLI and ANLI. The Hub lists [ANLI](https://huggingface.co/datasets/facebook/anli) as CC BY-NC 4.0 (non-commercial), [MultiNLI](https://huggingface.co/datasets/nyu-mll/multi_nli) as CC BY 3.0, CC BY-SA 3.0, MIT and other, and [FEVER](https://huggingface.co/datasets/fever/fever) as CC BY-SA 3.0 and GPL 3.0. Whether dataset terms reach a trained model is unsettled. Get advice if it matters to your use.
|
| 20 |
|
| 21 |
+
### MIT notice (Microsoft DeBERTa)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
```text
|
| 24 |
MIT License
|
| 25 |
|
| 26 |
+
Copyright (c) Microsoft Corporation.
|
|
|
|
|
|
|
| 27 |
|
| 28 |
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 29 |
of this software and associated documentation files (the "Software"), to deal
|
|
|
|
| 43 |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 44 |
SOFTWARE.
|
| 45 |
```
|
| 46 |
+
|
| 47 |
+
## `scripts/` and `examples/`
|
| 48 |
+
|
| 49 |
+
Apache License 2.0. They include code adapted from [GLiNER2](https://github.com/fastino-ai/GLiNER2) 2.1.0 by Fastino AI (Apache-2.0); each file says what was changed or followed.
|
| 50 |
+
|
| 51 |
+
## Correction
|
| 52 |
+
|
| 53 |
+
Earlier versions of this file listed a commit of the original DeBERTa NLI model that does not exist, and copyright lines for Fastino AI, Moritz Laurer and Xenova that those authors do not publish. Both were removed.
|
README.md
CHANGED
|
@@ -2,189 +2,154 @@
|
|
| 2 |
license: other
|
| 3 |
license_name: apache-2.0-and-mit
|
| 4 |
license_link: https://huggingface.co/iris-hq/iris-names/blob/main/LICENSES.md
|
|
|
|
|
|
|
| 5 |
library_name: onnx
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
tags:
|
| 7 |
- onnx
|
|
|
|
| 8 |
- named-entity-recognition
|
|
|
|
| 9 |
- natural-language-inference
|
|
|
|
|
|
|
|
|
|
| 10 |
- iris
|
| 11 |
-
base_model:
|
| 12 |
-
- fastino/gliner2.5-base-v1
|
| 13 |
-
- MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli
|
| 14 |
---
|
| 15 |
|
| 16 |
-
#
|
| 17 |
|
| 18 |
-
|
| 19 |
|
| 20 |
-
|
| 21 |
-
-
|
| 22 |
-
|
|
|
|
| 23 |
|
| 24 |
-
|
| 25 |
|
| 26 |
-
|
| 27 |
|
| 28 |
-
|
| 29 |
|
| 30 |
-
|
| 31 |
|
| 32 |
-
```
|
| 33 |
-
iris-names-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
model.onnx
|
| 44 |
-
model.onnx_data
|
| 45 |
-
config.json
|
| 46 |
-
tokenizer.json
|
| 47 |
-
tokenizer_config.json
|
| 48 |
```
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
- Pinned commit SHA: `72a1ce83a0144efaf828b3c3844320a61197a53d`
|
| 59 |
-
- Upstream FP32 source: `MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli` (commit `ef67fd0301dd3eebc5eed7fd3fae0ef2fc0bbd0a`)
|
| 60 |
-
- License: MIT (note: ANLI training dataset is CC BY-NC 4.0; see `LICENSES.md`)
|
| 61 |
-
- **Python Export & Reference Environment:**
|
| 62 |
-
- Python `3.13.11`
|
| 63 |
-
- `gliner2==2.1.0`
|
| 64 |
-
- `torch==2.15.0` (CPU)
|
| 65 |
-
- `transformers==4.57.6`
|
| 66 |
-
- `tokenizers==0.22.2`
|
| 67 |
-
- `onnx==1.23.2`, `onnxscript==0.7.2`
|
| 68 |
-
- `onnxruntime==1.23.2`
|
| 69 |
-
|
| 70 |
-
## Three Required Export Patches Against `gliner2==2.1.0`
|
| 71 |
-
|
| 72 |
-
Exporting `fastino/gliner2.5-base-v1`'s `BoundaryHead` (`candidate_pool="shared"`) to ONNX (opset 18, `dynamo=False`) and running it in ONNX Runtime 1.23.2 across arbitrary dynamic word lengths `L >= 1` requires three patches:
|
| 73 |
-
|
| 74 |
-
1. **TorchScript ONNX symbolic for `aten::sort` and `aten::argsort` with `stable=True`:**
|
| 75 |
-
PyTorch's 4-argument `aten::sort.stable(self, stable, dim, descending)` overload passes `descending` as the 4th positional argument (`out`) to `torch.onnx._internal.torchscript_exporter.symbolic_opset11.sort(g, self, dim, descending, out=None)`, raising `OnnxExporterError: Unsupported: ONNX export of operator Sort, Out parameter is not supported`. Registering custom symbolics for `aten::sort` and `aten::argsort` at opset 11 unpacks `(self, stable, dim, descending)` and delegates to `symbolic_helper._sort_helper(g, self, dim, descending=descending, out=None)` (which emits ONNX `TopK(..., sorted=1)`).
|
| 76 |
-
2. **Replace `torch.eye(n, dtype=torch.bool)` and in-place slice mutations in `gliner2/models/boundary/encoding.py`:**
|
| 77 |
-
`torch.eye(n, dtype=torch.bool)` exports an ONNX `EyeLike` node with `dtype=bool`, which fails at session initialization in ONNX Runtime 1.23.2 (`NOT_IMPLEMENTED : Could not find an implementation for EyeLike(9) node`). Replacing `diagonal = torch.eye(n, dtype=torch.bool, device=states.device)` with `diagonal = positions.view(n, 1) == positions.view(1, n)` emits an `Equal` node on `int64` coordinates. Replacing the in-place slice assignments in `shift_left_with_bos` and `shift_right_with_eos` with `torch.cat` and `torch.where` removes graph input mutation warnings.
|
| 78 |
-
3. **Right-pad boundary logits to `k=32` in `select_top_boundaries` (`gliner2/models/boundary/proposal.py`):**
|
| 79 |
-
In eager mode, `k = min(k, n)` where `n = L + 1` is traced as a Python constant (`32` when exported at `L = 40`). On short sentences with `L < 31` words (`n < 32`), an unpadded slice produces `< 32` top boundaries and fails in `DocumentCandidatePool.forward`'s `.expand(b, 32, 32)`. Right-padding `masked` with `k` columns of `MASK_LOGIT` (`-1e4`) and `valid_mask` with `k` columns of `False` before `torch.topk(..., k=k, dim=-1, largest=True, sorted=True)` guarantees a static `32 × 32 = 1024 >= 192` candidate pair grid for any `L >= 1` while masking padded slots to `(score=0, idx=0, valid=False)`, producing 100% identical candidate indices and logits to unmodified PyTorch.
|
| 80 |
-
|
| 81 |
-
### Unified Diff Against `gliner2==2.1.0`
|
| 82 |
-
|
| 83 |
-
```diff
|
| 84 |
-
--- a/gliner2/models/boundary/encoding.py
|
| 85 |
-
+++ b/gliner2/models/boundary/encoding.py
|
| 86 |
-
@@ -38,9 +38,7 @@
|
| 87 |
-
Returns:
|
| 88 |
-
[B, L + 1, H]
|
| 89 |
-
"""
|
| 90 |
-
b, l, h = text_states.shape
|
| 91 |
-
- out = torch.empty(b, l + 1, h, dtype=text_states.dtype, device=text_states.device)
|
| 92 |
-
- out[:, 0] = bos_state.to(text_states.dtype)
|
| 93 |
-
- out[:, 1:] = text_states
|
| 94 |
-
- return out
|
| 95 |
-
+ bos = bos_state.to(text_states.dtype).view(1, 1, h).expand(b, 1, h)
|
| 96 |
-
+ return torch.cat([bos, text_states], dim=1)
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
def shift_right_with_eos(
|
| 100 |
-
@@ -59,13 +57,11 @@
|
| 101 |
-
Returns:
|
| 102 |
-
[B, L + 1, H]
|
| 103 |
-
"""
|
| 104 |
-
b, l, h = text_states.shape
|
| 105 |
-
- out = torch.empty(b, l + 1, h, dtype=text_states.dtype, device=text_states.device)
|
| 106 |
-
- out[:, :l] = text_states
|
| 107 |
-
- out[:, l] = eos_state.to(text_states.dtype)
|
| 108 |
-
- # Place EOS at each sample's own final boundary index n_b.
|
| 109 |
-
- eos = eos_state.to(text_states.dtype).view(1, h).expand(b, h)
|
| 110 |
-
- out[torch.arange(b, device=text_states.device), text_lengths.clamp(max=l)] = eos
|
| 111 |
-
- return out
|
| 112 |
-
+ eos = eos_state.to(text_states.dtype).view(1, 1, h).expand(b, 1, h)
|
| 113 |
-
+ padded = torch.cat([text_states, eos], dim=1)
|
| 114 |
-
+ idx = torch.arange(l + 1, device=text_states.device).unsqueeze(0)
|
| 115 |
-
+ is_eos = idx == text_lengths.clamp(max=l).unsqueeze(1)
|
| 116 |
-
+ return torch.where(is_eos.unsqueeze(-1), eos_state.to(text_states.dtype).view(1, 1, h), padded)
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
class ResidualSwiGLU(nn.Module):
|
| 120 |
-
@@ -118,17 +114,20 @@
|
| 121 |
-
qkv = self.qkv_projection(self.norm(states)).view(
|
| 122 |
-
b, n, 3, self.num_heads, self.head_dim
|
| 123 |
-
)
|
| 124 |
-
- query, key, value = qkv.permute(2, 0, 3, 1, 4)
|
| 125 |
-
+ query, key, value = qkv.unbind(2)
|
| 126 |
-
+ query = query.transpose(1, 2)
|
| 127 |
-
+ key = key.transpose(1, 2)
|
| 128 |
-
+ value = value.transpose(1, 2)
|
| 129 |
-
allowed = mask.view(b, 1, 1, n).expand(b, 1, n, n)
|
| 130 |
-
+ positions = torch.arange(n, device=states.device)
|
| 131 |
-
if self.window > 0:
|
| 132 |
-
- positions = torch.arange(n, device=states.device)
|
| 133 |
-
local = (
|
| 134 |
-
positions.view(n, 1) - positions.view(1, n)
|
| 135 |
-
).abs() <= self.window
|
| 136 |
-
allowed = allowed & local.view(1, 1, n, n)
|
| 137 |
-
# Padding query rows still need one legal key to avoid NaNs.
|
| 138 |
-
- diagonal = torch.eye(n, dtype=torch.bool, device=states.device)
|
| 139 |
-
+ diagonal = positions.view(n, 1) == positions.view(1, n)
|
| 140 |
-
allowed = allowed | diagonal.view(1, 1, n, n)
|
| 141 |
-
attended = F.scaled_dot_product_attention(
|
| 142 |
-
query,
|
| 143 |
-
--- a/gliner2/models/boundary/proposal.py
|
| 144 |
-
+++ b/gliner2/models/boundary/proposal.py
|
| 145 |
-
@@ -93,13 +93,14 @@
|
| 146 |
-
Returns:
|
| 147 |
-
scores [B, Q, k], indices [B, Q, k], valid [B, Q, k].
|
| 148 |
-
"""
|
| 149 |
-
- n = logits.shape[-1]
|
| 150 |
-
- k = min(k, n)
|
| 151 |
-
+ b, q, n = logits.shape
|
| 152 |
-
floor = MASK_LOGIT
|
| 153 |
-
masked = logits.masked_fill(~valid_mask, floor)
|
| 154 |
-
- scores, idx = torch.sort(masked, dim=-1, descending=True, stable=True)
|
| 155 |
-
- scores = scores[..., :k]
|
| 156 |
-
- idx = idx[..., :k]
|
| 157 |
-
- valid = torch.gather(valid_mask, -1, idx)
|
| 158 |
-
+ pad_logits = masked.new_full((b, q, k), floor)
|
| 159 |
-
+ pad_valid = valid_mask.new_zeros((b, q, k))
|
| 160 |
-
+ masked_padded = torch.cat([masked, pad_logits], dim=-1)
|
| 161 |
-
+ valid_padded = torch.cat([valid_mask, pad_valid], dim=-1)
|
| 162 |
-
+ scores, idx = torch.topk(masked_padded, k=k, dim=-1, largest=True, sorted=True)
|
| 163 |
-
+ valid = torch.gather(valid_padded, -1, idx)
|
| 164 |
-
scores = torch.where(valid, scores, torch.zeros_like(scores))
|
| 165 |
-
idx = torch.where(valid, idx, torch.zeros_like(idx))
|
| 166 |
-
return scores, idx, valid
|
| 167 |
```
|
| 168 |
|
| 169 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
|
| 173 |
-
|
| 174 |
-
1. In `tokenizer_config.json`, set `"tokenizer_class": "XLMRobertaTokenizer"`.
|
| 175 |
-
2. In `tokenizer.json`, iterate over `added_tokens` sorted ascending by `id`; for each entry whose `id == len(model.vocab)`, append `[content, 0.0]` to `model.vocab`.
|
| 176 |
|
| 177 |
-
##
|
|
|
|
|
|
|
| 178 |
|
| 179 |
```bash
|
| 180 |
-
uv
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
|
| 185 |
-
|
| 186 |
-
.venv/bin/python build_bundle.py
|
| 187 |
|
| 188 |
-
|
| 189 |
-
|
| 190 |
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
license: other
|
| 3 |
license_name: apache-2.0-and-mit
|
| 4 |
license_link: https://huggingface.co/iris-hq/iris-names/blob/main/LICENSES.md
|
| 5 |
+
language:
|
| 6 |
+
- en
|
| 7 |
library_name: onnx
|
| 8 |
+
pipeline_tag: token-classification
|
| 9 |
+
base_model:
|
| 10 |
+
- fastino/gliner2.5-base-v1
|
| 11 |
+
- Xenova/DeBERTa-v3-base-mnli-fever-anli
|
| 12 |
+
base_model_relation: quantized
|
| 13 |
tags:
|
| 14 |
- onnx
|
| 15 |
+
- onnxruntime
|
| 16 |
- named-entity-recognition
|
| 17 |
+
- zero-shot
|
| 18 |
- natural-language-inference
|
| 19 |
+
- gliner2
|
| 20 |
+
- deberta-v3
|
| 21 |
+
- on-device
|
| 22 |
- iris
|
|
|
|
|
|
|
|
|
|
| 23 |
---
|
| 24 |
|
| 25 |
+
# iris-names
|
| 26 |
|
| 27 |
+
Two existing open models, converted or repackaged as ONNX files so an app can find names in text on the CPU, without sending the text anywhere:
|
| 28 |
|
| 29 |
+
| Folder | What it does | Upstream model | What was changed here |
|
| 30 |
+
|---|---|---|---|
|
| 31 |
+
| `gliner25/` | Finds spans of text for labels you choose | [fastino/gliner2.5-base-v1](https://huggingface.co/fastino/gliner2.5-base-v1), by Fastino AI (Apache-2.0) | Exported to ONNX in FP32, entity spans only; tokenizer files edited |
|
| 32 |
+
| `deberta-nli/` | Scores whether a sentence supports a statement | [MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli](https://huggingface.co/MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli), by Moritz Laurer (MIT), from the [Xenova ONNX conversion](https://huggingface.co/Xenova/DeBERTa-v3-base-mnli-fever-anli) (`model_q4f16.onnx`) | Weights moved to a separate data file; tokenizer files edited |
|
| 33 |
|
| 34 |
+
**Nothing was trained or fine-tuned here, and this repository did no quantisation.** The Q4F16 quantisation is Xenova's. `base_model_relation: quantized` is the Hub's nearest category for a conversion; the GLiNER files are FP32. Credit for the models belongs to their authors. This repository adds the export, the packaging, a rebuild script and an example.
|
| 35 |
|
| 36 |
+
[Iris](https://huggingface.co/iris-hq), a personal knowledge app, downloads these files at commit `d179d4a5a599fa8541dd0da17d0aea89096039fc`. The model files are the same at every commit of this repository so far.
|
| 37 |
|
| 38 |
+
## Use it
|
| 39 |
|
| 40 |
+
You need [uv](https://docs.astral.sh/uv/) and about 1 GB of free disk space.
|
| 41 |
|
| 42 |
+
```bash
|
| 43 |
+
uvx hf download iris-hq/iris-names --local-dir iris-names
|
| 44 |
+
uv run iris-names/examples/extract.py --model-dir iris-names --check "Ada Lovelace worked with Charles Babbage in London."
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
Or with pip, in a virtual environment:
|
| 48 |
+
|
| 49 |
+
```bash
|
| 50 |
+
pip install onnxruntime==1.23.2 tokenizers==0.22.2 "huggingface_hub>=1.0" "numpy>=2.0"
|
| 51 |
+
hf download iris-hq/iris-names --local-dir iris-names
|
| 52 |
+
python iris-names/examples/extract.py --model-dir iris-names --check "Ada Lovelace worked with Charles Babbage in London."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
```
|
| 54 |
|
| 55 |
+
Output, shortened (`score` is GLiNER's, `check` is DeBERTa's):
|
| 56 |
+
|
| 57 |
+
```json
|
| 58 |
+
[
|
| 59 |
+
{"text": "Ada Lovelace", "label": "person", "start": 0, "end": 12, "score": 0.995, "check": 0.9979},
|
| 60 |
+
{"text": "Charles Babbage", "label": "person", "start": 25, "end": 40, "score": 0.9727, "check": 0.9932},
|
| 61 |
+
{"text": "London", "label": "location", "start": 44, "end": 50, "score": 0.9972, "check": 0.9799}
|
| 62 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
```
|
| 64 |
|
| 65 |
+
Choose labels with `--labels person,city`. `--self-test` checks an installation. Once the files are downloaded, `--model-dir` makes no network request.
|
| 66 |
+
|
| 67 |
+
Load the tokenizers with `tokenizers.Tokenizer.from_file`, as the example does. `transformers.AutoTokenizer` (4.57.6) fails on `gliner25/`.
|
| 68 |
+
|
| 69 |
+
The example is a plain reference for the two models. It is not Iris's extraction pipeline, which adds its own filtering, so its results differ from Iris's.
|
| 70 |
+
|
| 71 |
+
## How it works
|
| 72 |
+
|
| 73 |
+
1. **Split.** Text becomes lowercased words with their positions, by GLiNER2's word pattern.
|
| 74 |
+
2. **Prompt.** The example reads one line at a time. Labels and words become one sequence of at most 512 tokens: `( [P] entities ( [E] label … ) ) [SEP_TEXT] words…`. There is no outer `[CLS]` or `[SEP]`. A longer line is read in windows that do not overlap.
|
| 75 |
+
3. **Encode.** `gliner25/encoder/model.onnx` gives a 768-wide vector per token. Each word uses its first token, and each label uses its `[E]` token.
|
| 76 |
+
4. **Find spans.** `gliner25/boundary_head.onnx` scores up to 192 candidate spans per label, plus a score that the label is absent.
|
| 77 |
+
5. **Decode.** Labels whose absent score is over 0.5 are dropped, spans under the threshold are dropped, and the best set of non-overlapping spans is kept for each label. Different labels may overlap.
|
| 78 |
+
6. **Check (optional).** `deberta-nli/model.onnx` reads `[CLS] premise [SEP] hypothesis [SEP]`, such as a sentence and "London is a location.", and gives the probability that the first supports the second. The wording in the example is illustrative.
|
| 79 |
+
|
| 80 |
+
| File | Inputs | Outputs |
|
| 81 |
+
|---|---|---|
|
| 82 |
+
| `gliner25/encoder/model.onnx` (opset 18) | `input_ids`, `attention_mask`: int64 `[batch, seq]` | `last_hidden_state`: float32 `[batch, seq, 768]` |
|
| 83 |
+
| `gliner25/boundary_head.onnx` (opset 18) | `token_states` float32 `[batch, words, 768]`, `text_mask` bool `[batch, words]`, `query_states` float32 `[batch, queries, 768]`, `query_mask` bool `[batch, queries]` | `indices` int64 `[batch, queries, 192, 2]` (first word, end word), `pair_logits` float32 and `valid_mask` bool `[batch, queries, 192]`, `null_logits` float32 `[batch, queries]` |
|
| 84 |
+
| `deberta-nli/model.onnx` (opset 12, and `com.microsoft` `MatMulNBits`, so it needs ONNX Runtime) | `input_ids`, `attention_mask`: int64 `[batch, seq]` | `logits`: float32 `[batch, 3]` (entailment, neutral, contradiction) |
|
| 85 |
+
|
| 86 |
+
**Tokenizer edits.** In both folders `tokenizer_class` is `XLMRobertaTokenizer`, and added tokens missing from the Unigram vocabulary are appended to it, so that [swift-transformers](https://github.com/huggingface/swift-transformers) 1.4.0 can load them. Token IDs do not change.
|
| 87 |
+
|
| 88 |
+
## Hardware
|
| 89 |
+
|
| 90 |
+
- **Disk:** 1,015,584,754 bytes (969 MiB) of model files.
|
| 91 |
+
- **CPU only.** No GPU was used or tested.
|
| 92 |
+
- **Measured** on one Apple M4 Pro with 64 GB, macOS 27.0.1, Python 3.13.11, 4 threads, with the example script, including start-up:
|
| 93 |
|
| 94 |
+
| Run | Time | Peak resident memory |
|
| 95 |
+
|---|---:|---:|
|
| 96 |
+
| One sentence, GLiNER only | 0.9 s | 837 MB |
|
| 97 |
+
| One sentence, with `--check` | 1.2 s | 834 MB |
|
| 98 |
+
| 60 lines, 480 words, with `--check` (180 names found) | 10 s | 834 MB |
|
| 99 |
|
| 100 |
+
Each is a single run, so treat them as a rough guide. Allow at least 1 GB of free memory. Linux, Windows, Intel Macs and phones are untested.
|
|
|
|
|
|
|
| 101 |
|
| 102 |
+
## Rebuild it
|
| 103 |
+
|
| 104 |
+
`scripts/build_bundle.py` downloads both upstream models at fixed commits (about 1 GB), rebuilds all 11 model files and compares them with `SHA256SUMS`.
|
| 105 |
|
| 106 |
```bash
|
| 107 |
+
uv run iris-names/scripts/build_bundle.py rebuilt
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
| Source | Commit |
|
| 111 |
+
|---|---|
|
| 112 |
+
| `fastino/gliner2.5-base-v1` | `07d99c0ba5d15cb3b24e0a236fa99bdd4ef87a5c` |
|
| 113 |
+
| `Xenova/DeBERTa-v3-base-mnli-fever-anli` | `72a1ce83a0144efaf828b3c3844320a61197a53d` |
|
| 114 |
+
|
| 115 |
+
On 2026-11-24 it rebuilt 11 of 11 files byte for byte on the Mac above. Another platform may give different bytes.
|
| 116 |
+
|
| 117 |
+
GLiNER's boundary head needs four small changes to `gliner2==2.1.0` before it exports. They are in the script, with the reasons. Package versions are pinned at the top of the script.
|
| 118 |
|
| 119 |
+
To check a download:
|
|
|
|
| 120 |
|
| 121 |
+
```bash
|
| 122 |
+
cd iris-names && shasum -a 256 -c SHA256SUMS
|
| 123 |
```
|
| 124 |
+
|
| 125 |
+
## Checks
|
| 126 |
+
|
| 127 |
+
Run on 2026-11-24 and 25 against commit `d179d4a5a599fa8541dd0da17d0aea89096039fc`:
|
| 128 |
+
|
| 129 |
+
- **Same spans as PyTorch.** On 27 short texts with 5 labels at threshold 0.5, the example found the same 113 spans as unmodified `gliner2==2.1.0`, with scores within 0.0001. All texts fitted in one 512-token window. Longer text can differ, because this example cuts it into windows.
|
| 130 |
+
- **Python.** The self-test passes on 3.11, 3.12 and 3.13.
|
| 131 |
+
|
| 132 |
+
These show that the conversion is faithful. They do not measure accuracy.
|
| 133 |
+
|
| 134 |
+
**No accuracy results are published.** Iris has measured its own pipeline, but those numbers include filtering that is not in this repository, so they would not describe these files. See the upstream cards for their authors' results, and test on your own text.
|
| 135 |
+
|
| 136 |
+
## Limits
|
| 137 |
+
|
| 138 |
+
- **English.** Both models are English. A Japanese sentence gave no names; other languages were not evaluated.
|
| 139 |
+
- **Common words are reported as names.** "He met the teacher at the store on Monday." gives teacher (person), store (location) and Monday (event). Expect to filter.
|
| 140 |
+
- **Wrong types and boundaries.** "My dog Biscuit likes the park." gives Biscuit (product). "The Soviet official praised The Beatles and the Newark Bay project." gives Beatles (location), while "The Beatles played in Hamburg." is read correctly.
|
| 141 |
+
- **Case is ignored** by the word splitter, so capital letters are no signal.
|
| 142 |
+
- **Crowded text loses names.** The GLiNER 2.5 head keeps the 32 best start points and 32 best end points per label and window. In a test with 48 names in one paragraph, PyTorch and this ONNX export both found 31. Pass short texts: sentences, lines or paragraphs.
|
| 143 |
+
- **Long lines** are cut into windows, and a name on a window edge can be missed. Every label shortens the window.
|
| 144 |
+
- **NLI scores are not calibrated probabilities**, depend on the wording of the hypothesis, and are no guarantee. Pairs over 512 tokens are not checked.
|
| 145 |
+
- **Entity spans only.** GLiNER 2.5's relations, classification and structured output were not exported.
|
| 146 |
+
- **Bias.** Upstream training data can carry social and geographic bias. Do not use this alone for decisions about people.
|
| 147 |
+
- Finding names in documents is processing personal data. Running locally does not change your duties under privacy law.
|
| 148 |
+
|
| 149 |
+
## Licences
|
| 150 |
+
|
| 151 |
+
`gliner25/` is Apache-2.0 and `deberta-nli/` is MIT. The second model was trained partly on ANLI, a dataset under CC BY-NC 4.0, so check your position before commercial use. The scripts here are Apache-2.0. Full notices are in [LICENSES.md](LICENSES.md).
|
| 152 |
+
|
| 153 |
+
## Cite
|
| 154 |
+
|
| 155 |
+
Please cite the original authors: [GLiNER2](https://arxiv.org/abs/2507.18546) (Zaratiana et al., 2025), and the [DeBERTa-v3 NLI model](https://huggingface.co/MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli), whose card gives its citation.
|
SHA256SUMS
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
4a5f8b1df58dba69e3588255c297e6ad1a70dc8b6312990959f3a3032c892738 deberta-nli/config.json
|
| 2 |
+
e0adb1b53ad0bdcf10cf18a6d98207d0403e4e7a87046f6ccf7aa871252d661d deberta-nli/model.onnx
|
| 3 |
+
835c91321cdf40a99df2f80ca12608efb15806f9a2950f10bc85718b48ef8cc3 deberta-nli/model.onnx_data
|
| 4 |
+
2910d9437f3dc5eebb5643cea037e9a9495b718a14e64a982155011c5ebe890c deberta-nli/tokenizer.json
|
| 5 |
+
156ad30e2990ca0bc0d3cff75f2651ae19e18b8d99e20c9aadd9096b9e7ca35e deberta-nli/tokenizer_config.json
|
| 6 |
+
354c425958b19200cf33fc1fba463f2c8aa42a170e759888af240be13978066d gliner25/boundary_head.onnx
|
| 7 |
+
d6b515c21ae2100c12267fb42a3f02c1e99ad87580366aebedb161efd74441c7 gliner25/config.json
|
| 8 |
+
4ed0793d74cc156be6a87f85e94372854fc452d34df23974f9979f23ae53a69b gliner25/encoder/model.onnx
|
| 9 |
+
e5561bfead6c1422513060d358f3818fa482752bbf446b84ed1c932a47ed2d01 gliner25/encoder/model.onnx_data
|
| 10 |
+
9b85c8cb45c6451b817afb2dad9e43eb23159f34b694007d8b2e78574c76ab04 gliner25/tokenizer.json
|
| 11 |
+
539533ecf03df44a0b873233c67f97c2b4e524834c6ea0a9975bf9d586b0e8db gliner25/tokenizer_config.json
|
examples/extract.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.11,<3.14"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "onnxruntime==1.23.2",
|
| 5 |
+
# "tokenizers==0.22.2",
|
| 6 |
+
# "huggingface_hub>=1.0",
|
| 7 |
+
# "numpy>=2.0",
|
| 8 |
+
# ]
|
| 9 |
+
# ///
|
| 10 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 11 |
+
"""Find names in text with the iris-names ONNX files, on the CPU, offline after download.
|
| 12 |
+
|
| 13 |
+
python extract.py "Ada Lovelace worked with Charles Babbage in London."
|
| 14 |
+
python extract.py --labels person,city --check "..."
|
| 15 |
+
python extract.py --self-test
|
| 16 |
+
|
| 17 |
+
This is a plain reference for the two models. It is not Iris's extraction pipeline,
|
| 18 |
+
which adds its own filtering, so results differ from Iris.
|
| 19 |
+
|
| 20 |
+
The word splitter and the overlap rule follow gliner2 2.1.0 (by Fastino AI,
|
| 21 |
+
Apache-2.0, https://github.com/fastino-ai/GLiNER2).
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
import argparse
|
| 25 |
+
import bisect
|
| 26 |
+
import json
|
| 27 |
+
import re
|
| 28 |
+
import sys
|
| 29 |
+
import unicodedata
|
| 30 |
+
from pathlib import Path
|
| 31 |
+
|
| 32 |
+
import numpy as np
|
| 33 |
+
import onnxruntime as ort
|
| 34 |
+
from tokenizers import Tokenizer
|
| 35 |
+
|
| 36 |
+
REPO = "iris-hq/iris-names"
|
| 37 |
+
REVISION = "d179d4a5a599fa8541dd0da17d0aea89096039fc"
|
| 38 |
+
MODEL_FILES = ["gliner25/*", "gliner25/encoder/*", "deberta-nli/*"]
|
| 39 |
+
LIMIT = 512 # tokens per model call
|
| 40 |
+
LABELS = ["person", "organization", "location", "product", "event"]
|
| 41 |
+
|
| 42 |
+
MARKS = "".join(chr(c) for c in range(sys.maxunicode + 1) if unicodedata.category(chr(c)).startswith("M"))
|
| 43 |
+
WORD = rf"[\w{MARKS}]"
|
| 44 |
+
SPLITTER = re.compile(
|
| 45 |
+
rf"""(?:https?://[^\s]+|www\.[^\s]+)
|
| 46 |
+
|[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{{2,}}
|
| 47 |
+
|@[a-z0-9_]+
|
| 48 |
+
|{WORD}+(?:[-_]{WORD}+)*
|
| 49 |
+
|\S""",
|
| 50 |
+
re.VERBOSE | re.IGNORECASE,
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def split_words(text):
|
| 55 |
+
"""Lowercased words with character offsets into the original text."""
|
| 56 |
+
return [(m.group().lower(), m.start(), m.end()) for m in SPLITTER.finditer(text)]
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def session(path):
|
| 60 |
+
options = ort.SessionOptions()
|
| 61 |
+
options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_BASIC
|
| 62 |
+
options.enable_cpu_mem_arena = False
|
| 63 |
+
options.enable_mem_pattern = False
|
| 64 |
+
options.add_session_config_entry("session.disable_prepacking", "1")
|
| 65 |
+
options.intra_op_num_threads = 4
|
| 66 |
+
options.log_severity_level = 3
|
| 67 |
+
return ort.InferenceSession(str(path), options, providers=["CPUExecutionProvider"])
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def sigmoid(x):
|
| 71 |
+
return 1 / (1 + np.exp(-np.clip(x, -60, 60)))
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def best_non_overlapping(spans):
|
| 75 |
+
"""The set of (start, end, score) spans with the highest total score and no overlap."""
|
| 76 |
+
spans = sorted({(s, e): p for s, e, p in sorted(spans, key=lambda x: x[2])}.items(), key=lambda x: (x[0][1], x[0][0]))
|
| 77 |
+
ends = [e for (_, e), _ in spans]
|
| 78 |
+
best = [(0.0, [])]
|
| 79 |
+
for i, ((s, e), p) in enumerate(spans):
|
| 80 |
+
total, chosen = best[bisect.bisect_right(ends, s, 0, i)]
|
| 81 |
+
take = (total + p, chosen + [(s, e, p)])
|
| 82 |
+
best.append(max(take, best[i], key=lambda b: (b[0], len(b[1]))))
|
| 83 |
+
return best[-1][1]
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class NameFinder:
|
| 87 |
+
"""GLiNER 2.5: text and labels in, scored spans out."""
|
| 88 |
+
|
| 89 |
+
def __init__(self, root):
|
| 90 |
+
root = Path(root) / "gliner25"
|
| 91 |
+
self.tokenizer = Tokenizer.from_file(str(root / "tokenizer.json"))
|
| 92 |
+
self.encoder = session(root / "encoder" / "model.onnx")
|
| 93 |
+
self.head = session(root / "boundary_head.onnx")
|
| 94 |
+
|
| 95 |
+
def ids(self, text):
|
| 96 |
+
return self.tokenizer.encode(text, add_special_tokens=False).ids
|
| 97 |
+
|
| 98 |
+
def find_words(self, words, labels, threshold=0.5):
|
| 99 |
+
"""Spans as (first word, end word, label index, score) for lowercased words."""
|
| 100 |
+
prefix = [i for t in ("(", "[P]", "entities", "(") for i in self.ids(t)]
|
| 101 |
+
queries = []
|
| 102 |
+
for label in labels:
|
| 103 |
+
queries.append(len(prefix)) # the [E] marker stands for the label
|
| 104 |
+
prefix += self.ids("[E]") + self.ids(label)
|
| 105 |
+
prefix += [i for t in (")", ")", "[SEP_TEXT]") for i in self.ids(t)]
|
| 106 |
+
budget = LIMIT - len(prefix)
|
| 107 |
+
if not labels or budget <= 0:
|
| 108 |
+
raise ValueError("give at least one label, and few enough to fit in 512 tokens")
|
| 109 |
+
|
| 110 |
+
spans, ids, routes, first = [], list(prefix), [], 0
|
| 111 |
+
for index, word in enumerate(words):
|
| 112 |
+
tokens = self.ids(word)
|
| 113 |
+
too_long = len(tokens) > budget # no span can include this word
|
| 114 |
+
if routes and (too_long or len(ids) + len(tokens) > LIMIT):
|
| 115 |
+
spans += self._window(ids, routes, queries, first, threshold)
|
| 116 |
+
ids, routes = list(prefix), []
|
| 117 |
+
if too_long:
|
| 118 |
+
continue
|
| 119 |
+
if not routes:
|
| 120 |
+
first = index
|
| 121 |
+
routes.append(len(ids)) # a word is represented by its first token
|
| 122 |
+
ids += tokens
|
| 123 |
+
if routes:
|
| 124 |
+
spans += self._window(ids, routes, queries, first, threshold)
|
| 125 |
+
return spans
|
| 126 |
+
|
| 127 |
+
def _window(self, ids, routes, queries, first, threshold):
|
| 128 |
+
states = self.encoder.run(None, {
|
| 129 |
+
"input_ids": np.array([ids], np.int64),
|
| 130 |
+
"attention_mask": np.ones((1, len(ids)), np.int64),
|
| 131 |
+
})[0][0]
|
| 132 |
+
last = len(ids) - 1
|
| 133 |
+
indices, pair_logits, valid, null_logits = self.head.run(None, {
|
| 134 |
+
"token_states": states[np.minimum(routes, last)][None],
|
| 135 |
+
"text_mask": np.ones((1, len(routes)), bool),
|
| 136 |
+
"query_states": states[queries][None],
|
| 137 |
+
"query_mask": np.ones((1, len(queries)), bool),
|
| 138 |
+
})
|
| 139 |
+
scores, null = sigmoid(pair_logits[0]), sigmoid(null_logits[0])
|
| 140 |
+
out = []
|
| 141 |
+
for label in range(len(queries)):
|
| 142 |
+
if null[label] > 0.5: # the model says this label is absent
|
| 143 |
+
continue
|
| 144 |
+
keep = np.flatnonzero(valid[0, label] & (scores[label] >= threshold))
|
| 145 |
+
spans = [(int(indices[0, label, c, 0]), int(indices[0, label, c, 1]), float(scores[label, c])) for c in keep]
|
| 146 |
+
out += [(first + s, first + e, label, p) for s, e, p in best_non_overlapping(spans)]
|
| 147 |
+
return out
|
| 148 |
+
|
| 149 |
+
def find(self, text, labels=LABELS, threshold=0.5):
|
| 150 |
+
"""Names in one short text, such as a sentence or paragraph."""
|
| 151 |
+
words = split_words(text)
|
| 152 |
+
found = []
|
| 153 |
+
for s, e, label, score in self.find_words([w for w, _, _ in words], labels, threshold):
|
| 154 |
+
start, end = words[s][1], words[e - 1][2]
|
| 155 |
+
found.append({"text": text[start:end], "label": labels[label], "start": start, "end": end,
|
| 156 |
+
"score": round(score, 4)})
|
| 157 |
+
return sorted(found, key=lambda f: (f["start"], f["end"]))
|
| 158 |
+
|
| 159 |
+
def find_lines(self, text, labels=LABELS, threshold=0.5):
|
| 160 |
+
"""Names in longer text, read a line at a time: the head proposes about 32 names per call."""
|
| 161 |
+
found, offset = [], 0
|
| 162 |
+
for line in text.splitlines(keepends=True):
|
| 163 |
+
for f in self.find(line, labels, threshold):
|
| 164 |
+
found.append({**f, "start": f["start"] + offset, "end": f["end"] + offset})
|
| 165 |
+
offset += len(line)
|
| 166 |
+
return found
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class Checker:
|
| 170 |
+
"""DeBERTa-v3 NLI: the probability that a premise entails a hypothesis."""
|
| 171 |
+
|
| 172 |
+
def __init__(self, root):
|
| 173 |
+
root = Path(root) / "deberta-nli"
|
| 174 |
+
self.tokenizer = Tokenizer.from_file(str(root / "tokenizer.json"))
|
| 175 |
+
self.model = session(root / "model.onnx")
|
| 176 |
+
id2label = json.loads((root / "config.json").read_text())["id2label"]
|
| 177 |
+
self.entailment = next(int(k) for k, v in id2label.items() if v.lower() == "entailment")
|
| 178 |
+
|
| 179 |
+
def entails(self, premise, hypothesis):
|
| 180 |
+
def ids(text):
|
| 181 |
+
return self.tokenizer.encode(text, add_special_tokens=False).ids
|
| 182 |
+
|
| 183 |
+
pair = ids("[CLS]") + ids(premise) + ids("[SEP]") + ids(hypothesis) + ids("[SEP]")
|
| 184 |
+
if len(pair) > LIMIT:
|
| 185 |
+
return None # too long to check
|
| 186 |
+
logits = self.model.run(None, {
|
| 187 |
+
"input_ids": np.array([pair], np.int64),
|
| 188 |
+
"attention_mask": np.ones((1, len(pair)), np.int64),
|
| 189 |
+
})[0][0].astype(np.float64)
|
| 190 |
+
weights = np.exp(logits - logits.max())
|
| 191 |
+
return float(weights[self.entailment] / weights.sum())
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def sentence_around(text, start, end):
|
| 195 |
+
breaks = [0] + [m.end() for m in re.finditer(r"[.!?]\s+|\n+", text)] + [len(text)]
|
| 196 |
+
left = max(b for b in breaks if b <= start)
|
| 197 |
+
right = min(b for b in breaks if b >= end)
|
| 198 |
+
return text[left:right].strip()
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def self_test(root):
|
| 202 |
+
assert best_non_overlapping([(0, 2, 0.9), (1, 3, 0.8), (2, 4, 0.7)]) == [(0, 2, 0.9), (2, 4, 0.7)]
|
| 203 |
+
assert best_non_overlapping([(0, 4, 0.9), (0, 2, 0.6), (2, 4, 0.6)]) == [(0, 2, 0.6), (2, 4, 0.6)]
|
| 204 |
+
finder = NameFinder(root)
|
| 205 |
+
found = {(f["text"], f["label"]) for f in finder.find("Ada Lovelace worked with Charles Babbage in London.")}
|
| 206 |
+
assert found == {("Ada Lovelace", "person"), ("Charles Babbage", "person"), ("London", "location")}, found
|
| 207 |
+
assert finder.find("") == [] == finder.find_lines("")
|
| 208 |
+
lines = "Alice left.\r\n\nShe met Bob.\n"
|
| 209 |
+
in_lines = finder.find_lines(lines)
|
| 210 |
+
assert all(lines[f["start"]:f["end"]] == f["text"] for f in in_lines), in_lines
|
| 211 |
+
assert {"Alice", "Bob"} <= {f["text"] for f in in_lines}, in_lines
|
| 212 |
+
checker = Checker(root)
|
| 213 |
+
yes = checker.entails("Kyoto is a city in Japan.", "Kyoto is a city.")
|
| 214 |
+
no = checker.entails("Kyoto is a city in Japan.", "Kyoto is a person.")
|
| 215 |
+
assert yes > 0.9 and no < 0.1, (yes, no)
|
| 216 |
+
assert checker.entails("word " * 600, "Kyoto is a city.") is None
|
| 217 |
+
print("self-test passed")
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def main():
|
| 221 |
+
parser = argparse.ArgumentParser(description="Find names in text with the iris-names ONNX files.")
|
| 222 |
+
parser.add_argument("text", nargs="?", help="text to read; leave out to read standard input")
|
| 223 |
+
parser.add_argument("--labels", default=",".join(LABELS), help="comma-separated, lowercase")
|
| 224 |
+
parser.add_argument("--threshold", type=float, default=0.5)
|
| 225 |
+
parser.add_argument("--check", action="store_true", help="also score each type with the NLI model")
|
| 226 |
+
parser.add_argument("--model-dir", help="a downloaded copy; default: download the pinned revision")
|
| 227 |
+
parser.add_argument("--self-test", action="store_true")
|
| 228 |
+
args = parser.parse_args()
|
| 229 |
+
|
| 230 |
+
root = args.model_dir
|
| 231 |
+
if not root:
|
| 232 |
+
from huggingface_hub import snapshot_download
|
| 233 |
+
root = snapshot_download(REPO, revision=REVISION, allow_patterns=MODEL_FILES)
|
| 234 |
+
if args.self_test:
|
| 235 |
+
return self_test(root)
|
| 236 |
+
|
| 237 |
+
text = args.text if args.text is not None else sys.stdin.read()
|
| 238 |
+
labels = [label.strip() for label in args.labels.split(",") if label.strip()]
|
| 239 |
+
found = NameFinder(root).find_lines(text, labels, args.threshold)
|
| 240 |
+
if args.check:
|
| 241 |
+
checker = Checker(root)
|
| 242 |
+
for f in found:
|
| 243 |
+
# Illustrative wording: choose and test your own for your labels.
|
| 244 |
+
score = checker.entails(sentence_around(text, f["start"], f["end"]), f"{f['text']} is a {f['label']}.")
|
| 245 |
+
f["check"] = None if score is None else round(score, 4)
|
| 246 |
+
print(json.dumps(found, indent=2, ensure_ascii=False))
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
if __name__ == "__main__":
|
| 250 |
+
main()
|
scripts/build_bundle.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = "==3.13.*"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "gliner2==2.1.0",
|
| 5 |
+
# "torch==2.15.0",
|
| 6 |
+
# "transformers==4.57.6",
|
| 7 |
+
# "tokenizers==0.22.2",
|
| 8 |
+
# "onnx==1.23.2",
|
| 9 |
+
# "onnxscript==0.7.2",
|
| 10 |
+
# "onnxruntime==1.23.2",
|
| 11 |
+
# "huggingface_hub==0.36.2",
|
| 12 |
+
# ]
|
| 13 |
+
# ///
|
| 14 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 15 |
+
"""Rebuild the iris-names ONNX files from the pinned upstream models.
|
| 16 |
+
|
| 17 |
+
python build_bundle.py OUT_DIR
|
| 18 |
+
|
| 19 |
+
Downloads fastino/gliner2.5-base-v1 and the Q4F16 ONNX file of
|
| 20 |
+
Xenova/DeBERTa-v3-base-mnli-fever-anli at fixed commits, converts and repackages
|
| 21 |
+
them, then compares every file with ../SHA256SUMS. Nothing is trained, and no
|
| 22 |
+
weight is changed or quantised here. OUT_DIR must not exist.
|
| 23 |
+
|
| 24 |
+
The functions prefixed onnx_ are modified from gliner2 2.1.0 (by Fastino AI,
|
| 25 |
+
Apache-2.0, https://github.com/fastino-ai/GLiNER2). The changes let the boundary
|
| 26 |
+
head export to ONNX and run on sentences of any length:
|
| 27 |
+
1. shift_left_with_bos / shift_right_with_eos: cat/where instead of in-place writes.
|
| 28 |
+
2. BoundaryAttentionBlock: the diagonal mask compares positions, because ONNX
|
| 29 |
+
Runtime has no boolean EyeLike.
|
| 30 |
+
3. select_top_boundaries: right-pads to k before topk, so k is constant.
|
| 31 |
+
4. aten::sort and aten::argsort with stable=True get a TopK symbolic.
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
import hashlib
|
| 35 |
+
import json
|
| 36 |
+
import shutil
|
| 37 |
+
import sys
|
| 38 |
+
import tempfile
|
| 39 |
+
from pathlib import Path
|
| 40 |
+
|
| 41 |
+
import gliner2.models.boundary.encoding as b_enc
|
| 42 |
+
import gliner2.models.boundary.pool as b_pool
|
| 43 |
+
import gliner2.models.boundary.proposal as b_prop
|
| 44 |
+
import onnx
|
| 45 |
+
import torch
|
| 46 |
+
from gliner2 import AutoExtractor
|
| 47 |
+
from gliner2.models.boundary.constants import MASK_LOGIT
|
| 48 |
+
from huggingface_hub import snapshot_download
|
| 49 |
+
from torch.onnx import register_custom_op_symbolic
|
| 50 |
+
from torch.onnx._internal.torchscript_exporter import symbolic_helper
|
| 51 |
+
|
| 52 |
+
GLINER = ("fastino/gliner2.5-base-v1", "07d99c0ba5d15cb3b24e0a236fa99bdd4ef87a5c")
|
| 53 |
+
NLI = ("Xenova/DeBERTa-v3-base-mnli-fever-anli", "72a1ce83a0144efaf828b3c3844320a61197a53d")
|
| 54 |
+
TOKENIZER_FILES = ["config.json", "tokenizer.json", "tokenizer_config.json"]
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def sort_symbolic(g, self, *args):
|
| 58 |
+
if len(args) == 3: # (stable, dim, descending)
|
| 59 |
+
args = args[1:]
|
| 60 |
+
dim = symbolic_helper._parse_arg(args[0], "i")
|
| 61 |
+
descending = symbolic_helper._parse_arg(args[1], "i")
|
| 62 |
+
return symbolic_helper._sort_helper(g, self, dim, descending=descending, out=None)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def argsort_symbolic(g, self, *args):
|
| 66 |
+
return sort_symbolic(g, self, *args)[1]
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def onnx_shift_left_with_bos(text_states, bos_state):
|
| 70 |
+
b, l, h = text_states.shape
|
| 71 |
+
bos = bos_state.to(text_states.dtype).view(1, 1, h).expand(b, 1, h)
|
| 72 |
+
return torch.cat([bos, text_states], dim=1)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def onnx_shift_right_with_eos(text_states, text_lengths, eos_state):
|
| 76 |
+
b, l, h = text_states.shape
|
| 77 |
+
eos = eos_state.to(text_states.dtype).view(1, 1, h).expand(b, 1, h)
|
| 78 |
+
padded = torch.cat([text_states, eos], dim=1)
|
| 79 |
+
idx = torch.arange(l + 1, device=text_states.device).unsqueeze(0)
|
| 80 |
+
is_eos = idx == text_lengths.clamp(max=l).unsqueeze(1)
|
| 81 |
+
return torch.where(is_eos.unsqueeze(-1), eos_state.to(text_states.dtype).view(1, 1, h), padded)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def onnx_attention_forward(self, states, mask):
|
| 85 |
+
b, n, d = states.shape
|
| 86 |
+
qkv = self.qkv_projection(self.norm(states)).view(b, n, 3, self.num_heads, self.head_dim)
|
| 87 |
+
query, key, value = qkv.unbind(2)
|
| 88 |
+
query = query.transpose(1, 2)
|
| 89 |
+
key = key.transpose(1, 2)
|
| 90 |
+
value = value.transpose(1, 2)
|
| 91 |
+
allowed = mask.view(b, 1, 1, n).expand(b, 1, n, n)
|
| 92 |
+
positions = torch.arange(n, device=states.device)
|
| 93 |
+
if self.window > 0:
|
| 94 |
+
local = (positions.view(n, 1) - positions.view(1, n)).abs() <= self.window
|
| 95 |
+
allowed = allowed & local.view(1, 1, n, n)
|
| 96 |
+
diagonal = positions.view(n, 1) == positions.view(1, n)
|
| 97 |
+
allowed = allowed | diagonal.view(1, 1, n, n)
|
| 98 |
+
attended = torch.nn.functional.scaled_dot_product_attention(
|
| 99 |
+
query, key, value, attn_mask=allowed, dropout_p=0.0
|
| 100 |
+
)
|
| 101 |
+
attended = attended.transpose(1, 2).reshape(b, n, d)
|
| 102 |
+
update = self.output_projection(attended)
|
| 103 |
+
return (states + update) * mask.unsqueeze(-1).to(states.dtype)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def onnx_select_top_boundaries(logits, valid_mask, k):
|
| 107 |
+
b, q, n = logits.shape
|
| 108 |
+
floor = MASK_LOGIT
|
| 109 |
+
masked = logits.masked_fill(~valid_mask, floor)
|
| 110 |
+
pad_logits = masked.new_full((b, q, k), floor)
|
| 111 |
+
pad_valid = valid_mask.new_zeros((b, q, k))
|
| 112 |
+
masked_padded = torch.cat([masked, pad_logits], dim=-1)
|
| 113 |
+
valid_padded = torch.cat([valid_mask, pad_valid], dim=-1)
|
| 114 |
+
scores, idx = torch.topk(masked_padded, k=k, dim=-1, largest=True, sorted=True)
|
| 115 |
+
valid = torch.gather(valid_padded, -1, idx)
|
| 116 |
+
scores = torch.where(valid, scores, torch.zeros_like(scores))
|
| 117 |
+
idx = torch.where(valid, idx, torch.zeros_like(idx))
|
| 118 |
+
return scores, idx, valid
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class Encoder(torch.nn.Module):
|
| 122 |
+
def __init__(self, enc):
|
| 123 |
+
super().__init__()
|
| 124 |
+
self.enc = enc
|
| 125 |
+
|
| 126 |
+
def forward(self, input_ids, attention_mask):
|
| 127 |
+
return self.enc(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class BoundaryHead(torch.nn.Module):
|
| 131 |
+
def __init__(self, bh):
|
| 132 |
+
super().__init__()
|
| 133 |
+
self.bh = bh
|
| 134 |
+
self.bh.candidate_encoder = None # entity spans only: no relations or attributes
|
| 135 |
+
|
| 136 |
+
def forward(self, token_states, text_mask, query_states, query_mask):
|
| 137 |
+
out = self.bh(token_states, text_mask, query_states, query_mask, return_candidates=True)
|
| 138 |
+
c = out.candidates
|
| 139 |
+
return c.indices, c.pair_logits, c.valid_mask, out.null_logits
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def rewrite_tokenizer(src: Path, dst: Path):
|
| 143 |
+
"""Make the tokenizer load in swift-transformers 1.4.0. Token IDs do not change."""
|
| 144 |
+
shutil.copyfile(src / "config.json", dst / "config.json")
|
| 145 |
+
config = json.loads((src / "tokenizer_config.json").read_text(encoding="utf-8"))
|
| 146 |
+
config["tokenizer_class"] = "XLMRobertaTokenizer"
|
| 147 |
+
(dst / "tokenizer_config.json").write_text(json.dumps(config, ensure_ascii=False), encoding="utf-8")
|
| 148 |
+
tokenizer = json.loads((src / "tokenizer.json").read_text(encoding="utf-8"))
|
| 149 |
+
vocab = tokenizer["model"]["vocab"]
|
| 150 |
+
for token in sorted(tokenizer["added_tokens"], key=lambda t: t["id"]):
|
| 151 |
+
if token["id"] < len(vocab):
|
| 152 |
+
if vocab[token["id"]][0] != token["content"]:
|
| 153 |
+
raise SystemExit(f"unexpected added token {token}")
|
| 154 |
+
elif token["id"] == len(vocab):
|
| 155 |
+
vocab.append([token["content"], 0.0])
|
| 156 |
+
else:
|
| 157 |
+
raise SystemExit(f"gap before added token {token}")
|
| 158 |
+
(dst / "tokenizer.json").write_text(json.dumps(tokenizer, ensure_ascii=False), encoding="utf-8")
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def save_external(src: Path, out_dir: Path):
|
| 162 |
+
onnx.save_model(
|
| 163 |
+
onnx.load(str(src)), str(out_dir / "model.onnx"), save_as_external_data=True,
|
| 164 |
+
all_tensors_to_one_file=True, location="model.onnx_data", size_threshold=1024,
|
| 165 |
+
convert_attribute=False,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def export_gliner(src: Path, out: Path, tmp: Path):
|
| 170 |
+
register_custom_op_symbolic("aten::sort", sort_symbolic, 11)
|
| 171 |
+
register_custom_op_symbolic("aten::argsort", argsort_symbolic, 11)
|
| 172 |
+
b_enc.shift_left_with_bos = onnx_shift_left_with_bos
|
| 173 |
+
b_enc.shift_right_with_eos = onnx_shift_right_with_eos
|
| 174 |
+
b_enc.BoundaryAttentionBlock.forward = onnx_attention_forward
|
| 175 |
+
b_prop.select_top_boundaries = onnx_select_top_boundaries
|
| 176 |
+
b_pool.select_top_boundaries = onnx_select_top_boundaries
|
| 177 |
+
|
| 178 |
+
torch.manual_seed(0)
|
| 179 |
+
model = AutoExtractor.from_pretrained(str(src))
|
| 180 |
+
model.eval()
|
| 181 |
+
|
| 182 |
+
torch.manual_seed(0)
|
| 183 |
+
batch, words, queries, hidden = 2, 40, 23, 768 # example input: batch, words and queries stay dynamic
|
| 184 |
+
torch.onnx.export(
|
| 185 |
+
BoundaryHead(model.boundary_head).eval(),
|
| 186 |
+
(torch.randn(batch, words, hidden), torch.ones(batch, words, dtype=torch.bool),
|
| 187 |
+
torch.randn(batch, queries, hidden), torch.ones(batch, queries, dtype=torch.bool)),
|
| 188 |
+
str(out / "boundary_head.onnx"),
|
| 189 |
+
input_names=["token_states", "text_mask", "query_states", "query_mask"],
|
| 190 |
+
output_names=["indices", "pair_logits", "valid_mask", "null_logits"],
|
| 191 |
+
dynamic_axes={
|
| 192 |
+
"token_states": {0: "batch", 1: "words"},
|
| 193 |
+
"text_mask": {0: "batch", 1: "words"},
|
| 194 |
+
"query_states": {0: "batch", 1: "queries"},
|
| 195 |
+
"query_mask": {0: "batch", 1: "queries"},
|
| 196 |
+
"indices": {0: "batch", 1: "queries", 2: "candidates"},
|
| 197 |
+
"pair_logits": {0: "batch", 1: "queries", 2: "candidates"},
|
| 198 |
+
"valid_mask": {0: "batch", 1: "queries", 2: "candidates"},
|
| 199 |
+
"null_logits": {0: "batch", 1: "queries"},
|
| 200 |
+
},
|
| 201 |
+
opset_version=18, dynamo=False,
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
torch.manual_seed(0)
|
| 205 |
+
torch.onnx.export(
|
| 206 |
+
Encoder(model.encoder.float()).eval(),
|
| 207 |
+
(torch.randint(1, 1000, (2, 32), dtype=torch.long), torch.ones((2, 32), dtype=torch.long)),
|
| 208 |
+
str(tmp / "encoder.onnx"),
|
| 209 |
+
input_names=["input_ids", "attention_mask"],
|
| 210 |
+
output_names=["last_hidden_state"],
|
| 211 |
+
dynamic_axes={
|
| 212 |
+
"input_ids": {0: "batch", 1: "seq"},
|
| 213 |
+
"attention_mask": {0: "batch", 1: "seq"},
|
| 214 |
+
"last_hidden_state": {0: "batch", 1: "seq"},
|
| 215 |
+
},
|
| 216 |
+
opset_version=18, dynamo=False,
|
| 217 |
+
)
|
| 218 |
+
(out / "encoder").mkdir()
|
| 219 |
+
save_external(tmp / "encoder.onnx", out / "encoder")
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def sha256(path: Path) -> str:
|
| 223 |
+
with path.open("rb") as f:
|
| 224 |
+
return hashlib.file_digest(f, "sha256").hexdigest()
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def main() -> int:
|
| 228 |
+
if len(sys.argv) != 2:
|
| 229 |
+
raise SystemExit("usage: python build_bundle.py OUT_DIR")
|
| 230 |
+
out = Path(sys.argv[1])
|
| 231 |
+
sums = (Path(__file__).resolve().parent.parent / "SHA256SUMS").read_text().splitlines()
|
| 232 |
+
(out / "gliner25").mkdir(parents=True)
|
| 233 |
+
(out / "deberta-nli").mkdir()
|
| 234 |
+
gliner = Path(snapshot_download(GLINER[0], revision=GLINER[1],
|
| 235 |
+
allow_patterns=TOKENIZER_FILES + ["encoder_config/config.json", "model.safetensors"]))
|
| 236 |
+
nli = Path(snapshot_download(NLI[0], revision=NLI[1], allow_patterns=TOKENIZER_FILES + ["onnx/model_q4f16.onnx"]))
|
| 237 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 238 |
+
export_gliner(gliner, out / "gliner25", Path(tmp))
|
| 239 |
+
save_external(nli / "onnx" / "model_q4f16.onnx", out / "deberta-nli")
|
| 240 |
+
rewrite_tokenizer(gliner, out / "gliner25")
|
| 241 |
+
rewrite_tokenizer(nli, out / "deberta-nli")
|
| 242 |
+
|
| 243 |
+
different = 0
|
| 244 |
+
for line in sums:
|
| 245 |
+
want, name = line.split(" ", 1)
|
| 246 |
+
same = sha256(out / name) == want
|
| 247 |
+
different += not same
|
| 248 |
+
print("same " if same else "DIFFERENT", name)
|
| 249 |
+
print(f"{len(sums) - different} of {len(sums)} files are byte-identical to the published ones")
|
| 250 |
+
return 1 if different else 0
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
if __name__ == "__main__":
|
| 254 |
+
sys.exit(main())
|