Token Classification
ONNX
GLiNER2
English
onnxruntime
named-entity-recognition
zero-shot
natural-language-inference
deberta-v3
on-device
iris
Run this model with HF Jobs
Run iris-hq/iris-names on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/iris-hq/iris-names. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/iris-hq/iris-names on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
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 filesFiles changed (6)
- LICENSE-APACHE-2.0.txtAdded+202
- LICENSES.md+23-32
- README.md+124-159
- SHA256SUMSAdded+11
- examples/extract.pyAdded+250
- scripts/build_bundle.pyAdded+254
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.112334567895611121314151678910111819202122232425121327141516171829192031323334353621222324254142432627282913 unmodified lines4344454647484950515253# Third-Party Model Licenses (`iris-names-1`)# Licences and notices
## 1. GLiNER 2.5 Base (`gliner25/`)This repository redistributes two third-party models in converted form. Their licences apply to their files. Nothing here was trained.
- **Upstream Repository:** [`fastino/gliner2.5-base-v1`](https://huggingface.co/fastino/gliner2.5-base-v1)- **Pinned Revision:** `07d99c0ba5d15cb3b24e0a236fa99bdd4ef87a5c`- **Author:** Fastino AI (`fastino-ai/GLiNER2`)- **Base Encoder:** [`microsoft/deberta-v3-base`](https://huggingface.co/microsoft/deberta-v3-base) (MIT License)- **License:** Apache License 2.0## `gliner25/`: GLiNER 2.5 Base
```textCopyright 2025-2026 Fastino AI
Licensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at- **Source:** [fastino/gliner2.5-base-v1](https://huggingface.co/fastino/gliner2.5-base-v1), commit `07d99c0ba5d15cb3b24e0a236fa99bdd4ef87a5c`, by Fastino AI.- **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.- **Encoder it builds on:** [microsoft/deberta-v3-base](https://huggingface.co/microsoft/deberta-v3-base), by Microsoft (MIT, notice below).- **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.
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.```## `deberta-nli/`: DeBERTa-v3 Base MNLI-FEVER-ANLI
---- **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.- **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.- **Base model:** [microsoft/deberta-v3-base](https://huggingface.co/microsoft/deberta-v3-base), by Microsoft (MIT, notice below).- **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.
## 2. DeBERTa-v3 Base MNLI-FEVER-ANLI (`deberta-nli/`)**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.
- **Upstream ONNX Port:** [`Xenova/DeBERTa-v3-base-mnli-fever-anli`](https://huggingface.co/Xenova/DeBERTa-v3-base-mnli-fever-anli) (`onnx/model_q4f16.onnx`, repackaged with external data)- **Pinned Revision (Xenova):** `72a1ce83a0144efaf828b3c3844320a61197a53d`- **Upstream PyTorch Checkpoint:** [`MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli`](https://huggingface.co/MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli) (revision `ef67fd0301dd3eebc5eed7fd3fae0ef2fc0bbd0a`)- **Author:** Moritz Laurer (ONNX conversion and Q4F16 quantization by Joshua Lochner / Xenova; base model `microsoft/deberta-v3-base` by Microsoft)- **Model License:** MIT License- **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).### MIT notice (Microsoft DeBERTa)
```textMIT License
Copyright (c) Microsoft Corporation (DeBERTa-v3 base architecture and weights)Copyright (c) Moritz Laurer (MNLI/FEVER/ANLI fine-tuned checkpoint)Copyright (c) Joshua Lochner / Xenova (ONNX export and Q4F16 quantization)Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to deal13 unmodified linesOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.```
## `scripts/` and `examples/`
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.
## Correction
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.1 unmodified line234567891011121314151617181920212211121323241625261827282021222930313233243435263637283839304041323334353637383940414243444546474243444546474849505152535450515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651665556575859606162636416965666768697071727374757677787980818283848586878889909192931719495969798991731741751001011771021031041051061801811821831071081091101111121131141151161171181851861191201881891211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551 unmodified linelicense: otherlicense_name: apache-2.0-and-mitlicense_link: https://huggingface.co/iris-hq/iris-names/blob/main/LICENSES.mdlanguage:- enlibrary_name: onnxpipeline_tag: token-classificationbase_model:- fastino/gliner2.5-base-v1- Xenova/DeBERTa-v3-base-mnli-fever-anlibase_model_relation: quantizedtags:- onnx- onnxruntime- named-entity-recognition- zero-shot- natural-language-inference- gliner2- deberta-v3- on-device- irisbase_model:- fastino/gliner2.5-base-v1- MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli---
# Iris name models# iris-names
The local name models Iris downloads when a person chooses Download in Settings (Names only). Iris pins one commit of this repository and checks every file's size and SHA-256 before use; no note text is ever sent here.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:
- `gliner25/`: GLiNER 2.5 Base (fastino/gliner2.5-base-v1 @ 07d99c0ba5d15cb3b24e0a236fa99bdd4ef87a5c), entity span path only, exported to ONNX (FP32 encoder with external data, FP32 boundary head). Apache-2.0.- `deberta-nli/`: DeBERTa-v3 Base MNLI/FEVER/ANLI (MoritzLaurer, via Xenova @ 72a1ce83a0144efaf828b3c3844320a61197a53d), Q4F16 repackaged with external data. MIT; trained partly on ANLI (CC BY-NC 4.0).- Tokenizers are rewritten for swift-transformers 1.4.0 (XLMRobertaTokenizer class, added tokens appended to the Unigram vocab); token IDs are unchanged.| Folder | What it does | Upstream model | What was changed here ||---|---|---|---|| `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 || `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 |
See LICENSES.md for full notices. The export and repackaging recipe follows.**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.
# `iris-names-1` Model Bundle Recipe[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.
This directory contains the reproducible offline export, repackaging, and tokenizer-rewrite recipe for the `iris-names-1` ONNX bundle used by Iris's native `Names only` extraction (`namesFind` + `namesCheck` in `iris-voice-helper`).## Use it
## Bundle LayoutYou need [uv](https://docs.astral.sh/uv/) and about 1 GB of free disk space.
```textiris-names-1/ gliner25/ encoder/ model.onnx model.onnx_data boundary_head.onnx config.json tokenizer.json tokenizer_config.json deberta-nli/ model.onnx model.onnx_data config.json tokenizer.json tokenizer_config.json```bashuvx hf download iris-hq/iris-names --local-dir iris-namesuv run iris-names/examples/extract.py --model-dir iris-names --check "Ada Lovelace worked with Charles Babbage in London."```
Or with pip, in a virtual environment:
```bashpip install onnxruntime==1.23.2 tokenizers==0.22.2 "huggingface_hub>=1.0" "numpy>=2.0"hf download iris-hq/iris-names --local-dir iris-namespython iris-names/examples/extract.py --model-dir iris-names --check "Ada Lovelace worked with Charles Babbage in London."```
## Pinned Upstream Sources & Versions
- **Stage 1 (GLiNER 2.5 Base):** - Hugging Face repository: `fastino/gliner2.5-base-v1` - Pinned commit SHA: `07d99c0ba5d15cb3b24e0a236fa99bdd4ef87a5c` - License: Apache-2.0- **Stage 2 (DeBERTa-v3 Base MNLI/FEVER/ANLI Q4F16):** - Hugging Face repository: `Xenova/DeBERTa-v3-base-mnli-fever-anli` (`onnx/model_q4f16.onnx` + tokenizer/config files) - Pinned commit SHA: `72a1ce83a0144efaf828b3c3844320a61197a53d` - Upstream FP32 source: `MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli` (commit `ef67fd0301dd3eebc5eed7fd3fae0ef2fc0bbd0a`) - License: MIT (note: ANLI training dataset is CC BY-NC 4.0; see `LICENSES.md`)- **Python Export & Reference Environment:** - Python `3.13.11` - `gliner2==2.1.0` - `torch==2.15.0` (CPU) - `transformers==4.57.6` - `tokenizers==0.22.2` - `onnx==1.23.2`, `onnxscript==0.7.2` - `onnxruntime==1.23.2`
## Three Required Export Patches Against `gliner2==2.1.0`
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:
1. **TorchScript ONNX symbolic for `aten::sort` and `aten::argsort` with `stable=True`:** 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)`).2. **Replace `torch.eye(n, dtype=torch.bool)` and in-place slice mutations in `gliner2/models/boundary/encoding.py`:** `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.3. **Right-pad boundary logits to `k=32` in `select_top_boundaries` (`gliner2/models/boundary/proposal.py`):** 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.
### Unified Diff Against `gliner2==2.1.0`
```diff--- a/gliner2/models/boundary/encoding.py+++ b/gliner2/models/boundary/encoding.py@@ -38,9 +38,7 @@ Returns: [B, L + 1, H] """ b, l, h = text_states.shape- out = torch.empty(b, l + 1, h, dtype=text_states.dtype, device=text_states.device)- out[:, 0] = bos_state.to(text_states.dtype)- out[:, 1:] = text_states- return out+ bos = bos_state.to(text_states.dtype).view(1, 1, h).expand(b, 1, h)+ return torch.cat([bos, text_states], dim=1) def shift_right_with_eos(@@ -59,13 +57,11 @@ Returns: [B, L + 1, H] """ b, l, h = text_states.shape- out = torch.empty(b, l + 1, h, dtype=text_states.dtype, device=text_states.device)- out[:, :l] = text_states- out[:, l] = eos_state.to(text_states.dtype)- # Place EOS at each sample's own final boundary index n_b.- eos = eos_state.to(text_states.dtype).view(1, h).expand(b, h)- out[torch.arange(b, device=text_states.device), text_lengths.clamp(max=l)] = eos- return out+ eos = eos_state.to(text_states.dtype).view(1, 1, h).expand(b, 1, h)+ padded = torch.cat([text_states, eos], dim=1)+ idx = torch.arange(l + 1, device=text_states.device).unsqueeze(0)+ is_eos = idx == text_lengths.clamp(max=l).unsqueeze(1)+ return torch.where(is_eos.unsqueeze(-1), eos_state.to(text_states.dtype).view(1, 1, h), padded) class ResidualSwiGLU(nn.Module):@@ -118,17 +114,20 @@ qkv = self.qkv_projection(self.norm(states)).view( b, n, 3, self.num_heads, self.head_dim )- query, key, value = qkv.permute(2, 0, 3, 1, 4)+ query, key, value = qkv.unbind(2)+ query = query.transpose(1, 2)+ key = key.transpose(1, 2)+ value = value.transpose(1, 2) allowed = mask.view(b, 1, 1, n).expand(b, 1, n, n)+ positions = torch.arange(n, device=states.device) if self.window > 0:- positions = torch.arange(n, device=states.device) local = ( positions.view(n, 1) - positions.view(1, n) ).abs() <= self.window allowed = allowed & local.view(1, 1, n, n) # Padding query rows still need one legal key to avoid NaNs.- diagonal = torch.eye(n, dtype=torch.bool, device=states.device)+ diagonal = positions.view(n, 1) == positions.view(1, n) allowed = allowed | diagonal.view(1, 1, n, n) attended = F.scaled_dot_product_attention( query,--- a/gliner2/models/boundary/proposal.py+++ b/gliner2/models/boundary/proposal.py@@ -93,13 +93,14 @@ Returns: scores [B, Q, k], indices [B, Q, k], valid [B, Q, k]. """- n = logits.shape[-1]- k = min(k, n)+ b, q, n = logits.shape floor = MASK_LOGIT masked = logits.masked_fill(~valid_mask, floor)- scores, idx = torch.sort(masked, dim=-1, descending=True, stable=True)- scores = scores[..., :k]- idx = idx[..., :k]- valid = torch.gather(valid_mask, -1, idx)+ pad_logits = masked.new_full((b, q, k), floor)+ pad_valid = valid_mask.new_zeros((b, q, k))+ masked_padded = torch.cat([masked, pad_logits], dim=-1)+ valid_padded = torch.cat([valid_mask, pad_valid], dim=-1)+ scores, idx = torch.topk(masked_padded, k=k, dim=-1, largest=True, sorted=True)+ valid = torch.gather(valid_padded, -1, idx) scores = torch.where(valid, scores, torch.zeros_like(scores)) idx = torch.where(valid, idx, torch.zeros_like(idx)) return scores, idx, validOutput, shortened (`score` is GLiNER's, `check` is DeBERTa's):
```json[ {"text": "Ada Lovelace", "label": "person", "start": 0, "end": 12, "score": 0.995, "check": 0.9979}, {"text": "Charles Babbage", "label": "person", "start": 25, "end": 40, "score": 0.9727, "check": 0.9932}, {"text": "London", "label": "location", "start": 44, "end": 50, "score": 0.9972, "check": 0.9799}]```
## Tokenizer Rewrite for `swift-transformers` 1.4.0 CompatibilityChoose labels with `--labels person,city`. `--self-test` checks an installation. Once the files are downloaded, `--model-dir` makes no network request.
Load the tokenizers with `tokenizers.Tokenizer.from_file`, as the example does. `transformers.AutoTokenizer` (4.57.6) fails on `gliner25/`.
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.
## How it works
1. **Split.** Text becomes lowercased words with their positions, by GLiNER2's word pattern.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.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.4. **Find spans.** `gliner25/boundary_head.onnx` scores up to 192 candidate spans per label, plus a score that the label is absent.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.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.
| File | Inputs | Outputs ||---|---|---|| `gliner25/encoder/model.onnx` (opset 18) | `input_ids`, `attention_mask`: int64 `[batch, seq]` | `last_hidden_state`: float32 `[batch, seq, 768]` || `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]` || `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) |
**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.
## Hardware
- **Disk:** 1,015,584,754 bytes (969 MiB) of model files.- **CPU only.** No GPU was used or tested.- **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:
Iris's native helper uses `swift-transformers` `Tokenizers` `1.4.0` (`AutoTokenizer.from(modelFolder:)`). Stock `DebertaV2Tokenizer` configs are rejected by `swift-transformers` `1.4.0`, and class-only rewrites map added tokens (`[P]`, `[E]`, `[SEP_TEXT]`, `[MASK]`) to `<unk>` (`3`) because `UnigramTokenizer` builds its token-to-ID map solely from `model.vocab`.| Run | Time | Peak resident memory ||---|---:|---:|| One sentence, GLiNER only | 0.9 s | 837 MB || One sentence, with `--check` | 1.2 s | 834 MB || 60 lines, 480 words, with `--check` (180 names found) | 10 s | 834 MB |
For both `gliner25/` and `deberta-nli/`, `build_bundle.py` applies the proven `xlm-vocab` rewrite:1. In `tokenizer_config.json`, set `"tokenizer_class": "XLMRobertaTokenizer"`.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`.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.
## Reproducing the Bundle and Fixtures## Rebuild it
`scripts/build_bundle.py` downloads both upstream models at fixed commits (about 1 GB), rebuilds all 11 model files and compares them with `SHA256SUMS`.
```bashuv venv .venvuv pip install --python .venv/bin/python \ "gliner2==2.1.0" "transformers==4.57.6" "tokenizers==0.22.2" \ "torch==2.15.0" "onnx==1.23.2" "onnxscript==0.7.2" "onnxruntime==1.23.2"uv run iris-names/scripts/build_bundle.py rebuilt```
| Source | Commit ||---|---|| `fastino/gliner2.5-base-v1` | `07d99c0ba5d15cb3b24e0a236fa99bdd4ef87a5c` || `Xenova/DeBERTa-v3-base-mnli-fever-anli` | `72a1ce83a0144efaf828b3c3844320a61197a53d` |
On 2026-11-24 it rebuilt 11 of 11 files byte for byte on the Mac above. Another platform may give different bytes.
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.
# 1. Build and verify deterministic bundle + manifest.json.venv/bin/python build_bundle.pyTo check a download:
# 2. Generate and verify deterministic golden fixtures in tools/voice/fixtures/names/.venv/bin/python reference.py```bashcd iris-names && shasum -a 256 -c SHA256SUMS```
## Checks
Run on 2026-11-24 and 25 against commit `d179d4a5a599fa8541dd0da17d0aea89096039fc`:
- **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.- **Python.** The self-test passes on 3.11, 3.12 and 3.13.
These show that the conversion is faithful. They do not measure accuracy.
**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.
## Limits
- **English.** Both models are English. A Japanese sentence gave no names; other languages were not evaluated.- **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.- **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.- **Case is ignored** by the word splitter, so capital letters are no signal.- **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.- **Long lines** are cut into windows, and a name on a window edge can be missed. Every label shortens the window.- **NLI scores are not calibrated probabilities**, depend on the wording of the hypothesis, and are no guarantee. Pairs over 512 tokens are not checked.- **Entity spans only.** GLiNER 2.5's relations, classification and structured output were not exported.- **Bias.** Upstream training data can carry social and geographic bias. Do not use this alone for decisions about people.- Finding names in documents is processing personal data. Running locally does not change your duties under privacy law.
## Licences
`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).
## Cite
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.12345678910114a5f8b1df58dba69e3588255c297e6ad1a70dc8b6312990959f3a3032c892738 deberta-nli/config.jsone0adb1b53ad0bdcf10cf18a6d98207d0403e4e7a87046f6ccf7aa871252d661d deberta-nli/model.onnx835c91321cdf40a99df2f80ca12608efb15806f9a2950f10bc85718b48ef8cc3 deberta-nli/model.onnx_data2910d9437f3dc5eebb5643cea037e9a9495b718a14e64a982155011c5ebe890c deberta-nli/tokenizer.json156ad30e2990ca0bc0d3cff75f2651ae19e18b8d99e20c9aadd9096b9e7ca35e deberta-nli/tokenizer_config.json354c425958b19200cf33fc1fba463f2c8aa42a170e759888af240be13978066d gliner25/boundary_head.onnxd6b515c21ae2100c12267fb42a3f02c1e99ad87580366aebedb161efd74441c7 gliner25/config.json4ed0793d74cc156be6a87f85e94372854fc452d34df23974f9979f23ae53a69b gliner25/encoder/model.onnxe5561bfead6c1422513060d358f3818fa482752bbf446b84ed1c932a47ed2d01 gliner25/encoder/model.onnx_data9b85c8cb45c6451b817afb2dad9e43eb23159f34b694007d8b2e78574c76ab04 gliner25/tokenizer.json539533ecf03df44a0b873233c67f97c2b4e524834c6ea0a9975bf9d586b0e8db gliner25/tokenizer_config.json123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250# /// script# requires-python = ">=3.11,<3.14"# dependencies = [# "onnxruntime==1.23.2",# "tokenizers==0.22.2",# "huggingface_hub>=1.0",# "numpy>=2.0",# ]# ///# SPDX-License-Identifier: Apache-2.0"""Find names in text with the iris-names ONNX files, on the CPU, offline after download.
python extract.py "Ada Lovelace worked with Charles Babbage in London." python extract.py --labels person,city --check "..." python extract.py --self-test
This is a plain reference for the two models. It is not Iris's extraction pipeline,which adds its own filtering, so results differ from Iris.
The word splitter and the overlap rule follow gliner2 2.1.0 (by Fastino AI,Apache-2.0, https://github.com/fastino-ai/GLiNER2)."""
import argparseimport bisectimport jsonimport reimport sysimport unicodedatafrom pathlib import Path
import numpy as npimport onnxruntime as ortfrom tokenizers import Tokenizer
REPO = "iris-hq/iris-names"REVISION = "d179d4a5a599fa8541dd0da17d0aea89096039fc"MODEL_FILES = ["gliner25/*", "gliner25/encoder/*", "deberta-nli/*"]LIMIT = 512 # tokens per model callLABELS = ["person", "organization", "location", "product", "event"]
MARKS = "".join(chr(c) for c in range(sys.maxunicode + 1) if unicodedata.category(chr(c)).startswith("M"))WORD = rf"[\w{MARKS}]"SPLITTER = re.compile( rf"""(?:https?://[^\s]+|www\.[^\s]+) |[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{{2,}} |@[a-z0-9_]+ |{WORD}+(?:[-_]{WORD}+)* |\S""", re.VERBOSE | re.IGNORECASE,)
def split_words(text): """Lowercased words with character offsets into the original text.""" return [(m.group().lower(), m.start(), m.end()) for m in SPLITTER.finditer(text)]
def session(path): options = ort.SessionOptions() options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_BASIC options.enable_cpu_mem_arena = False options.enable_mem_pattern = False options.add_session_config_entry("session.disable_prepacking", "1") options.intra_op_num_threads = 4 options.log_severity_level = 3 return ort.InferenceSession(str(path), options, providers=["CPUExecutionProvider"])
def sigmoid(x): return 1 / (1 + np.exp(-np.clip(x, -60, 60)))
def best_non_overlapping(spans): """The set of (start, end, score) spans with the highest total score and no overlap.""" 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])) ends = [e for (_, e), _ in spans] best = [(0.0, [])] for i, ((s, e), p) in enumerate(spans): total, chosen = best[bisect.bisect_right(ends, s, 0, i)] take = (total + p, chosen + [(s, e, p)]) best.append(max(take, best[i], key=lambda b: (b[0], len(b[1])))) return best[-1][1]
class NameFinder: """GLiNER 2.5: text and labels in, scored spans out."""
def __init__(self, root): root = Path(root) / "gliner25" self.tokenizer = Tokenizer.from_file(str(root / "tokenizer.json")) self.encoder = session(root / "encoder" / "model.onnx") self.head = session(root / "boundary_head.onnx")
def ids(self, text): return self.tokenizer.encode(text, add_special_tokens=False).ids
def find_words(self, words, labels, threshold=0.5): """Spans as (first word, end word, label index, score) for lowercased words.""" prefix = [i for t in ("(", "[P]", "entities", "(") for i in self.ids(t)] queries = [] for label in labels: queries.append(len(prefix)) # the [E] marker stands for the label prefix += self.ids("[E]") + self.ids(label) prefix += [i for t in (")", ")", "[SEP_TEXT]") for i in self.ids(t)] budget = LIMIT - len(prefix) if not labels or budget <= 0: raise ValueError("give at least one label, and few enough to fit in 512 tokens")
spans, ids, routes, first = [], list(prefix), [], 0 for index, word in enumerate(words): tokens = self.ids(word) too_long = len(tokens) > budget # no span can include this word if routes and (too_long or len(ids) + len(tokens) > LIMIT): spans += self._window(ids, routes, queries, first, threshold) ids, routes = list(prefix), [] if too_long: continue if not routes: first = index routes.append(len(ids)) # a word is represented by its first token ids += tokens if routes: spans += self._window(ids, routes, queries, first, threshold) return spans
def _window(self, ids, routes, queries, first, threshold): states = self.encoder.run(None, { "input_ids": np.array([ids], np.int64), "attention_mask": np.ones((1, len(ids)), np.int64), })[0][0] last = len(ids) - 1 indices, pair_logits, valid, null_logits = self.head.run(None, { "token_states": states[np.minimum(routes, last)][None], "text_mask": np.ones((1, len(routes)), bool), "query_states": states[queries][None], "query_mask": np.ones((1, len(queries)), bool), }) scores, null = sigmoid(pair_logits[0]), sigmoid(null_logits[0]) out = [] for label in range(len(queries)): if null[label] > 0.5: # the model says this label is absent continue keep = np.flatnonzero(valid[0, label] & (scores[label] >= threshold)) spans = [(int(indices[0, label, c, 0]), int(indices[0, label, c, 1]), float(scores[label, c])) for c in keep] out += [(first + s, first + e, label, p) for s, e, p in best_non_overlapping(spans)] return out
def find(self, text, labels=LABELS, threshold=0.5): """Names in one short text, such as a sentence or paragraph.""" words = split_words(text) found = [] for s, e, label, score in self.find_words([w for w, _, _ in words], labels, threshold): start, end = words[s][1], words[e - 1][2] found.append({"text": text[start:end], "label": labels[label], "start": start, "end": end, "score": round(score, 4)}) return sorted(found, key=lambda f: (f["start"], f["end"]))
def find_lines(self, text, labels=LABELS, threshold=0.5): """Names in longer text, read a line at a time: the head proposes about 32 names per call.""" found, offset = [], 0 for line in text.splitlines(keepends=True): for f in self.find(line, labels, threshold): found.append({**f, "start": f["start"] + offset, "end": f["end"] + offset}) offset += len(line) return found
class Checker: """DeBERTa-v3 NLI: the probability that a premise entails a hypothesis."""
def __init__(self, root): root = Path(root) / "deberta-nli" self.tokenizer = Tokenizer.from_file(str(root / "tokenizer.json")) self.model = session(root / "model.onnx") id2label = json.loads((root / "config.json").read_text())["id2label"] self.entailment = next(int(k) for k, v in id2label.items() if v.lower() == "entailment")
def entails(self, premise, hypothesis): def ids(text): return self.tokenizer.encode(text, add_special_tokens=False).ids
pair = ids("[CLS]") + ids(premise) + ids("[SEP]") + ids(hypothesis) + ids("[SEP]") if len(pair) > LIMIT: return None # too long to check logits = self.model.run(None, { "input_ids": np.array([pair], np.int64), "attention_mask": np.ones((1, len(pair)), np.int64), })[0][0].astype(np.float64) weights = np.exp(logits - logits.max()) return float(weights[self.entailment] / weights.sum())
def sentence_around(text, start, end): breaks = [0] + [m.end() for m in re.finditer(r"[.!?]\s+|\n+", text)] + [len(text)] left = max(b for b in breaks if b <= start) right = min(b for b in breaks if b >= end) return text[left:right].strip()
def self_test(root): assert best_non_overlapping([(0, 2, 0.9), (1, 3, 0.8), (2, 4, 0.7)]) == [(0, 2, 0.9), (2, 4, 0.7)] assert best_non_overlapping([(0, 4, 0.9), (0, 2, 0.6), (2, 4, 0.6)]) == [(0, 2, 0.6), (2, 4, 0.6)] finder = NameFinder(root) found = {(f["text"], f["label"]) for f in finder.find("Ada Lovelace worked with Charles Babbage in London.")} assert found == {("Ada Lovelace", "person"), ("Charles Babbage", "person"), ("London", "location")}, found assert finder.find("") == [] == finder.find_lines("") lines = "Alice left.\r\n\nShe met Bob.\n" in_lines = finder.find_lines(lines) assert all(lines[f["start"]:f["end"]] == f["text"] for f in in_lines), in_lines assert {"Alice", "Bob"} <= {f["text"] for f in in_lines}, in_lines checker = Checker(root) yes = checker.entails("Kyoto is a city in Japan.", "Kyoto is a city.") no = checker.entails("Kyoto is a city in Japan.", "Kyoto is a person.") assert yes > 0.9 and no < 0.1, (yes, no) assert checker.entails("word " * 600, "Kyoto is a city.") is None print("self-test passed")
def main(): parser = argparse.ArgumentParser(description="Find names in text with the iris-names ONNX files.") parser.add_argument("text", nargs="?", help="text to read; leave out to read standard input") parser.add_argument("--labels", default=",".join(LABELS), help="comma-separated, lowercase") parser.add_argument("--threshold", type=float, default=0.5) parser.add_argument("--check", action="store_true", help="also score each type with the NLI model") parser.add_argument("--model-dir", help="a downloaded copy; default: download the pinned revision") parser.add_argument("--self-test", action="store_true") args = parser.parse_args()
root = args.model_dir if not root: from huggingface_hub import snapshot_download root = snapshot_download(REPO, revision=REVISION, allow_patterns=MODEL_FILES) if args.self_test: return self_test(root)
text = args.text if args.text is not None else sys.stdin.read() labels = [label.strip() for label in args.labels.split(",") if label.strip()] found = NameFinder(root).find_lines(text, labels, args.threshold) if args.check: checker = Checker(root) for f in found: # Illustrative wording: choose and test your own for your labels. score = checker.entails(sentence_around(text, f["start"], f["end"]), f"{f['text']} is a {f['label']}.") f["check"] = None if score is None else round(score, 4) print(json.dumps(found, indent=2, ensure_ascii=False))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254# /// script# requires-python = "==3.13.*"# dependencies = [# "gliner2==2.1.0",# "torch==2.15.0",# "transformers==4.57.6",# "tokenizers==0.22.2",# "onnx==1.23.2",# "onnxscript==0.7.2",# "onnxruntime==1.23.2",# "huggingface_hub==0.36.2",# ]# ///# SPDX-License-Identifier: Apache-2.0"""Rebuild the iris-names ONNX files from the pinned upstream models.
python build_bundle.py OUT_DIR
Downloads fastino/gliner2.5-base-v1 and the Q4F16 ONNX file ofXenova/DeBERTa-v3-base-mnli-fever-anli at fixed commits, converts and repackagesthem, then compares every file with ../SHA256SUMS. Nothing is trained, and noweight is changed or quantised here. OUT_DIR must not exist.
The functions prefixed onnx_ are modified from gliner2 2.1.0 (by Fastino AI,Apache-2.0, https://github.com/fastino-ai/GLiNER2). The changes let the boundaryhead export to ONNX and run on sentences of any length: 1. shift_left_with_bos / shift_right_with_eos: cat/where instead of in-place writes. 2. BoundaryAttentionBlock: the diagonal mask compares positions, because ONNX Runtime has no boolean EyeLike. 3. select_top_boundaries: right-pads to k before topk, so k is constant. 4. aten::sort and aten::argsort with stable=True get a TopK symbolic."""
import hashlibimport jsonimport shutilimport sysimport tempfilefrom pathlib import Path
import gliner2.models.boundary.encoding as b_encimport gliner2.models.boundary.pool as b_poolimport gliner2.models.boundary.proposal as b_propimport onnximport torchfrom gliner2 import AutoExtractorfrom gliner2.models.boundary.constants import MASK_LOGITfrom huggingface_hub import snapshot_downloadfrom torch.onnx import register_custom_op_symbolicfrom torch.onnx._internal.torchscript_exporter import symbolic_helper
GLINER = ("fastino/gliner2.5-base-v1", "07d99c0ba5d15cb3b24e0a236fa99bdd4ef87a5c")NLI = ("Xenova/DeBERTa-v3-base-mnli-fever-anli", "72a1ce83a0144efaf828b3c3844320a61197a53d")TOKENIZER_FILES = ["config.json", "tokenizer.json", "tokenizer_config.json"]
def sort_symbolic(g, self, *args): if len(args) == 3: # (stable, dim, descending) args = args[1:] dim = symbolic_helper._parse_arg(args[0], "i") descending = symbolic_helper._parse_arg(args[1], "i") return symbolic_helper._sort_helper(g, self, dim, descending=descending, out=None)
def argsort_symbolic(g, self, *args): return sort_symbolic(g, self, *args)[1]
def onnx_shift_left_with_bos(text_states, bos_state): b, l, h = text_states.shape bos = bos_state.to(text_states.dtype).view(1, 1, h).expand(b, 1, h) return torch.cat([bos, text_states], dim=1)
def onnx_shift_right_with_eos(text_states, text_lengths, eos_state): b, l, h = text_states.shape eos = eos_state.to(text_states.dtype).view(1, 1, h).expand(b, 1, h) padded = torch.cat([text_states, eos], dim=1) idx = torch.arange(l + 1, device=text_states.device).unsqueeze(0) is_eos = idx == text_lengths.clamp(max=l).unsqueeze(1) return torch.where(is_eos.unsqueeze(-1), eos_state.to(text_states.dtype).view(1, 1, h), padded)
def onnx_attention_forward(self, states, mask): b, n, d = states.shape qkv = self.qkv_projection(self.norm(states)).view(b, n, 3, self.num_heads, self.head_dim) query, key, value = qkv.unbind(2) query = query.transpose(1, 2) key = key.transpose(1, 2) value = value.transpose(1, 2) allowed = mask.view(b, 1, 1, n).expand(b, 1, n, n) positions = torch.arange(n, device=states.device) if self.window > 0: local = (positions.view(n, 1) - positions.view(1, n)).abs() <= self.window allowed = allowed & local.view(1, 1, n, n) diagonal = positions.view(n, 1) == positions.view(1, n) allowed = allowed | diagonal.view(1, 1, n, n) attended = torch.nn.functional.scaled_dot_product_attention( query, key, value, attn_mask=allowed, dropout_p=0.0 ) attended = attended.transpose(1, 2).reshape(b, n, d) update = self.output_projection(attended) return (states + update) * mask.unsqueeze(-1).to(states.dtype)
def onnx_select_top_boundaries(logits, valid_mask, k): b, q, n = logits.shape floor = MASK_LOGIT masked = logits.masked_fill(~valid_mask, floor) pad_logits = masked.new_full((b, q, k), floor) pad_valid = valid_mask.new_zeros((b, q, k)) masked_padded = torch.cat([masked, pad_logits], dim=-1) valid_padded = torch.cat([valid_mask, pad_valid], dim=-1) scores, idx = torch.topk(masked_padded, k=k, dim=-1, largest=True, sorted=True) valid = torch.gather(valid_padded, -1, idx) scores = torch.where(valid, scores, torch.zeros_like(scores)) idx = torch.where(valid, idx, torch.zeros_like(idx)) return scores, idx, valid
class Encoder(torch.nn.Module): def __init__(self, enc): super().__init__() self.enc = enc
def forward(self, input_ids, attention_mask): return self.enc(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state
class BoundaryHead(torch.nn.Module): def __init__(self, bh): super().__init__() self.bh = bh self.bh.candidate_encoder = None # entity spans only: no relations or attributes
def forward(self, token_states, text_mask, query_states, query_mask): out = self.bh(token_states, text_mask, query_states, query_mask, return_candidates=True) c = out.candidates return c.indices, c.pair_logits, c.valid_mask, out.null_logits
def rewrite_tokenizer(src: Path, dst: Path): """Make the tokenizer load in swift-transformers 1.4.0. Token IDs do not change.""" shutil.copyfile(src / "config.json", dst / "config.json") config = json.loads((src / "tokenizer_config.json").read_text(encoding="utf-8")) config["tokenizer_class"] = "XLMRobertaTokenizer" (dst / "tokenizer_config.json").write_text(json.dumps(config, ensure_ascii=False), encoding="utf-8") tokenizer = json.loads((src / "tokenizer.json").read_text(encoding="utf-8")) vocab = tokenizer["model"]["vocab"] for token in sorted(tokenizer["added_tokens"], key=lambda t: t["id"]): if token["id"] < len(vocab): if vocab[token["id"]][0] != token["content"]: raise SystemExit(f"unexpected added token {token}") elif token["id"] == len(vocab): vocab.append([token["content"], 0.0]) else: raise SystemExit(f"gap before added token {token}") (dst / "tokenizer.json").write_text(json.dumps(tokenizer, ensure_ascii=False), encoding="utf-8")
def save_external(src: Path, out_dir: Path): onnx.save_model( onnx.load(str(src)), str(out_dir / "model.onnx"), save_as_external_data=True, all_tensors_to_one_file=True, location="model.onnx_data", size_threshold=1024, convert_attribute=False, )
def export_gliner(src: Path, out: Path, tmp: Path): register_custom_op_symbolic("aten::sort", sort_symbolic, 11) register_custom_op_symbolic("aten::argsort", argsort_symbolic, 11) b_enc.shift_left_with_bos = onnx_shift_left_with_bos b_enc.shift_right_with_eos = onnx_shift_right_with_eos b_enc.BoundaryAttentionBlock.forward = onnx_attention_forward b_prop.select_top_boundaries = onnx_select_top_boundaries b_pool.select_top_boundaries = onnx_select_top_boundaries
torch.manual_seed(0) model = AutoExtractor.from_pretrained(str(src)) model.eval()
torch.manual_seed(0) batch, words, queries, hidden = 2, 40, 23, 768 # example input: batch, words and queries stay dynamic torch.onnx.export( BoundaryHead(model.boundary_head).eval(), (torch.randn(batch, words, hidden), torch.ones(batch, words, dtype=torch.bool), torch.randn(batch, queries, hidden), torch.ones(batch, queries, dtype=torch.bool)), str(out / "boundary_head.onnx"), input_names=["token_states", "text_mask", "query_states", "query_mask"], output_names=["indices", "pair_logits", "valid_mask", "null_logits"], dynamic_axes={ "token_states": {0: "batch", 1: "words"}, "text_mask": {0: "batch", 1: "words"}, "query_states": {0: "batch", 1: "queries"}, "query_mask": {0: "batch", 1: "queries"}, "indices": {0: "batch", 1: "queries", 2: "candidates"}, "pair_logits": {0: "batch", 1: "queries", 2: "candidates"}, "valid_mask": {0: "batch", 1: "queries", 2: "candidates"}, "null_logits": {0: "batch", 1: "queries"}, }, opset_version=18, dynamo=False, )
torch.manual_seed(0) torch.onnx.export( Encoder(model.encoder.float()).eval(), (torch.randint(1, 1000, (2, 32), dtype=torch.long), torch.ones((2, 32), dtype=torch.long)), str(tmp / "encoder.onnx"), input_names=["input_ids", "attention_mask"], output_names=["last_hidden_state"], dynamic_axes={ "input_ids": {0: "batch", 1: "seq"}, "attention_mask": {0: "batch", 1: "seq"}, "last_hidden_state": {0: "batch", 1: "seq"}, }, opset_version=18, dynamo=False, ) (out / "encoder").mkdir() save_external(tmp / "encoder.onnx", out / "encoder")
def sha256(path: Path) -> str: with path.open("rb") as f: return hashlib.file_digest(f, "sha256").hexdigest()
def main() -> int: if len(sys.argv) != 2: raise SystemExit("usage: python build_bundle.py OUT_DIR") out = Path(sys.argv[1]) sums = (Path(__file__).resolve().parent.parent / "SHA256SUMS").read_text().splitlines() (out / "gliner25").mkdir(parents=True) (out / "deberta-nli").mkdir() gliner = Path(snapshot_download(GLINER[0], revision=GLINER[1], allow_patterns=TOKENIZER_FILES + ["encoder_config/config.json", "model.safetensors"])) nli = Path(snapshot_download(NLI[0], revision=NLI[1], allow_patterns=TOKENIZER_FILES + ["onnx/model_q4f16.onnx"])) with tempfile.TemporaryDirectory() as tmp: export_gliner(gliner, out / "gliner25", Path(tmp)) save_external(nli / "onnx" / "model_q4f16.onnx", out / "deberta-nli") rewrite_tokenizer(gliner, out / "gliner25") rewrite_tokenizer(nli, out / "deberta-nli")
different = 0 for line in sums: want, name = line.split(" ", 1) same = sha256(out / name) == want different += not same print("same " if same else "DIFFERENT", name) print(f"{len(sums) - different} of {len(sums)} files are byte-identical to the published ones") return 1 if different else 0
if __name__ == "__main__": sys.exit(main())LICENSE-APACHE-2.0.txtAdded+202
LICENSES.md+23-32
README.md+124-159
SHA256SUMSAdded+11
examples/extract.pyAdded+250
scripts/build_bundle.pyAdded+254