temsa commited on
Commit
b08ade7
·
verified ·
1 Parent(s): 457de06

Publish IrishCore-DiffMask-135M-v1-rc6

Browse files
.gitattributes CHANGED
@@ -1,35 +1,5 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
  *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
  *.pt filter=lfs diff=lfs merge=lfs -text
23
  *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
  *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
1
  *.bin filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
2
  *.onnx filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
3
  *.pt filter=lfs diff=lfs merge=lfs -text
4
  *.pth filter=lfs diff=lfs merge=lfs -text
 
5
  *.safetensors filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
LICENSE ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "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.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "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.
20
+
21
+ "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).
22
+
23
+ "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.
24
+
25
+ "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."
26
+
27
+ "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.
28
+
29
+ 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.
30
+
31
+ 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.
32
+
33
+ 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:
34
+
35
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
36
+
37
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
38
+
39
+ (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
40
+
41
+ (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.
42
+
43
+ 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.
44
+
45
+ 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.
46
+
47
+ 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.
48
+
49
+ 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.
50
+
51
+ 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.
52
+
53
+ 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.
54
+
55
+ END OF TERMS AND CONDITIONS
56
+
57
+ APPENDIX: How to apply the Apache License to your work.
58
+
59
+ 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.
60
+
61
+ Copyright [yyyy] [name of copyright owner]
62
+
63
+ Licensed under the Apache License, Version 2.0 (the "License");
64
+ you may not use this file except in compliance with the License.
65
+ You may obtain a copy of the License at
66
+
67
+ http://www.apache.org/licenses/LICENSE-2.0
68
+
69
+ Unless required by applicable law or agreed to in writing, software
70
+ distributed under the License is distributed on an "AS IS" BASIS,
71
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
72
+ See the License for the specific language governing permissions and
73
+ limitations under the License.
NOTICE ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ IrishCore-DiffMask-135M-v1-rc6
2
+
3
+ This release is derived from:
4
+ - OpenMed/OpenMed-PII-mLiteClinical-Base-135M-v1 (Apache-2.0)
5
+
6
+ Training and evaluation data used for this derivative included:
7
+ - temsa/OpenMed-Irish-CorePII-TrainMix-v1
8
+ - temsa/OpenMed-Irish-PPSN-Eircode-Spec-v1
9
+ - joelniklaus/mapa (CC-BY-4.0)
10
+ - gretelai/synthetic_pii_finance_multilingual (Apache-2.0)
11
+
12
+ Additional local synthetic hardening and replay sets were used during model selection.
13
+ Please review upstream licenses and dataset cards before redistributing derivative datasets.
README.md ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ - ga
5
+ license: apache-2.0
6
+ library_name: transformers
7
+ pipeline_tag: token-classification
8
+ tags:
9
+ - pii
10
+ - de-identification
11
+ - token-classification
12
+ - ireland
13
+ - irish
14
+ - gaelic
15
+ - diffusion-style
16
+ - denoising
17
+ - ppsn
18
+ - eircode
19
+ - onnx
20
+ - int8
21
+ - dynamic-quantization
22
+ - cpu
23
+ base_model:
24
+ - OpenMed/OpenMed-PII-mLiteClinical-Base-135M-v1
25
+ datasets:
26
+ - temsa/OpenMed-Irish-CorePII-TrainMix-v1
27
+ - temsa/OpenMed-Irish-PPSN-Eircode-Spec-v1
28
+ - joelniklaus/mapa
29
+ - gretelai/synthetic_pii_finance_multilingual
30
+ model-index:
31
+ - name: IrishCore-DiffMask-135M-v1-rc6
32
+ results:
33
+ - task:
34
+ type: token-classification
35
+ name: Irish core PII masking
36
+ dataset:
37
+ type: custom
38
+ name: irish_core_pii_v1
39
+ metrics:
40
+ - type: f1
41
+ name: Overall F1
42
+ value: 0.9733
43
+ - task:
44
+ type: token-classification
45
+ name: Multilingual PPSN masking
46
+ dataset:
47
+ type: custom
48
+ name: multilingual_ppsn_v1_all
49
+ metrics:
50
+ - type: f1
51
+ name: Overall F1
52
+ value: 0.9274
53
+ - task:
54
+ type: token-classification
55
+ name: Hardening exact suite
56
+ dataset:
57
+ type: custom
58
+ name: irish_dllm_hardening_exact_v1
59
+ metrics:
60
+ - type: f1
61
+ name: Overall F1
62
+ value: 0.9756
63
+ ---
64
+
65
+ # IrishCore-DiffMask-135M-v1-rc6
66
+
67
+ `IrishCore-DiffMask-135M-v1-rc6` is a raw-only Irish PII masking model derived from `OpenMed/OpenMed-PII-mLiteClinical-Base-135M-v1`.
68
+
69
+ It is a small, scanner-free span extractor tuned for:
70
+
71
+ - `PPSN`
72
+ - `ACCOUNT_NUMBER`
73
+ - `BANK_ROUTING_NUMBER`
74
+ - `CREDIT_DEBIT_CARD`
75
+ - `PASSPORT_NUMBER`
76
+ - `POSTCODE`
77
+ - `PHONE_NUMBER`
78
+ - `EMAIL`
79
+ - `FIRST_NAME`
80
+ - `LAST_NAME`
81
+ - `SWIFT_BIC`
82
+
83
+ The main target is English plus Irish Gaelic text in citizen-support, public-sector, and HSE-style flows. The repo ships both the full `transformers` checkpoint and a dynamic q8 ONNX artifact for CPU deployment.
84
+
85
+ ## Evaluation Harness
86
+
87
+ Release gating for this checkpoint uses the deployment-aligned clean single-pass token-span path.
88
+
89
+ - `experiments/irish_core_span_raw_only/benchmark_multitask.py`
90
+ - `scripts/eval_dllm_release.py --inference-mode clean_single_pass`
91
+
92
+ These two paths now match exactly on the checked suites.
93
+ The older diffusion-style eval path is retained only as a training diagnostic and is not used for release scoring.
94
+
95
+ For this release, the best local raw checkpoint is `models/irishcore-diffmask-135m-v1-rc6k-blend-0p30`, and the bundled CPU artifact is `onnx/model_quantized.onnx`.
96
+
97
+
98
+ ## What "DiffMask" Means Here
99
+
100
+ This release is not a generative diffusion language model. It is a compact discriminative token-span model trained with a diffusion-style denoising schedule.
101
+
102
+ The short version:
103
+
104
+ - **Base OpenMed**: plain BIO token classification
105
+ - **DiffMask**: token-span extraction with token-presence and boundary heads
106
+ - **DiffMask training**: repeated masked denoising over the same sentence
107
+ - **DiffMask inference**: one forward pass, no iterative refinement, no text generation
108
+
109
+ Concretely:
110
+
111
+ - The encoder starts from the DistilBERT-family weights inside `OpenMed/OpenMed-PII-mLiteClinical-Base-135M-v1`.
112
+ - The model adds three task heads over the encoder hidden states:
113
+ - a per-label token-presence head
114
+ - a typed start-boundary head
115
+ - a typed end-boundary head
116
+ - During training, each input sentence is corrupted multiple times by replacing a random fraction of visible tokens with `[MASK]`.
117
+ - The corruption level follows a short noise schedule from heavy masking to light masking.
118
+ - The same gold spans are learned at every noise level, and the losses are averaged across the denoising passes.
119
+ - At inference time there is no diffusion loop and no rewrite step: the model runs once and a score-only span decoder reconstructs spans from token scores plus typed boundaries.
120
+
121
+ So the "DLLM" aspect here is the training recipe: repeated masked denoising over text, not autoregressive generation.
122
+
123
+ ## What It Is Not
124
+
125
+ This model is **not** a full discrete diffusion language model in the LLaDA sense.
126
+
127
+ A true DLLM would usually have:
128
+
129
+ - timestep or noise conditioning inside the model
130
+ - iterative denoising at inference time
131
+ - multi-step sequence refinement at runtime
132
+ - text generation or full-sequence reconstruction as a first-class objective
133
+
134
+ This release does **not** do that.
135
+
136
+ Instead, it uses the diffusion idea only as a **training-time robustness trick**:
137
+
138
+ - corrupt the sentence with `[MASK]` at several noise levels
139
+ - train on the same target spans each time
140
+ - average those losses
141
+
142
+ At runtime, it behaves like a normal fast discriminative extractor.
143
+
144
+ ## Architecture
145
+
146
+ - Encoder: DistilBERT-size encoder from the OpenMed mLiteClinical 135M base
147
+ - Heads:
148
+ - token presence per released label
149
+ - typed start boundary per released label
150
+ - typed end boundary per released label
151
+ - Decoder:
152
+ - score-only span decoding from offsets, token continuity, label-specific thresholds, and typed boundaries
153
+ - no regex candidate extractor
154
+ - no checksum validator
155
+ - no scanner layer
156
+
157
+ The release behavior is fully defined by the weights plus the bundled decoder in `common.py`.
158
+
159
+ ## Training And Inference Flow
160
+
161
+ Training:
162
+
163
+ 1. tokenize a sentence with gold BIO spans
164
+ 2. convert spans into:
165
+ - token-presence targets
166
+ - typed start targets
167
+ - typed end targets
168
+ 3. create several noised copies of the same tokenized sentence by masking random visible tokens
169
+ 4. run the same encoder+heads on each noised copy
170
+ 5. average the losses across those denoising passes
171
+
172
+ Inference:
173
+
174
+ 1. tokenize the raw text once
175
+ 2. run a single forward pass
176
+ 3. predict:
177
+ - which labels are present on each token
178
+ - where each labeled span starts
179
+ - where each labeled span ends
180
+ 4. decode spans with label-aware thresholds and boundary rules
181
+ 5. replace the detected spans with placeholders such as `[PII:PPSN]`
182
+
183
+ There is no multi-step refinement loop in deployment.
184
+
185
+ ## How It Differs From The Original OpenMed Model
186
+
187
+ The original `OpenMed/OpenMed-PII-mLiteClinical-Base-135M-v1` is a standard `DistilBertForTokenClassification` model:
188
+
189
+ - one encoder
190
+ - one token-classification head
191
+ - BIO labels such as `B-email`, `I-email`, `B-phone_number`
192
+ - generic token aggregation to recover spans
193
+
194
+ DiffMask changes two things:
195
+
196
+ 1. **Different supervision**
197
+ - base OpenMed learns only BIO token labels
198
+ - DiffMask learns token presence plus typed span boundaries
199
+
200
+ 2. **Different training recipe**
201
+ - base OpenMed is trained as a standard token classifier
202
+ - DiffMask is trained on multiple masked-noised views of the same sentence
203
+
204
+ That makes DiffMask better suited to structured Irish identifiers and mixed PII masking, while still keeping a small encoder and a fast CPU path.
205
+
206
+ ## How It Differs From `rc5` And `rc8`
207
+
208
+ | Model | Core idea | External scanner/validator | Runtime shape |
209
+ |---|---|---|---|
210
+ | `rc5` | token classifier + repair logic | yes | heavier, decoder-assisted |
211
+ | `rc8` | raw-only token-span model | no | one pass + span decoder |
212
+ | `DiffMask` | raw-only token-span model + denoising training | no | one pass + span decoder |
213
+
214
+ So DiffMask is closest to `rc8` operationally, but it uses a stronger training recipe.
215
+
216
+ ## Why This Exists
217
+
218
+ The older `rc5` release still depended on a repair-oriented decoder stack. The public `rc8` release removed that external logic, but it regressed on several structured Irish identifiers. This release keeps the raw-only deployment shape while re-hardening the model on Irish numeric and mixed-PII cases.
219
+
220
+ ## References
221
+
222
+ Direct implementation references:
223
+
224
+ - Devlin et al., *BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding*
225
+ https://arxiv.org/abs/1810.04805
226
+ - Sanh et al., *DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter*
227
+ https://arxiv.org/abs/1910.01108
228
+ - Fu et al., *Boundary Smoothing for Named Entity Recognition*
229
+ https://aclanthology.org/2022.acl-long.490/
230
+ - Wang et al., *SPANNER: Named Entity Re-/Recognition as Span Prediction*
231
+ https://aclanthology.org/2021.acl-long.558/
232
+
233
+ Conceptual diffusion-style training references:
234
+
235
+ - Nie et al., *LLaDA 2.0: Scaling Up Diffusion Language Models to 100B*
236
+ https://arxiv.org/abs/2512.15745
237
+ - Gong et al., *Scaling Diffusion Language Models via Adaptation from Autoregressive Models*
238
+ https://arxiv.org/abs/2410.17891
239
+
240
+ These diffusion papers were used as architectural inspiration for the masked noising schedule. This release does **not** implement a generative text diffusion runtime.
241
+
242
+ ## Included Artifacts
243
+
244
+ - Full `transformers` checkpoint in the repo root
245
+ - Dynamic q8 ONNX export in `onnx/model_quantized.onnx`
246
+ - Unquantized ONNX export in `onnx/model.onnx`
247
+ - `inference_mask.py` for the full checkpoint
248
+ - `inference_mask_onnx.py` for the ONNX q8 path
249
+ - `common.py`, `model.py`, and `multitask_model.py` implementing the release decoder
250
+ - benchmark files in `eval/`
251
+
252
+ Artifact sizes:
253
+
254
+ - Full checkpoint: `514 MB` (`model.safetensors`)
255
+ - Dynamic q8 ONNX: `393 MB` (`onnx/model_quantized.onnx`)
256
+
257
+ ## How To Use It
258
+
259
+ Full checkpoint:
260
+
261
+ ```bash
262
+ uv run python inference_mask.py \
263
+ --model temsa/IrishCore-DiffMask-135M-v1-rc6 \
264
+ --min-score 0.5 \
265
+ --text "My PPSN is 1234567TW, my Eircode is D02 X285, and my phone is 087 123 4567." \
266
+ --json
267
+ ```
268
+
269
+ Dynamic q8 ONNX:
270
+
271
+ ```bash
272
+ uv run python inference_mask_onnx.py \
273
+ --model temsa/IrishCore-DiffMask-135M-v1-rc6 \
274
+ --min-score 0.5 \
275
+ --text "Please provide your passport NN5123456 and call me on 0851234567." \
276
+ --json
277
+ ```
278
+
279
+ Both scripts emit explicit placeholders like `[PII:PPSN]` in `masked_text`.
280
+
281
+ ## Q8 Comparison
282
+
283
+ Deployment-relevant comparison on CPU:
284
+
285
+ | Model | Core F1 | Edge F1 | Finance F1 | Finance-boundary F1 | User PPSN F1 | GA weak PPSN F1 | Multilingual PPSN F1 | Hardening F1 |
286
+ |---|---:|---:|---:|---:|---:|---:|---:|---:|
287
+ | `rc5` ONNX q8 | 0.9669 | 0.9744 | 0.9362 | 0.8750 | 1.0000 | 1.0000 | 0.9333 | - |
288
+ | `rc8` ONNX q8 | 0.9737 | 1.0000 | 1.0000 | 1.0000 | 1.0000 | 1.0000 | 0.9176 | 0.7059 |
289
+ | `IrishCore-DiffMask-135M-v1-rc6` ONNX q8 | 0.9733 | 0.9500 | 0.9804 | 1.0000 | 0.7500 | 1.0000 | 0.9274 | 0.9756 |
290
+
291
+ CPU throughput references:
292
+
293
+ | Suite | `rc5` q8 | `rc8` q8 | `IrishCore-DiffMask-135M-v1-rc6` q8 |
294
+ |---|---:|---:|---:|
295
+ | Irish core short-text path | 33.6193 ex/s | 257.3756 ex/s | 130.3415 ex/s |
296
+ | Multilingual PPSN short-text path | 35.5561 ex/s | 230.5181 ex/s | 200.2041 ex/s |
297
+ | Runtime profile source | 23.8338 ex/s | 179.4708 ex/s | 167.1461 ex/s |
298
+
299
+ Notes:
300
+
301
+ - The `rc5` speed references come from its published q8 end-to-end inference stack, which includes its older repair decoder.
302
+ - The `rc8` and `IrishCore-DiffMask-135M-v1-rc6` numbers use the same raw-only token-span ONNX path.
303
+ - A weight-only q4 ONNX experiment was also tried during development, but it was slower than q8 on this CPU and is not shipped.
304
+
305
+ ## Limits
306
+
307
+ - This is still a compact model. The hardest remaining errors are multilingual PPSN near-miss cases rather than Irish core numeric formats.
308
+ - The release path is intentionally scanner-free. If you need deterministic validation of individual identifier types, add that in your application layer.
309
+ - If you rely on release behavior, use the bundled inference scripts or import `decode_token_presence_segments` from `common.py`.
310
+
311
+ ## License And Attribution
312
+
313
+ - Release license: Apache-2.0
314
+ - Base model: `OpenMed/OpenMed-PII-mLiteClinical-Base-135M-v1`
315
+ - The derivative release remains subject to the attribution terms of the upstream datasets listed above.
316
+ - See `NOTICE`, `training_sources.json`, and `eval/benchmark_summary.json` for provenance and benchmark details.
317
+
318
+ ## Release Note
319
+
320
+ `rc6` is the first DiffMask package selected after reconciling the evaluation harness. Under the aligned harness, it matches the prior best candidate on fresh holdout, QA feedback exact, UAT exact, multilingual PPSN, edge, finance, and hardening, while improving Irish core on the full checkpoint.
common.py ADDED
@@ -0,0 +1,613 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import tempfile
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import numpy as np
10
+ from huggingface_hub import HfApi, hf_hub_download
11
+ from transformers import AutoConfig, AutoTokenizer
12
+
13
+ TOKENIZER_FILES = [
14
+ "tokenizer_config.json",
15
+ "tokenizer.json",
16
+ "special_tokens_map.json",
17
+ "vocab.txt",
18
+ "vocab.json",
19
+ "merges.txt",
20
+ "added_tokens.json",
21
+ "sentencepiece.bpe.model",
22
+ "spiece.model",
23
+ ]
24
+ DEFAULT_LABEL_MAX_SPAN_TOKENS = {
25
+ # Token-piece limits, not word limits. These need to reflect how the
26
+ # underlying tokenizer actually fragments compact identifiers.
27
+ "PPSN": 9,
28
+ "POSTCODE": 7,
29
+ "PHONE_NUMBER": 10,
30
+ "PASSPORT_NUMBER": 8,
31
+ "BANK_ROUTING_NUMBER": 5,
32
+ "ACCOUNT_NUMBER": 19,
33
+ "CREDIT_DEBIT_CARD": 12,
34
+ "SWIFT_BIC": 8,
35
+ "EMAIL": 15,
36
+ "FIRST_NAME": 5,
37
+ "LAST_NAME": 8,
38
+ }
39
+ DEFAULT_LABEL_MIN_NONSPACE_CHARS = {
40
+ "PPSN": 8,
41
+ "POSTCODE": 6,
42
+ "PHONE_NUMBER": 7,
43
+ "PASSPORT_NUMBER": 7,
44
+ "BANK_ROUTING_NUMBER": 6,
45
+ "ACCOUNT_NUMBER": 6,
46
+ "CREDIT_DEBIT_CARD": 12,
47
+ "SWIFT_BIC": 8,
48
+ "EMAIL": 6,
49
+ "FIRST_NAME": 2,
50
+ "LAST_NAME": 2,
51
+ }
52
+ WHITESPACE_BRIDGE_LABELS = {
53
+ "PPSN",
54
+ "POSTCODE",
55
+ "PHONE_NUMBER",
56
+ "PASSPORT_NUMBER",
57
+ "BANK_ROUTING_NUMBER",
58
+ "ACCOUNT_NUMBER",
59
+ "CREDIT_DEBIT_CARD",
60
+ "SWIFT_BIC",
61
+ }
62
+ SIMPLE_PUNCT_BRIDGE_LABELS = {
63
+ "PHONE_NUMBER",
64
+ "BANK_ROUTING_NUMBER",
65
+ "ACCOUNT_NUMBER",
66
+ "CREDIT_DEBIT_CARD",
67
+ }
68
+ MIN_CHAR_FALLBACK_LABELS = {
69
+ "PHONE_NUMBER",
70
+ "BANK_ROUTING_NUMBER",
71
+ "ACCOUNT_NUMBER",
72
+ "CREDIT_DEBIT_CARD",
73
+ "EMAIL",
74
+ }
75
+ CONSERVATIVE_BOUNDARY_REFINEMENT_LABELS = {
76
+ "PPSN",
77
+ "POSTCODE",
78
+ "PHONE_NUMBER",
79
+ "PASSPORT_NUMBER",
80
+ "BANK_ROUTING_NUMBER",
81
+ "ACCOUNT_NUMBER",
82
+ "CREDIT_DEBIT_CARD",
83
+ "SWIFT_BIC",
84
+ "EMAIL",
85
+ }
86
+ OUTPUT_PRIORITY = {
87
+ "PPSN": 0,
88
+ "PASSPORT_NUMBER": 1,
89
+ "ACCOUNT_NUMBER": 2,
90
+ "BANK_ROUTING_NUMBER": 3,
91
+ "CREDIT_DEBIT_CARD": 4,
92
+ "PHONE_NUMBER": 5,
93
+ "SWIFT_BIC": 6,
94
+ "POSTCODE": 7,
95
+ "EMAIL": 8,
96
+ "FIRST_NAME": 9,
97
+ "LAST_NAME": 10,
98
+ }
99
+
100
+
101
+ def normalize_entity_name(label: str) -> str:
102
+ label = (label or "").strip()
103
+ if label.startswith("B-") or label.startswith("I-"):
104
+ label = label[2:]
105
+ return label.upper()
106
+
107
+
108
+ def _sanitize_tokenizer_dir(tokenizer_path: Path) -> str:
109
+ tokenizer_cfg_path = tokenizer_path / "tokenizer_config.json"
110
+ if not tokenizer_cfg_path.exists():
111
+ return str(tokenizer_path)
112
+ data = json.loads(tokenizer_cfg_path.read_text(encoding="utf-8"))
113
+ if "fix_mistral_regex" not in data:
114
+ return str(tokenizer_path)
115
+ tmpdir = Path(tempfile.mkdtemp(prefix="openmed_span_tokenizer_"))
116
+ keep = set(TOKENIZER_FILES)
117
+ for child in tokenizer_path.iterdir():
118
+ if child.is_file() and child.name in keep:
119
+ (tmpdir / child.name).write_bytes(child.read_bytes())
120
+ data.pop("fix_mistral_regex", None)
121
+ (tmpdir / "tokenizer_config.json").write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
122
+ return str(tmpdir)
123
+
124
+
125
+ def safe_auto_tokenizer(tokenizer_ref: str):
126
+ tokenizer_path = Path(tokenizer_ref)
127
+ if tokenizer_path.exists():
128
+ tokenizer_ref = _sanitize_tokenizer_dir(tokenizer_path)
129
+ else:
130
+ api = HfApi()
131
+ files = set(api.list_repo_files(repo_id=tokenizer_ref, repo_type="model"))
132
+ tmpdir = Path(tempfile.mkdtemp(prefix="openmed_remote_span_tokenizer_"))
133
+ copied = False
134
+ for name in TOKENIZER_FILES:
135
+ if name not in files:
136
+ continue
137
+ src = hf_hub_download(repo_id=tokenizer_ref, filename=name, repo_type="model")
138
+ (tmpdir / Path(name).name).write_bytes(Path(src).read_bytes())
139
+ copied = True
140
+ if copied:
141
+ tokenizer_ref = _sanitize_tokenizer_dir(tmpdir)
142
+
143
+ try:
144
+ return AutoTokenizer.from_pretrained(tokenizer_ref, use_fast=True, fix_mistral_regex=True)
145
+ except Exception:
146
+ pass
147
+ try:
148
+ return AutoTokenizer.from_pretrained(tokenizer_ref, use_fast=True, fix_mistral_regex=False)
149
+ except TypeError:
150
+ pass
151
+ try:
152
+ return AutoTokenizer.from_pretrained(tokenizer_ref, use_fast=True)
153
+ except Exception:
154
+ return AutoTokenizer.from_pretrained(tokenizer_ref, use_fast=False)
155
+
156
+
157
+ def label_names_from_config(config) -> list[str]:
158
+ names = list(getattr(config, "span_label_names", []))
159
+ if not names:
160
+ raise ValueError("Missing span_label_names in config")
161
+ return [normalize_entity_name(name) for name in names]
162
+
163
+
164
+ def label_thresholds_from_config(config, default_threshold: float) -> dict[str, float]:
165
+ raw = getattr(config, "span_label_thresholds", None) or {}
166
+ out = {normalize_entity_name(key): float(value) for key, value in raw.items()}
167
+ for label in label_names_from_config(config):
168
+ out.setdefault(label, float(default_threshold))
169
+ return out
170
+
171
+
172
+ def token_label_thresholds_from_config(config, default_threshold: float) -> dict[str, float]:
173
+ raw = getattr(config, "token_label_thresholds", None) or {}
174
+ out = {normalize_entity_name(key): float(value) for key, value in raw.items()}
175
+ for label in label_names_from_config(config):
176
+ out.setdefault(label, float(default_threshold))
177
+ return out
178
+
179
+
180
+ def token_extend_thresholds_from_config(config, default_fraction: float = 0.6) -> dict[str, float]:
181
+ raw = getattr(config, "token_extend_thresholds", None) or {}
182
+ out = {normalize_entity_name(key): float(value) for key, value in raw.items()}
183
+ for label in label_names_from_config(config):
184
+ out.setdefault(label, max(0.0, min(1.0, float(token_label_thresholds_from_config(config, 0.5).get(label, 0.5)) * default_fraction)))
185
+ return out
186
+
187
+
188
+ def boundary_label_thresholds_from_config(config, default_threshold: float = 0.0) -> dict[str, float]:
189
+ raw = getattr(config, "boundary_label_thresholds", None) or {}
190
+ out = {normalize_entity_name(key): float(value) for key, value in raw.items()}
191
+ for label in label_names_from_config(config):
192
+ out.setdefault(label, float(default_threshold))
193
+ return out
194
+
195
+
196
+ def label_max_span_tokens_from_config(config) -> dict[str, int]:
197
+ raw = getattr(config, "span_label_max_span_tokens", None) or {}
198
+ out = {normalize_entity_name(key): int(value) for key, value in raw.items()}
199
+ for label, value in DEFAULT_LABEL_MAX_SPAN_TOKENS.items():
200
+ out.setdefault(label, value)
201
+ for label in label_names_from_config(config):
202
+ out.setdefault(label, 8)
203
+ return out
204
+
205
+
206
+ def label_min_nonspace_chars_from_config(config) -> dict[str, int]:
207
+ raw = getattr(config, "span_label_min_nonspace_chars", None) or {}
208
+ out = {normalize_entity_name(key): int(value) for key, value in raw.items()}
209
+ for label, value in DEFAULT_LABEL_MIN_NONSPACE_CHARS.items():
210
+ out.setdefault(label, value)
211
+ for label in label_names_from_config(config):
212
+ out.setdefault(label, 1)
213
+ return out
214
+
215
+
216
+ def overlaps(a: dict, b: dict) -> bool:
217
+ return not (a["end"] <= b["start"] or b["end"] <= a["start"])
218
+
219
+
220
+ def dedupe_spans(spans: list[dict]) -> list[dict]:
221
+ ordered = sorted(
222
+ spans,
223
+ key=lambda item: (-float(item.get("score", 0.0)), item["start"], item["end"], OUTPUT_PRIORITY.get(item["label"], 99)),
224
+ )
225
+ kept = []
226
+ for span in ordered:
227
+ if any(overlaps(span, other) for other in kept):
228
+ continue
229
+ kept.append(span)
230
+ kept.sort(key=lambda item: (item["start"], item["end"], OUTPUT_PRIORITY.get(item["label"], 99)))
231
+ return kept
232
+
233
+
234
+ def _valid_offset(offset: tuple[int, int]) -> bool:
235
+ return bool(offset) and offset[1] > offset[0]
236
+
237
+
238
+ def _has_skippable_bridge(text: str, left: tuple[int, int], right: tuple[int, int], label: str) -> bool:
239
+ bridge = text[int(left[1]) : int(right[0])]
240
+ if bridge == "":
241
+ return True
242
+ if label == "PPSN" and bridge.isspace():
243
+ next_token = _token_text(text, right).strip()
244
+ return 0 < len(next_token) <= 2 and next_token.isalnum()
245
+ if label in WHITESPACE_BRIDGE_LABELS and bridge.isspace():
246
+ return True
247
+ if label in SIMPLE_PUNCT_BRIDGE_LABELS:
248
+ normalized = bridge.replace("\u00A0", " ").replace("\u202F", " ").strip()
249
+ if normalized == "-":
250
+ return True
251
+ return False
252
+
253
+
254
+ def _has_left_extension_bridge(text: str, left: tuple[int, int], right: tuple[int, int]) -> bool:
255
+ bridge = text[int(left[1]) : int(right[0])]
256
+ return bridge == ""
257
+
258
+
259
+ def _nonspace_length(text: str, start: int, end: int) -> int:
260
+ return sum(0 if ch.isspace() else 1 for ch in text[int(start) : int(end)])
261
+
262
+
263
+ def _is_simple_punct_token(text: str, offset: tuple[int, int], label: str) -> bool:
264
+ if label not in SIMPLE_PUNCT_BRIDGE_LABELS or not _valid_offset(offset):
265
+ return False
266
+ token_text = text[int(offset[0]) : int(offset[1])].replace("\u00A0", " ").replace("\u202F", " ").strip()
267
+ return token_text == "-"
268
+
269
+
270
+ def _token_text(text: str, offset: tuple[int, int]) -> str:
271
+ return text[int(offset[0]) : int(offset[1])]
272
+
273
+
274
+ def _is_short_alnum_token(text: str, offset: tuple[int, int], max_len: int = 4) -> bool:
275
+ token_text = _token_text(text, offset).strip()
276
+ return 0 < len(token_text) <= max_len and token_text.isalnum()
277
+
278
+
279
+ def _rescue_structured_start(
280
+ text: str,
281
+ offsets: list[tuple[int, int]],
282
+ valid: list[bool],
283
+ token_scores: np.ndarray,
284
+ start_scores: np.ndarray,
285
+ label: str,
286
+ label_index: int,
287
+ threshold: float,
288
+ boundary_threshold: float,
289
+ start_idx: int,
290
+ end_idx: int,
291
+ ) -> int | None:
292
+ if label not in {"ACCOUNT_NUMBER", "CREDIT_DEBIT_CARD"}:
293
+ return None
294
+ segment_text = text[int(offsets[start_idx][0]) : int(offsets[end_idx][1])]
295
+ if label == "ACCOUNT_NUMBER" and not any(ch.isspace() for ch in segment_text):
296
+ return None
297
+ best_idx = None
298
+ best_score = -1.0
299
+ for cand_idx in range(start_idx, end_idx + 1):
300
+ if not valid[cand_idx]:
301
+ continue
302
+ token_score = float(token_scores[cand_idx, label_index])
303
+ start_score = float(start_scores[cand_idx, label_index])
304
+ if token_score < threshold or start_score < boundary_threshold:
305
+ continue
306
+ token_text = _token_text(text, offsets[cand_idx]).strip()
307
+ score = start_score + 0.2 * token_score
308
+ if label == "ACCOUNT_NUMBER":
309
+ next_text = _token_text(text, offsets[cand_idx + 1]).strip() if cand_idx + 1 <= end_idx and valid[cand_idx + 1] else ""
310
+ if token_text.upper() == "I" and next_text.upper() == "E":
311
+ score += 1.0
312
+ elif token_text.upper().startswith("IE"):
313
+ score += 0.6
314
+ elif label == "CREDIT_DEBIT_CARD" and token_text.isdigit():
315
+ score += 0.3
316
+ if score > best_score:
317
+ best_idx = cand_idx
318
+ best_score = score
319
+ return best_idx
320
+
321
+
322
+ def _rescue_email_outer_span(span_text: str, outer_text: str) -> bool:
323
+ if "@" not in span_text or " " in outer_text:
324
+ return False
325
+ if "@" not in outer_text:
326
+ return False
327
+ _, _, span_domain = span_text.partition("@")
328
+ _, _, outer_domain = outer_text.partition("@")
329
+ if "." in span_domain and not span_text.endswith("@"):
330
+ return False
331
+ return "." in outer_domain and not outer_text.endswith("@")
332
+
333
+
334
+ def _rescue_iban_tail(text: str, offsets: list[tuple[int, int]], valid: list[bool], start_idx: int, end_idx: int) -> int:
335
+ next_idx = end_idx + 1
336
+ span_text = text[int(offsets[start_idx][0]) : int(offsets[end_idx][1])]
337
+ if not any(ch.isspace() for ch in span_text):
338
+ return end_idx
339
+ compact = "".join(ch for ch in span_text if not ch.isspace())
340
+ if not compact.upper().startswith("IE"):
341
+ return end_idx
342
+ while next_idx < len(offsets) and valid[next_idx]:
343
+ if not _has_skippable_bridge(text, offsets[end_idx], offsets[next_idx], "ACCOUNT_NUMBER"):
344
+ break
345
+ if not _is_short_alnum_token(text, offsets[next_idx]):
346
+ break
347
+ end_idx = next_idx
348
+ span_text = text[int(offsets[start_idx][0]) : int(offsets[end_idx][1])]
349
+ compact = "".join(ch for ch in span_text if not ch.isspace())
350
+ if len(compact) >= 22:
351
+ break
352
+ next_idx += 1
353
+ return end_idx
354
+
355
+
356
+ def decode_span_logits(
357
+ text: str,
358
+ offsets: list[tuple[int, int]],
359
+ start_scores: np.ndarray,
360
+ end_scores: np.ndarray,
361
+ label_names: list[str],
362
+ default_threshold: float,
363
+ label_thresholds: dict[str, float] | None = None,
364
+ label_max_span_tokens: dict[str, int] | None = None,
365
+ ) -> list[dict]:
366
+ thresholds = {label: float(default_threshold) for label in label_names}
367
+ if label_thresholds:
368
+ thresholds.update({normalize_entity_name(key): float(value) for key, value in label_thresholds.items()})
369
+ max_tokens = dict(DEFAULT_LABEL_MAX_SPAN_TOKENS)
370
+ if label_max_span_tokens:
371
+ max_tokens.update({normalize_entity_name(key): int(value) for key, value in label_max_span_tokens.items()})
372
+
373
+ spans: list[dict] = []
374
+ for label_index, label in enumerate(label_names):
375
+ threshold = thresholds.get(label, float(default_threshold))
376
+ max_span = max_tokens.get(label, 8)
377
+ start_candidates = [idx for idx in range(len(offsets)) if _valid_offset(offsets[idx]) and float(start_scores[idx, label_index]) >= threshold]
378
+ for start_idx in start_candidates:
379
+ best = None
380
+ for end_idx in range(start_idx, min(len(offsets), start_idx + max_span)):
381
+ if not _valid_offset(offsets[end_idx]):
382
+ continue
383
+ end_score = float(end_scores[end_idx, label_index])
384
+ if end_score < threshold:
385
+ continue
386
+ score = min(float(start_scores[start_idx, label_index]), end_score)
387
+ if best is None or score > best["score"]:
388
+ best = {
389
+ "label": label,
390
+ "start": int(offsets[start_idx][0]),
391
+ "end": int(offsets[end_idx][1]),
392
+ "score": score,
393
+ }
394
+ if best is not None and best["start"] < best["end"]:
395
+ best["text"] = text[best["start"]:best["end"]]
396
+ spans.append(best)
397
+ return dedupe_spans(spans)
398
+
399
+
400
+ def decode_token_presence_segments(
401
+ text: str,
402
+ offsets: list[tuple[int, int]],
403
+ token_scores: np.ndarray,
404
+ label_names: list[str],
405
+ default_threshold: float,
406
+ label_thresholds: dict[str, float] | None = None,
407
+ label_extend_thresholds: dict[str, float] | None = None,
408
+ label_max_span_tokens: dict[str, int] | None = None,
409
+ label_min_nonspace_chars: dict[str, int] | None = None,
410
+ boundary_label_thresholds: dict[str, float] | None = None,
411
+ start_scores: np.ndarray | None = None,
412
+ end_scores: np.ndarray | None = None,
413
+ ) -> list[dict]:
414
+ thresholds = {label: float(default_threshold) for label in label_names}
415
+ if label_thresholds:
416
+ thresholds.update({normalize_entity_name(key): float(value) for key, value in label_thresholds.items()})
417
+ extend_thresholds = {label: max(0.0, min(1.0, thresholds[label] * 0.6)) for label in label_names}
418
+ if label_extend_thresholds:
419
+ extend_thresholds.update({normalize_entity_name(key): float(value) for key, value in label_extend_thresholds.items()})
420
+ max_tokens = dict(DEFAULT_LABEL_MAX_SPAN_TOKENS)
421
+ if label_max_span_tokens:
422
+ max_tokens.update({normalize_entity_name(key): int(value) for key, value in label_max_span_tokens.items()})
423
+ min_nonspace_chars = dict(DEFAULT_LABEL_MIN_NONSPACE_CHARS)
424
+ if label_min_nonspace_chars:
425
+ min_nonspace_chars.update({normalize_entity_name(key): int(value) for key, value in label_min_nonspace_chars.items()})
426
+ boundary_thresholds = {label: 0.0 for label in label_names}
427
+ if boundary_label_thresholds:
428
+ boundary_thresholds.update({normalize_entity_name(key): float(value) for key, value in boundary_label_thresholds.items()})
429
+
430
+ spans: list[dict] = []
431
+ valid = [_valid_offset(offset) for offset in offsets]
432
+ num_tokens = len(offsets)
433
+ for label_index, label in enumerate(label_names):
434
+ threshold = thresholds.get(label, float(default_threshold))
435
+ extend_threshold = min(threshold, extend_thresholds.get(label, threshold))
436
+ max_span = max_tokens.get(label, 8)
437
+ idx = 0
438
+ while idx < num_tokens:
439
+ if not valid[idx] or float(token_scores[idx, label_index]) < threshold:
440
+ idx += 1
441
+ continue
442
+ start_idx = idx
443
+ end_idx = idx
444
+ outer_start_idx = start_idx
445
+ outer_end_idx = end_idx
446
+ while end_idx + 1 < num_tokens and valid[end_idx + 1] and float(token_scores[end_idx + 1, label_index]) >= threshold and (end_idx + 1 - start_idx + 1) <= max_span:
447
+ end_idx += 1
448
+ while (
449
+ start_idx - 1 >= 0
450
+ and valid[start_idx - 1]
451
+ and _has_left_extension_bridge(text, offsets[start_idx - 1], offsets[start_idx])
452
+ and float(token_scores[start_idx - 1, label_index]) >= extend_threshold
453
+ and (end_idx - (start_idx - 1) + 1) <= max_span
454
+ ):
455
+ start_idx -= 1
456
+ while end_idx + 1 < num_tokens:
457
+ next_idx = end_idx + 1
458
+ if not valid[next_idx]:
459
+ break
460
+ if (
461
+ _has_skippable_bridge(text, offsets[end_idx], offsets[next_idx], label)
462
+ and float(token_scores[next_idx, label_index]) >= extend_threshold
463
+ and (next_idx - start_idx + 1) <= max_span
464
+ ):
465
+ end_idx = next_idx
466
+ continue
467
+ if (
468
+ _is_simple_punct_token(text, offsets[next_idx], label)
469
+ and next_idx + 1 < num_tokens
470
+ and valid[next_idx + 1]
471
+ and _has_skippable_bridge(text, offsets[end_idx], offsets[next_idx], label)
472
+ and _has_skippable_bridge(text, offsets[next_idx], offsets[next_idx + 1], label)
473
+ and float(token_scores[next_idx + 1, label_index]) >= extend_threshold
474
+ and ((next_idx + 1) - start_idx + 1) <= max_span
475
+ ):
476
+ end_idx = next_idx + 1
477
+ continue
478
+ break
479
+ outer_start_idx = start_idx
480
+ outer_end_idx = end_idx
481
+ presence_slice = token_scores[start_idx : end_idx + 1, label_index]
482
+ score = float(presence_slice.mean())
483
+ out_start_idx = start_idx
484
+ out_end_idx = end_idx
485
+ if start_scores is not None and end_scores is not None:
486
+ refine_window = min(3, end_idx - start_idx + 1)
487
+ start_window = start_scores[start_idx : start_idx + refine_window, label_index]
488
+ best_start_rel = int(np.argmax(start_window))
489
+ best_start_idx = start_idx + best_start_rel
490
+ end_window_start = max(best_start_idx, end_idx - refine_window + 1)
491
+ end_window = end_scores[end_window_start : end_idx + 1, label_index]
492
+ best_end_rel = int(np.argmax(end_window))
493
+ best_end_idx = end_window_start + best_end_rel
494
+ if (
495
+ float(start_scores[best_start_idx, label_index]) < boundary_thresholds.get(label, 0.0)
496
+ or float(end_scores[best_end_idx, label_index]) < boundary_thresholds.get(label, 0.0)
497
+ ):
498
+ rescued_start_idx = _rescue_structured_start(
499
+ text,
500
+ offsets,
501
+ valid,
502
+ token_scores,
503
+ start_scores,
504
+ label,
505
+ label_index,
506
+ threshold,
507
+ boundary_thresholds.get(label, 0.0),
508
+ start_idx,
509
+ end_idx,
510
+ )
511
+ if rescued_start_idx is not None:
512
+ out_start_idx = rescued_start_idx
513
+ out_end_idx = end_idx
514
+ else:
515
+ idx = end_idx + 1
516
+ continue
517
+ else:
518
+ out_start_idx = best_start_idx
519
+ out_end_idx = best_end_idx
520
+ if label in CONSERVATIVE_BOUNDARY_REFINEMENT_LABELS and (
521
+ best_start_idx != start_idx or best_end_idx != end_idx
522
+ ):
523
+ outer_boundary = min(float(start_scores[start_idx, label_index]), float(end_scores[end_idx, label_index]))
524
+ refined_boundary = min(
525
+ float(start_scores[best_start_idx, label_index]),
526
+ float(end_scores[best_end_idx, label_index]),
527
+ )
528
+ if refined_boundary < outer_boundary + 0.08:
529
+ out_start_idx = start_idx
530
+ out_end_idx = end_idx
531
+ score = (
532
+ 0.65 * score
533
+ + 0.175 * float(start_scores[out_start_idx, label_index])
534
+ + 0.175 * float(end_scores[out_end_idx, label_index])
535
+ )
536
+ min_chars = int(min_nonspace_chars.get(label, 1))
537
+ if _nonspace_length(text, offsets[out_start_idx][0], offsets[out_end_idx][1]) < min_chars:
538
+ if (
539
+ label in MIN_CHAR_FALLBACK_LABELS
540
+ and (out_start_idx != start_idx or out_end_idx != end_idx)
541
+ and _nonspace_length(text, offsets[start_idx][0], offsets[end_idx][1]) >= min_chars
542
+ ):
543
+ out_start_idx = start_idx
544
+ out_end_idx = end_idx
545
+ else:
546
+ idx = end_idx + 1
547
+ continue
548
+ if label == "ACCOUNT_NUMBER":
549
+ out_end_idx = _rescue_iban_tail(text, offsets, valid, out_start_idx, out_end_idx)
550
+ span_text = text[int(offsets[out_start_idx][0]) : int(offsets[out_end_idx][1])]
551
+ outer_text = text[int(offsets[outer_start_idx][0]) : int(offsets[outer_end_idx][1])]
552
+ if label == "EMAIL" and _rescue_email_outer_span(span_text, outer_text):
553
+ out_start_idx = outer_start_idx
554
+ out_end_idx = outer_end_idx
555
+ span_text = outer_text
556
+ if label in {"FIRST_NAME", "LAST_NAME"} and any(ch.isdigit() for ch in span_text):
557
+ idx = end_idx + 1
558
+ continue
559
+ spans.append(
560
+ {
561
+ "label": label,
562
+ "start": int(offsets[out_start_idx][0]),
563
+ "end": int(offsets[out_end_idx][1]),
564
+ "score": score,
565
+ "text": span_text,
566
+ }
567
+ )
568
+ idx = end_idx + 1
569
+ return dedupe_spans(spans)
570
+
571
+
572
+ def load_onnx_session(model_ref: str, onnx_file: str = "model_quantized.onnx", onnx_subfolder: str = "onnx"):
573
+ import onnxruntime as ort
574
+
575
+ model_path = Path(model_ref)
576
+ if model_path.exists():
577
+ candidates = []
578
+ if onnx_subfolder:
579
+ candidates.append(model_path / onnx_subfolder / onnx_file)
580
+ candidates.append(model_path / onnx_file)
581
+ onnx_path = next((path for path in candidates if path.exists()), candidates[0])
582
+ config = AutoConfig.from_pretrained(model_ref)
583
+ tokenizer = safe_auto_tokenizer(model_ref)
584
+ else:
585
+ remote_name = f"{onnx_subfolder}/{onnx_file}" if onnx_subfolder else onnx_file
586
+ onnx_path = Path(hf_hub_download(repo_id=model_ref, filename=remote_name, repo_type="model"))
587
+ config = AutoConfig.from_pretrained(model_ref)
588
+ tokenizer = safe_auto_tokenizer(model_ref)
589
+ session = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"])
590
+ return session, tokenizer, config
591
+
592
+
593
+ def run_onnx(session, encoded: dict[str, Any]) -> tuple[np.ndarray, np.ndarray]:
594
+ feed = {}
595
+ input_names = {item.name for item in session.get_inputs()}
596
+ for key, value in encoded.items():
597
+ if key == "offset_mapping":
598
+ continue
599
+ if key in input_names:
600
+ feed[key] = value
601
+ outputs = session.run(None, feed)
602
+ return outputs[0], outputs[1]
603
+
604
+
605
+ def run_onnx_all(session, encoded: dict[str, Any]) -> list[np.ndarray]:
606
+ feed = {}
607
+ input_names = {item.name for item in session.get_inputs()}
608
+ for key, value in encoded.items():
609
+ if key == "offset_mapping":
610
+ continue
611
+ if key in input_names:
612
+ feed[key] = value
613
+ return session.run(None, feed)
config.json ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation": "gelu",
3
+ "architectures": [
4
+ "IrishCoreTokenSpanModel"
5
+ ],
6
+ "attention_dropout": 0.1,
7
+ "boundary_focal_gamma": 2.0,
8
+ "boundary_hard_fraction": 0.25,
9
+ "boundary_label_thresholds": {
10
+ "ACCOUNT_NUMBER": 0.1,
11
+ "BANK_ROUTING_NUMBER": 0.25,
12
+ "CREDIT_DEBIT_CARD": 0.25,
13
+ "EMAIL": 0.2,
14
+ "FIRST_NAME": 0.1,
15
+ "LAST_NAME": 0.1,
16
+ "PASSPORT_NUMBER": 0.25,
17
+ "PHONE_NUMBER": 0.25,
18
+ "POSTCODE": 0.4,
19
+ "PPSN": 0.35,
20
+ "SWIFT_BIC": 0.25
21
+ },
22
+ "boundary_loss_weight": 1.0,
23
+ "decoder_profile": "rc3_focusv3_email_extend015_passport075",
24
+ "dim": 768,
25
+ "dropout": 0.1,
26
+ "dtype": "float32",
27
+ "hidden_dim": 3072,
28
+ "id2label": {
29
+ "0": "O",
30
+ "1": "B-account_number",
31
+ "2": "B-age",
32
+ "3": "B-api_key",
33
+ "4": "B-bank_routing_number",
34
+ "5": "B-biometric_identifier",
35
+ "6": "B-blood_type",
36
+ "7": "B-certificate_license_number",
37
+ "8": "B-city",
38
+ "9": "B-company_name",
39
+ "10": "B-coordinate",
40
+ "11": "B-country",
41
+ "12": "B-county",
42
+ "13": "B-credit_debit_card",
43
+ "14": "B-customer_id",
44
+ "15": "B-cvv",
45
+ "16": "B-date",
46
+ "17": "B-date_of_birth",
47
+ "18": "B-date_time",
48
+ "19": "B-device_identifier",
49
+ "20": "B-education_level",
50
+ "21": "B-email",
51
+ "22": "B-employee_id",
52
+ "23": "B-employment_status",
53
+ "24": "B-fax_number",
54
+ "25": "B-first_name",
55
+ "26": "B-gender",
56
+ "27": "B-health_plan_beneficiary_number",
57
+ "28": "B-http_cookie",
58
+ "29": "B-ipv4",
59
+ "30": "B-ipv6",
60
+ "31": "B-language",
61
+ "32": "B-last_name",
62
+ "33": "B-license_plate",
63
+ "34": "B-mac_address",
64
+ "35": "B-medical_record_number",
65
+ "36": "B-occupation",
66
+ "37": "B-password",
67
+ "38": "B-phone_number",
68
+ "39": "B-pin",
69
+ "40": "B-political_view",
70
+ "41": "B-postcode",
71
+ "42": "B-race_ethnicity",
72
+ "43": "B-religious_belief",
73
+ "44": "B-sexuality",
74
+ "45": "B-ssn",
75
+ "46": "B-state",
76
+ "47": "B-street_address",
77
+ "48": "B-swift_bic",
78
+ "49": "B-tax_id",
79
+ "50": "B-time",
80
+ "51": "B-unique_id",
81
+ "52": "B-url",
82
+ "53": "B-user_name",
83
+ "54": "B-vehicle_identifier",
84
+ "55": "I-account_number",
85
+ "56": "I-api_key",
86
+ "57": "I-biometric_identifier",
87
+ "58": "I-blood_type",
88
+ "59": "I-certificate_license_number",
89
+ "60": "I-city",
90
+ "61": "I-company_name",
91
+ "62": "I-coordinate",
92
+ "63": "I-country",
93
+ "64": "I-county",
94
+ "65": "I-credit_debit_card",
95
+ "66": "I-customer_id",
96
+ "67": "I-date",
97
+ "68": "I-date_of_birth",
98
+ "69": "I-date_time",
99
+ "70": "I-device_identifier",
100
+ "71": "I-education_level",
101
+ "72": "I-email",
102
+ "73": "I-employee_id",
103
+ "74": "I-employment_status",
104
+ "75": "I-fax_number",
105
+ "76": "I-first_name",
106
+ "77": "I-gender",
107
+ "78": "I-health_plan_beneficiary_number",
108
+ "79": "I-http_cookie",
109
+ "80": "I-ipv4",
110
+ "81": "I-ipv6",
111
+ "82": "I-language",
112
+ "83": "I-last_name",
113
+ "84": "I-license_plate",
114
+ "85": "I-mac_address",
115
+ "86": "I-medical_record_number",
116
+ "87": "I-occupation",
117
+ "88": "I-password",
118
+ "89": "I-phone_number",
119
+ "90": "I-pin",
120
+ "91": "I-political_view",
121
+ "92": "I-postcode",
122
+ "93": "I-race_ethnicity",
123
+ "94": "I-religious_belief",
124
+ "95": "I-sexuality",
125
+ "96": "I-ssn",
126
+ "97": "I-state",
127
+ "98": "I-street_address",
128
+ "99": "I-swift_bic",
129
+ "100": "I-tax_id",
130
+ "101": "I-time",
131
+ "102": "I-unique_id",
132
+ "103": "I-url",
133
+ "104": "I-user_name",
134
+ "105": "I-vehicle_identifier",
135
+ "106": "B-PPSN",
136
+ "107": "I-PPSN",
137
+ "108": "B-PASSPORT_NUMBER",
138
+ "109": "I-PASSPORT_NUMBER",
139
+ "110": "I-bank_routing_number"
140
+ },
141
+ "initializer_range": 0.02,
142
+ "label2id": {
143
+ "B-PASSPORT_NUMBER": 108,
144
+ "B-PPSN": 106,
145
+ "B-account_number": 1,
146
+ "B-age": 2,
147
+ "B-api_key": 3,
148
+ "B-bank_routing_number": 4,
149
+ "B-biometric_identifier": 5,
150
+ "B-blood_type": 6,
151
+ "B-certificate_license_number": 7,
152
+ "B-city": 8,
153
+ "B-company_name": 9,
154
+ "B-coordinate": 10,
155
+ "B-country": 11,
156
+ "B-county": 12,
157
+ "B-credit_debit_card": 13,
158
+ "B-customer_id": 14,
159
+ "B-cvv": 15,
160
+ "B-date": 16,
161
+ "B-date_of_birth": 17,
162
+ "B-date_time": 18,
163
+ "B-device_identifier": 19,
164
+ "B-education_level": 20,
165
+ "B-email": 21,
166
+ "B-employee_id": 22,
167
+ "B-employment_status": 23,
168
+ "B-fax_number": 24,
169
+ "B-first_name": 25,
170
+ "B-gender": 26,
171
+ "B-health_plan_beneficiary_number": 27,
172
+ "B-http_cookie": 28,
173
+ "B-ipv4": 29,
174
+ "B-ipv6": 30,
175
+ "B-language": 31,
176
+ "B-last_name": 32,
177
+ "B-license_plate": 33,
178
+ "B-mac_address": 34,
179
+ "B-medical_record_number": 35,
180
+ "B-occupation": 36,
181
+ "B-password": 37,
182
+ "B-phone_number": 38,
183
+ "B-pin": 39,
184
+ "B-political_view": 40,
185
+ "B-postcode": 41,
186
+ "B-race_ethnicity": 42,
187
+ "B-religious_belief": 43,
188
+ "B-sexuality": 44,
189
+ "B-ssn": 45,
190
+ "B-state": 46,
191
+ "B-street_address": 47,
192
+ "B-swift_bic": 48,
193
+ "B-tax_id": 49,
194
+ "B-time": 50,
195
+ "B-unique_id": 51,
196
+ "B-url": 52,
197
+ "B-user_name": 53,
198
+ "B-vehicle_identifier": 54,
199
+ "I-PASSPORT_NUMBER": 109,
200
+ "I-PPSN": 107,
201
+ "I-account_number": 55,
202
+ "I-api_key": 56,
203
+ "I-bank_routing_number": 110,
204
+ "I-biometric_identifier": 57,
205
+ "I-blood_type": 58,
206
+ "I-certificate_license_number": 59,
207
+ "I-city": 60,
208
+ "I-company_name": 61,
209
+ "I-coordinate": 62,
210
+ "I-country": 63,
211
+ "I-county": 64,
212
+ "I-credit_debit_card": 65,
213
+ "I-customer_id": 66,
214
+ "I-date": 67,
215
+ "I-date_of_birth": 68,
216
+ "I-date_time": 69,
217
+ "I-device_identifier": 70,
218
+ "I-education_level": 71,
219
+ "I-email": 72,
220
+ "I-employee_id": 73,
221
+ "I-employment_status": 74,
222
+ "I-fax_number": 75,
223
+ "I-first_name": 76,
224
+ "I-gender": 77,
225
+ "I-health_plan_beneficiary_number": 78,
226
+ "I-http_cookie": 79,
227
+ "I-ipv4": 80,
228
+ "I-ipv6": 81,
229
+ "I-language": 82,
230
+ "I-last_name": 83,
231
+ "I-license_plate": 84,
232
+ "I-mac_address": 85,
233
+ "I-medical_record_number": 86,
234
+ "I-occupation": 87,
235
+ "I-password": 88,
236
+ "I-phone_number": 89,
237
+ "I-pin": 90,
238
+ "I-political_view": 91,
239
+ "I-postcode": 92,
240
+ "I-race_ethnicity": 93,
241
+ "I-religious_belief": 94,
242
+ "I-sexuality": 95,
243
+ "I-ssn": 96,
244
+ "I-state": 97,
245
+ "I-street_address": 98,
246
+ "I-swift_bic": 99,
247
+ "I-tax_id": 100,
248
+ "I-time": 101,
249
+ "I-unique_id": 102,
250
+ "I-url": 103,
251
+ "I-user_name": 104,
252
+ "I-vehicle_identifier": 105,
253
+ "O": 0
254
+ },
255
+ "max_position_embeddings": 512,
256
+ "model_type": "distilbert",
257
+ "n_heads": 12,
258
+ "n_layers": 6,
259
+ "num_span_labels": 11,
260
+ "output_past": true,
261
+ "pad_token_id": 0,
262
+ "qa_dropout": 0.1,
263
+ "seq_classif_dropout": 0.2,
264
+ "sinusoidal_pos_embds": false,
265
+ "span_label_max_span_tokens": {
266
+ "ACCOUNT_NUMBER": 19,
267
+ "BANK_ROUTING_NUMBER": 6,
268
+ "CREDIT_DEBIT_CARD": 13,
269
+ "EMAIL": 16,
270
+ "FIRST_NAME": 5,
271
+ "LAST_NAME": 8,
272
+ "PASSPORT_NUMBER": 9,
273
+ "PHONE_NUMBER": 10,
274
+ "POSTCODE": 8,
275
+ "PPSN": 9,
276
+ "SWIFT_BIC": 8
277
+ },
278
+ "span_label_names": [
279
+ "ACCOUNT_NUMBER",
280
+ "BANK_ROUTING_NUMBER",
281
+ "CREDIT_DEBIT_CARD",
282
+ "EMAIL",
283
+ "FIRST_NAME",
284
+ "LAST_NAME",
285
+ "PASSPORT_NUMBER",
286
+ "PHONE_NUMBER",
287
+ "POSTCODE",
288
+ "PPSN",
289
+ "SWIFT_BIC"
290
+ ],
291
+ "span_label_thresholds": {
292
+ "ACCOUNT_NUMBER": 0.5,
293
+ "BANK_ROUTING_NUMBER": 0.5,
294
+ "CREDIT_DEBIT_CARD": 0.5,
295
+ "EMAIL": 0.5,
296
+ "FIRST_NAME": 0.5,
297
+ "LAST_NAME": 0.5,
298
+ "PASSPORT_NUMBER": 0.5,
299
+ "PHONE_NUMBER": 0.5,
300
+ "POSTCODE": 0.5,
301
+ "PPSN": 0.5,
302
+ "SWIFT_BIC": 0.5
303
+ },
304
+ "span_positive_weight": 6.0,
305
+ "tie_weights_": true,
306
+ "token_extend_thresholds": {
307
+ "ACCOUNT_NUMBER": 0.08,
308
+ "BANK_ROUTING_NUMBER": 0.3,
309
+ "CREDIT_DEBIT_CARD": 0.3,
310
+ "EMAIL": 0.15,
311
+ "FIRST_NAME": 0.3,
312
+ "LAST_NAME": 0.3,
313
+ "PASSPORT_NUMBER": 0.15,
314
+ "PHONE_NUMBER": 0.15,
315
+ "POSTCODE": 0.3,
316
+ "PPSN": 0.3,
317
+ "SWIFT_BIC": 0.3
318
+ },
319
+ "token_focal_gamma": 1.0,
320
+ "token_hard_fraction": 0.4,
321
+ "token_label_thresholds": {
322
+ "ACCOUNT_NUMBER": 0.18,
323
+ "BANK_ROUTING_NUMBER": 0.8,
324
+ "CREDIT_DEBIT_CARD": 0.8,
325
+ "EMAIL": 0.95,
326
+ "FIRST_NAME": 0.3,
327
+ "LAST_NAME": 0.4,
328
+ "PASSPORT_NUMBER": 0.75,
329
+ "PHONE_NUMBER": 0.65,
330
+ "POSTCODE": 0.9,
331
+ "PPSN": 0.7,
332
+ "SWIFT_BIC": 0.8
333
+ },
334
+ "token_positive_weight": 4.0,
335
+ "token_presence_weight": 1.0,
336
+ "transformers_version": "4.57.6",
337
+ "vocab_size": 119547
338
+ }
eval/benchmark_summary.json ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "release": "IrishCore-DiffMask-135M-v1-rc6",
3
+ "repo_id": "temsa/IrishCore-DiffMask-135M-v1-rc6",
4
+ "architecture": {
5
+ "family": "DistilBERT-size token-span extractor",
6
+ "diffusion_style_training": true,
7
+ "runtime_diffusion": false,
8
+ "scanner_free": true,
9
+ "validator_free": true,
10
+ "heads": [
11
+ "token_presence_head",
12
+ "typed_start_boundary_head",
13
+ "typed_end_boundary_head"
14
+ ]
15
+ },
16
+ "base_model": "OpenMed/OpenMed-PII-mLiteClinical-Base-135M-v1",
17
+ "notes": [
18
+ "DiffMask uses a masked denoising training schedule, not a generative diffusion runtime.",
19
+ "ONNX q8 is the recommended CPU deployment artifact.",
20
+ "The release inference scripts emit [PII:LABEL] placeholders."
21
+ ],
22
+ "full": {
23
+ "core_f1": 0.9801324503311258,
24
+ "edge_f1": 0.9500000000000001,
25
+ "multilingual_f1": 0.9273743016759777,
26
+ "hardening_f1": 0.975609756097561
27
+ },
28
+ "onnx_q8": {
29
+ "core_f1": 0.9733333333333333,
30
+ "edge_f1": 0.9500000000000001,
31
+ "finance_f1": 0.9803921568627451,
32
+ "finance_boundary_f1": 1.0,
33
+ "user_ppsn_f1": 0.7499999999999999,
34
+ "gaelic_weak_ppsn_f1": 1.0,
35
+ "multilingual_f1": 0.9273743016759777,
36
+ "hardening_f1": 0.975609756097561,
37
+ "core_examples_per_second": 130.34154354965295,
38
+ "multilingual_examples_per_second": 200.20407351151675,
39
+ "runtime_profile_examples_per_second": 167.14610336175048
40
+ },
41
+ "comparison": {
42
+ "public_rc5_onnx_q8": {
43
+ "core": 0.9668874172185431,
44
+ "edge": 0.9743589743589743,
45
+ "remaining_gaps": 0.888888888888889,
46
+ "finance": 0.9361702127659575,
47
+ "finance_boundary": 0.8750000000000001,
48
+ "multilingual_ppsn": 0.9333333333333333,
49
+ "user_ppsn": 1.0,
50
+ "gaelic_weak_ppsn": 1.0,
51
+ "overlap_ppsn": 1.0
52
+ },
53
+ "public_rc8_onnx_q8": {
54
+ "min_score": 0.5,
55
+ "irish_core_manual_f1": 0.9736842105263158,
56
+ "irish_edge_f1": 1.0,
57
+ "finance_suite_f1": 1.0,
58
+ "finance_boundary_f1": 1.0,
59
+ "user_raw_ppsn_f1": 1.0,
60
+ "gaelic_weak_ppsn_f1": 1.0,
61
+ "multilingual_ppsn_f1": 0.9176470588235294,
62
+ "core_examples_per_second": 46.14201741375802,
63
+ "multilingual_examples_per_second": 99.71655616732895
64
+ }
65
+ }
66
+ }
eval/benchmark_summary.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Benchmark Summary
2
+
3
+ ## ONNX q8
4
+
5
+ | Suite | F1 | Examples/s |
6
+ |---|---:|---:|
7
+ | Irish core | 0.9733 | 130.3415 |
8
+ | Edge | 0.9500 | 275.6818 |
9
+ | Finance | 0.9804 | 264.2625 |
10
+ | Finance boundary | 1.0000 | 249.6232 |
11
+ | User PPSN | 0.7500 | 146.1010 |
12
+ | GA weak PPSN | 1.0000 | 67.8436 |
13
+ | Multilingual PPSN | 0.9274 | 200.2041 |
14
+ | Hardening exact | 0.9756 | 125.5843 |
15
+
16
+ ## Full checkpoint
17
+
18
+ | Suite | F1 | Examples/s |
19
+ |---|---:|---:|
20
+ | Irish core | 0.9801 | 106.7506 |
21
+ | Edge | 0.9500 | 114.6062 |
22
+ | Multilingual PPSN | 0.9274 | 110.2363 |
23
+ | Hardening exact | 0.9756 | 106.8223 |
eval/full_core_irish_core_pii_v1.json ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "models/irishcore-diffmask-135m-v1-rc6k-blend-0p30",
3
+ "input": "eval/irish_core_pii_v1.jsonl",
4
+ "loader_type": "token_span_pt",
5
+ "examples": 37,
6
+ "min_score": 0.5,
7
+ "iou_threshold": 0.5,
8
+ "elapsed_seconds": 0.3466022629290819,
9
+ "examples_per_second": 106.75060135879883,
10
+ "overall": {
11
+ "precision": 0.9866666666666667,
12
+ "recall": 0.9736842105263158,
13
+ "f1": 0.9801324503311258,
14
+ "tp": 74,
15
+ "fp": 1,
16
+ "fn": 2
17
+ },
18
+ "by_label": {
19
+ "ACCOUNT_NUMBER": {
20
+ "precision": 1.0,
21
+ "recall": 1.0,
22
+ "f1": 1.0,
23
+ "tp": 3,
24
+ "fp": 0,
25
+ "fn": 0
26
+ },
27
+ "BANK_ROUTING_NUMBER": {
28
+ "precision": 1.0,
29
+ "recall": 1.0,
30
+ "f1": 1.0,
31
+ "tp": 1,
32
+ "fp": 0,
33
+ "fn": 0
34
+ },
35
+ "CREDIT_DEBIT_CARD": {
36
+ "precision": 1.0,
37
+ "recall": 1.0,
38
+ "f1": 1.0,
39
+ "tp": 2,
40
+ "fp": 0,
41
+ "fn": 0
42
+ },
43
+ "EMAIL": {
44
+ "precision": 1.0,
45
+ "recall": 1.0,
46
+ "f1": 1.0,
47
+ "tp": 6,
48
+ "fp": 0,
49
+ "fn": 0
50
+ },
51
+ "FIRST_NAME": {
52
+ "precision": 0.9444444444444444,
53
+ "recall": 0.8947368421052632,
54
+ "f1": 0.918918918918919,
55
+ "tp": 17,
56
+ "fp": 1,
57
+ "fn": 2
58
+ },
59
+ "LAST_NAME": {
60
+ "precision": 1.0,
61
+ "recall": 1.0,
62
+ "f1": 1.0,
63
+ "tp": 19,
64
+ "fp": 0,
65
+ "fn": 0
66
+ },
67
+ "PASSPORT_NUMBER": {
68
+ "precision": 1.0,
69
+ "recall": 1.0,
70
+ "f1": 1.0,
71
+ "tp": 2,
72
+ "fp": 0,
73
+ "fn": 0
74
+ },
75
+ "PHONE_NUMBER": {
76
+ "precision": 1.0,
77
+ "recall": 1.0,
78
+ "f1": 1.0,
79
+ "tp": 12,
80
+ "fp": 0,
81
+ "fn": 0
82
+ },
83
+ "POSTCODE": {
84
+ "precision": 1.0,
85
+ "recall": 1.0,
86
+ "f1": 1.0,
87
+ "tp": 4,
88
+ "fp": 0,
89
+ "fn": 0
90
+ },
91
+ "PPSN": {
92
+ "precision": 1.0,
93
+ "recall": 1.0,
94
+ "f1": 1.0,
95
+ "tp": 6,
96
+ "fp": 0,
97
+ "fn": 0
98
+ },
99
+ "SWIFT_BIC": {
100
+ "precision": 1.0,
101
+ "recall": 1.0,
102
+ "f1": 1.0,
103
+ "tp": 2,
104
+ "fp": 0,
105
+ "fn": 0
106
+ }
107
+ }
108
+ }
eval/full_edge_irish_ppsn_phone_edge_v1.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "models/irishcore-diffmask-135m-v1-rc6k-blend-0p30",
3
+ "input": "eval/irish_ppsn_phone_edge_v1.jsonl",
4
+ "loader_type": "token_span_pt",
5
+ "examples": 22,
6
+ "min_score": 0.5,
7
+ "iou_threshold": 0.5,
8
+ "elapsed_seconds": 0.19196176307741553,
9
+ "examples_per_second": 114.60615722271578,
10
+ "overall": {
11
+ "precision": 0.9047619047619048,
12
+ "recall": 1.0,
13
+ "f1": 0.9500000000000001,
14
+ "tp": 19,
15
+ "fp": 2,
16
+ "fn": 0
17
+ },
18
+ "by_label": {
19
+ "PHONE_NUMBER": {
20
+ "precision": 0.9285714285714286,
21
+ "recall": 1.0,
22
+ "f1": 0.962962962962963,
23
+ "tp": 13,
24
+ "fp": 1,
25
+ "fn": 0
26
+ },
27
+ "PPSN": {
28
+ "precision": 0.8571428571428571,
29
+ "recall": 1.0,
30
+ "f1": 0.923076923076923,
31
+ "tp": 6,
32
+ "fp": 1,
33
+ "fn": 0
34
+ }
35
+ }
36
+ }
eval/full_hardening_exact_v1.json ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "models/irishcore-diffmask-135m-v1-rc6k-blend-0p30",
3
+ "input": "eval/irish_dllm_hardening_exact_v1.jsonl",
4
+ "loader_type": "token_span_pt",
5
+ "examples": 14,
6
+ "min_score": 0.5,
7
+ "iou_threshold": 0.5,
8
+ "elapsed_seconds": 0.13105878001078963,
9
+ "examples_per_second": 106.82229758927579,
10
+ "overall": {
11
+ "precision": 0.9523809523809523,
12
+ "recall": 1.0,
13
+ "f1": 0.975609756097561,
14
+ "tp": 20,
15
+ "fp": 1,
16
+ "fn": 0
17
+ },
18
+ "by_label": {
19
+ "ACCOUNT_NUMBER": {
20
+ "precision": 0.5,
21
+ "recall": 1.0,
22
+ "f1": 0.6666666666666666,
23
+ "tp": 1,
24
+ "fp": 1,
25
+ "fn": 0
26
+ },
27
+ "BANK_ROUTING_NUMBER": {
28
+ "precision": 1.0,
29
+ "recall": 1.0,
30
+ "f1": 1.0,
31
+ "tp": 2,
32
+ "fp": 0,
33
+ "fn": 0
34
+ },
35
+ "CREDIT_DEBIT_CARD": {
36
+ "precision": 1.0,
37
+ "recall": 1.0,
38
+ "f1": 1.0,
39
+ "tp": 2,
40
+ "fp": 0,
41
+ "fn": 0
42
+ },
43
+ "EMAIL": {
44
+ "precision": 1.0,
45
+ "recall": 1.0,
46
+ "f1": 1.0,
47
+ "tp": 2,
48
+ "fp": 0,
49
+ "fn": 0
50
+ },
51
+ "FIRST_NAME": {
52
+ "precision": 1.0,
53
+ "recall": 1.0,
54
+ "f1": 1.0,
55
+ "tp": 1,
56
+ "fp": 0,
57
+ "fn": 0
58
+ },
59
+ "LAST_NAME": {
60
+ "precision": 1.0,
61
+ "recall": 1.0,
62
+ "f1": 1.0,
63
+ "tp": 1,
64
+ "fp": 0,
65
+ "fn": 0
66
+ },
67
+ "PHONE_NUMBER": {
68
+ "precision": 1.0,
69
+ "recall": 1.0,
70
+ "f1": 1.0,
71
+ "tp": 2,
72
+ "fp": 0,
73
+ "fn": 0
74
+ },
75
+ "POSTCODE": {
76
+ "precision": 1.0,
77
+ "recall": 1.0,
78
+ "f1": 1.0,
79
+ "tp": 3,
80
+ "fp": 0,
81
+ "fn": 0
82
+ },
83
+ "PPSN": {
84
+ "precision": 1.0,
85
+ "recall": 1.0,
86
+ "f1": 1.0,
87
+ "tp": 3,
88
+ "fp": 0,
89
+ "fn": 0
90
+ },
91
+ "SWIFT_BIC": {
92
+ "precision": 1.0,
93
+ "recall": 1.0,
94
+ "f1": 1.0,
95
+ "tp": 3,
96
+ "fp": 0,
97
+ "fn": 0
98
+ }
99
+ }
100
+ }
eval/full_multilingual_ppsn_v1_all.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "models/irishcore-diffmask-135m-v1-rc6k-blend-0p30",
3
+ "input": "eval/multilingual_ppsn_v1_all.jsonl",
4
+ "loader_type": "token_span_pt",
5
+ "examples": 168,
6
+ "min_score": 0.5,
7
+ "iou_threshold": 0.5,
8
+ "elapsed_seconds": 1.5239994541043416,
9
+ "examples_per_second": 110.2362599589867,
10
+ "overall": {
11
+ "precision": 0.8736842105263158,
12
+ "recall": 0.9880952380952381,
13
+ "f1": 0.9273743016759777,
14
+ "tp": 83,
15
+ "fp": 12,
16
+ "fn": 1
17
+ },
18
+ "by_label": {
19
+ "PPSN": {
20
+ "precision": 0.9325842696629213,
21
+ "recall": 0.9880952380952381,
22
+ "f1": 0.9595375722543353,
23
+ "tp": 83,
24
+ "fp": 6,
25
+ "fn": 1
26
+ }
27
+ }
28
+ }
eval/harness_reconciliation.json ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "models/irishcore-diffmask-135m-v1-rc6b-focusv10-e012-b48w0",
3
+ "datasets": {
4
+ "fresh_holdout": {
5
+ "benchmark_multitask_pt": {
6
+ "precision": 0.9047619047619048,
7
+ "recall": 0.59375,
8
+ "f1": 0.7169811320754718,
9
+ "tp": 19,
10
+ "fp": 2,
11
+ "fn": 13
12
+ },
13
+ "eval_release_clean_single_pass": {
14
+ "precision": 0.9047619047619048,
15
+ "recall": 0.59375,
16
+ "f1": 0.7169811320754718,
17
+ "tp": 19,
18
+ "fp": 2,
19
+ "fn": 13
20
+ },
21
+ "eval_release_diffusion_last_pass": {
22
+ "precision": 0.782608695652174,
23
+ "recall": 0.5625,
24
+ "f1": 0.6545454545454547,
25
+ "tp": 18,
26
+ "fp": 5,
27
+ "fn": 14
28
+ }
29
+ },
30
+ "uat_exact": {
31
+ "benchmark_multitask_pt": {
32
+ "precision": 1.0,
33
+ "recall": 0.8235294117647058,
34
+ "f1": 0.9032258064516129,
35
+ "tp": 14,
36
+ "fp": 0,
37
+ "fn": 3
38
+ },
39
+ "eval_release_clean_single_pass": {
40
+ "precision": 1.0,
41
+ "recall": 0.8235294117647058,
42
+ "f1": 0.9032258064516129,
43
+ "tp": 14,
44
+ "fp": 0,
45
+ "fn": 3
46
+ },
47
+ "eval_release_diffusion_last_pass": {
48
+ "precision": 1.0,
49
+ "recall": 0.8235294117647058,
50
+ "f1": 0.9032258064516129,
51
+ "tp": 14,
52
+ "fp": 0,
53
+ "fn": 3
54
+ }
55
+ },
56
+ "irish_core": {
57
+ "benchmark_multitask_pt": {
58
+ "precision": 0.9864864864864865,
59
+ "recall": 0.9605263157894737,
60
+ "f1": 0.9733333333333333,
61
+ "tp": 73,
62
+ "fp": 1,
63
+ "fn": 3
64
+ },
65
+ "eval_release_clean_single_pass": {
66
+ "precision": 0.9864864864864865,
67
+ "recall": 0.9605263157894737,
68
+ "f1": 0.9733333333333333,
69
+ "tp": 73,
70
+ "fp": 1,
71
+ "fn": 3
72
+ },
73
+ "eval_release_diffusion_last_pass": {
74
+ "precision": 0.9736842105263158,
75
+ "recall": 0.9736842105263158,
76
+ "f1": 0.9736842105263158,
77
+ "tp": 74,
78
+ "fp": 2,
79
+ "fn": 2
80
+ }
81
+ },
82
+ "multilingual_ppsn": {
83
+ "benchmark_multitask_pt": {
84
+ "precision": 0.8736842105263158,
85
+ "recall": 0.9880952380952381,
86
+ "f1": 0.9273743016759777,
87
+ "tp": 83,
88
+ "fp": 12,
89
+ "fn": 1
90
+ },
91
+ "eval_release_clean_single_pass": {
92
+ "precision": 0.8736842105263158,
93
+ "recall": 0.9880952380952381,
94
+ "f1": 0.9273743016759777,
95
+ "tp": 83,
96
+ "fp": 12,
97
+ "fn": 1
98
+ },
99
+ "eval_release_diffusion_last_pass": {
100
+ "precision": 0.8666666666666667,
101
+ "recall": 0.9285714285714286,
102
+ "f1": 0.896551724137931,
103
+ "tp": 78,
104
+ "fp": 12,
105
+ "fn": 6
106
+ }
107
+ }
108
+ }
109
+ }
eval/harness_reconciliation.md ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DiffMask Eval Harness
2
+
3
+ - Model: `models/irishcore-diffmask-135m-v1-rc6b-focusv10-e012-b48w0`
4
+
5
+ ## Result
6
+
7
+ The deployment-aligned harness is the clean single-pass token-span path.
8
+
9
+ - `experiments/irish_core_span_raw_only/benchmark_multitask.py` and `scripts/eval_dllm_release.py --inference-mode clean_single_pass` match exactly on the checked suites.
10
+ - The old diffusion-style eval path (`diffusion_last_pass`) is not deployment-aligned and depresses scores on several suites.
11
+
12
+ ## Comparison
13
+
14
+ | Dataset | benchmark_multitask | eval_clean_single_pass | eval_diffusion_last_pass |
15
+ |---|---:|---:|---:|
16
+ | `fresh_holdout` | 0.7170 | 0.7170 | 0.6545 |
17
+ | `uat_exact` | 0.9032 | 0.9032 | 0.9032 |
18
+ | `irish_core` | 0.9733 | 0.9733 | 0.9737 |
19
+ | `multilingual_ppsn` | 0.9274 | 0.9274 | 0.8966 |
20
+
21
+ ## Conclusion
22
+
23
+ - Use `clean_single_pass` for release gating and model comparison.
24
+ - Keep `diffusion_last_pass` only as a training diagnostic if needed.
eval/q8_core_irish_core_pii_v1.json ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "models/irishcore-diffmask-135m-v1-rc6k-blend-0p30_onnx_q8",
3
+ "input": "eval/irish_core_pii_v1.jsonl",
4
+ "loader_type": "token_span_onnx_q8",
5
+ "examples": 37,
6
+ "min_score": 0.5,
7
+ "iou_threshold": 0.5,
8
+ "elapsed_seconds": 0.28386958595365286,
9
+ "examples_per_second": 130.34154354965295,
10
+ "overall": {
11
+ "precision": 0.9864864864864865,
12
+ "recall": 0.9605263157894737,
13
+ "f1": 0.9733333333333333,
14
+ "tp": 73,
15
+ "fp": 1,
16
+ "fn": 3
17
+ },
18
+ "by_label": {
19
+ "ACCOUNT_NUMBER": {
20
+ "precision": 1.0,
21
+ "recall": 1.0,
22
+ "f1": 1.0,
23
+ "tp": 3,
24
+ "fp": 0,
25
+ "fn": 0
26
+ },
27
+ "BANK_ROUTING_NUMBER": {
28
+ "precision": 1.0,
29
+ "recall": 1.0,
30
+ "f1": 1.0,
31
+ "tp": 1,
32
+ "fp": 0,
33
+ "fn": 0
34
+ },
35
+ "CREDIT_DEBIT_CARD": {
36
+ "precision": 1.0,
37
+ "recall": 1.0,
38
+ "f1": 1.0,
39
+ "tp": 2,
40
+ "fp": 0,
41
+ "fn": 0
42
+ },
43
+ "EMAIL": {
44
+ "precision": 1.0,
45
+ "recall": 1.0,
46
+ "f1": 1.0,
47
+ "tp": 6,
48
+ "fp": 0,
49
+ "fn": 0
50
+ },
51
+ "FIRST_NAME": {
52
+ "precision": 0.9444444444444444,
53
+ "recall": 0.8947368421052632,
54
+ "f1": 0.918918918918919,
55
+ "tp": 17,
56
+ "fp": 1,
57
+ "fn": 2
58
+ },
59
+ "LAST_NAME": {
60
+ "precision": 1.0,
61
+ "recall": 0.9473684210526315,
62
+ "f1": 0.972972972972973,
63
+ "tp": 18,
64
+ "fp": 0,
65
+ "fn": 1
66
+ },
67
+ "PASSPORT_NUMBER": {
68
+ "precision": 1.0,
69
+ "recall": 1.0,
70
+ "f1": 1.0,
71
+ "tp": 2,
72
+ "fp": 0,
73
+ "fn": 0
74
+ },
75
+ "PHONE_NUMBER": {
76
+ "precision": 1.0,
77
+ "recall": 1.0,
78
+ "f1": 1.0,
79
+ "tp": 12,
80
+ "fp": 0,
81
+ "fn": 0
82
+ },
83
+ "POSTCODE": {
84
+ "precision": 1.0,
85
+ "recall": 1.0,
86
+ "f1": 1.0,
87
+ "tp": 4,
88
+ "fp": 0,
89
+ "fn": 0
90
+ },
91
+ "PPSN": {
92
+ "precision": 1.0,
93
+ "recall": 1.0,
94
+ "f1": 1.0,
95
+ "tp": 6,
96
+ "fp": 0,
97
+ "fn": 0
98
+ },
99
+ "SWIFT_BIC": {
100
+ "precision": 1.0,
101
+ "recall": 1.0,
102
+ "f1": 1.0,
103
+ "tp": 2,
104
+ "fp": 0,
105
+ "fn": 0
106
+ }
107
+ }
108
+ }
eval/q8_edge_irish_ppsn_phone_edge_v1.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "models/irishcore-diffmask-135m-v1-rc6k-blend-0p30_onnx_q8",
3
+ "input": "eval/irish_ppsn_phone_edge_v1.jsonl",
4
+ "loader_type": "token_span_onnx_q8",
5
+ "examples": 22,
6
+ "min_score": 0.5,
7
+ "iou_threshold": 0.5,
8
+ "elapsed_seconds": 0.0798021589871496,
9
+ "examples_per_second": 275.68176449389824,
10
+ "overall": {
11
+ "precision": 0.9047619047619048,
12
+ "recall": 1.0,
13
+ "f1": 0.9500000000000001,
14
+ "tp": 19,
15
+ "fp": 2,
16
+ "fn": 0
17
+ },
18
+ "by_label": {
19
+ "PHONE_NUMBER": {
20
+ "precision": 0.9285714285714286,
21
+ "recall": 1.0,
22
+ "f1": 0.962962962962963,
23
+ "tp": 13,
24
+ "fp": 1,
25
+ "fn": 0
26
+ },
27
+ "PPSN": {
28
+ "precision": 0.8571428571428571,
29
+ "recall": 1.0,
30
+ "f1": 0.923076923076923,
31
+ "tp": 6,
32
+ "fp": 1,
33
+ "fn": 0
34
+ }
35
+ }
36
+ }
eval/q8_finance_boundary_repair_v1.json ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "models/irishcore-diffmask-135m-v1-rc6k-blend-0p30_onnx_q8",
3
+ "input": "eval/irish_finance_boundary_repair_v1.jsonl",
4
+ "loader_type": "token_span_onnx_q8",
5
+ "examples": 12,
6
+ "min_score": 0.5,
7
+ "iou_threshold": 0.5,
8
+ "elapsed_seconds": 0.0480724589433521,
9
+ "examples_per_second": 249.62317850519418,
10
+ "overall": {
11
+ "precision": 1.0,
12
+ "recall": 1.0,
13
+ "f1": 1.0,
14
+ "tp": 18,
15
+ "fp": 0,
16
+ "fn": 0
17
+ },
18
+ "by_label": {
19
+ "ACCOUNT_NUMBER": {
20
+ "precision": 1.0,
21
+ "recall": 1.0,
22
+ "f1": 1.0,
23
+ "tp": 2,
24
+ "fp": 0,
25
+ "fn": 0
26
+ },
27
+ "BANK_ROUTING_NUMBER": {
28
+ "precision": 1.0,
29
+ "recall": 1.0,
30
+ "f1": 1.0,
31
+ "tp": 2,
32
+ "fp": 0,
33
+ "fn": 0
34
+ },
35
+ "CREDIT_DEBIT_CARD": {
36
+ "precision": 1.0,
37
+ "recall": 1.0,
38
+ "f1": 1.0,
39
+ "tp": 2,
40
+ "fp": 0,
41
+ "fn": 0
42
+ },
43
+ "PASSPORT_NUMBER": {
44
+ "precision": 1.0,
45
+ "recall": 1.0,
46
+ "f1": 1.0,
47
+ "tp": 4,
48
+ "fp": 0,
49
+ "fn": 0
50
+ },
51
+ "PHONE_NUMBER": {
52
+ "precision": 1.0,
53
+ "recall": 1.0,
54
+ "f1": 1.0,
55
+ "tp": 4,
56
+ "fp": 0,
57
+ "fn": 0
58
+ },
59
+ "PPSN": {
60
+ "precision": 1.0,
61
+ "recall": 1.0,
62
+ "f1": 1.0,
63
+ "tp": 2,
64
+ "fp": 0,
65
+ "fn": 0
66
+ },
67
+ "SWIFT_BIC": {
68
+ "precision": 1.0,
69
+ "recall": 1.0,
70
+ "f1": 1.0,
71
+ "tp": 2,
72
+ "fp": 0,
73
+ "fn": 0
74
+ }
75
+ }
76
+ }
eval/q8_finance_irish_phone_passport_finance_v1.json ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "models/irishcore-diffmask-135m-v1-rc6k-blend-0p30_onnx_q8",
3
+ "input": "eval/irish_phone_passport_finance_v1.jsonl",
4
+ "loader_type": "token_span_onnx_q8",
5
+ "examples": 20,
6
+ "min_score": 0.5,
7
+ "iou_threshold": 0.5,
8
+ "elapsed_seconds": 0.07568231993354857,
9
+ "examples_per_second": 264.2625122691881,
10
+ "overall": {
11
+ "precision": 0.9615384615384616,
12
+ "recall": 1.0,
13
+ "f1": 0.9803921568627451,
14
+ "tp": 25,
15
+ "fp": 1,
16
+ "fn": 0
17
+ },
18
+ "by_label": {
19
+ "ACCOUNT_NUMBER": {
20
+ "precision": 0.6666666666666666,
21
+ "recall": 1.0,
22
+ "f1": 0.8,
23
+ "tp": 2,
24
+ "fp": 1,
25
+ "fn": 0
26
+ },
27
+ "BANK_ROUTING_NUMBER": {
28
+ "precision": 1.0,
29
+ "recall": 1.0,
30
+ "f1": 1.0,
31
+ "tp": 5,
32
+ "fp": 0,
33
+ "fn": 0
34
+ },
35
+ "CREDIT_DEBIT_CARD": {
36
+ "precision": 1.0,
37
+ "recall": 1.0,
38
+ "f1": 1.0,
39
+ "tp": 2,
40
+ "fp": 0,
41
+ "fn": 0
42
+ },
43
+ "PASSPORT_NUMBER": {
44
+ "precision": 1.0,
45
+ "recall": 1.0,
46
+ "f1": 1.0,
47
+ "tp": 6,
48
+ "fp": 0,
49
+ "fn": 0
50
+ },
51
+ "PHONE_NUMBER": {
52
+ "precision": 1.0,
53
+ "recall": 1.0,
54
+ "f1": 1.0,
55
+ "tp": 6,
56
+ "fp": 0,
57
+ "fn": 0
58
+ },
59
+ "PPSN": {
60
+ "precision": 1.0,
61
+ "recall": 1.0,
62
+ "f1": 1.0,
63
+ "tp": 2,
64
+ "fp": 0,
65
+ "fn": 0
66
+ },
67
+ "SWIFT_BIC": {
68
+ "precision": 1.0,
69
+ "recall": 1.0,
70
+ "f1": 1.0,
71
+ "tp": 2,
72
+ "fp": 0,
73
+ "fn": 0
74
+ }
75
+ }
76
+ }
eval/q8_gaelic_weak_ppsn_v1.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "models/irishcore-diffmask-135m-v1-rc6k-blend-0p30_onnx_q8",
3
+ "input": "eval/qa_feedback_ga_ppsn_weakctx_v1.jsonl",
4
+ "loader_type": "token_span_onnx_q8",
5
+ "examples": 2,
6
+ "min_score": 0.5,
7
+ "iou_threshold": 0.5,
8
+ "elapsed_seconds": 0.02947957592550665,
9
+ "examples_per_second": 67.84358109675307,
10
+ "overall": {
11
+ "precision": 1.0,
12
+ "recall": 1.0,
13
+ "f1": 1.0,
14
+ "tp": 2,
15
+ "fp": 0,
16
+ "fn": 0
17
+ },
18
+ "by_label": {
19
+ "PPSN": {
20
+ "precision": 1.0,
21
+ "recall": 1.0,
22
+ "f1": 1.0,
23
+ "tp": 2,
24
+ "fp": 0,
25
+ "fn": 0
26
+ }
27
+ }
28
+ }
eval/q8_hardening_exact_v1.json ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "models/irishcore-diffmask-135m-v1-rc6k-blend-0p30_onnx_q8",
3
+ "input": "eval/irish_dllm_hardening_exact_v1.jsonl",
4
+ "loader_type": "token_span_onnx_q8",
5
+ "examples": 14,
6
+ "min_score": 0.5,
7
+ "iou_threshold": 0.5,
8
+ "elapsed_seconds": 0.11147892102599144,
9
+ "examples_per_second": 125.58427971092296,
10
+ "overall": {
11
+ "precision": 0.9523809523809523,
12
+ "recall": 1.0,
13
+ "f1": 0.975609756097561,
14
+ "tp": 20,
15
+ "fp": 1,
16
+ "fn": 0
17
+ },
18
+ "by_label": {
19
+ "ACCOUNT_NUMBER": {
20
+ "precision": 0.5,
21
+ "recall": 1.0,
22
+ "f1": 0.6666666666666666,
23
+ "tp": 1,
24
+ "fp": 1,
25
+ "fn": 0
26
+ },
27
+ "BANK_ROUTING_NUMBER": {
28
+ "precision": 1.0,
29
+ "recall": 1.0,
30
+ "f1": 1.0,
31
+ "tp": 2,
32
+ "fp": 0,
33
+ "fn": 0
34
+ },
35
+ "CREDIT_DEBIT_CARD": {
36
+ "precision": 1.0,
37
+ "recall": 1.0,
38
+ "f1": 1.0,
39
+ "tp": 2,
40
+ "fp": 0,
41
+ "fn": 0
42
+ },
43
+ "EMAIL": {
44
+ "precision": 1.0,
45
+ "recall": 1.0,
46
+ "f1": 1.0,
47
+ "tp": 2,
48
+ "fp": 0,
49
+ "fn": 0
50
+ },
51
+ "FIRST_NAME": {
52
+ "precision": 1.0,
53
+ "recall": 1.0,
54
+ "f1": 1.0,
55
+ "tp": 1,
56
+ "fp": 0,
57
+ "fn": 0
58
+ },
59
+ "LAST_NAME": {
60
+ "precision": 1.0,
61
+ "recall": 1.0,
62
+ "f1": 1.0,
63
+ "tp": 1,
64
+ "fp": 0,
65
+ "fn": 0
66
+ },
67
+ "PHONE_NUMBER": {
68
+ "precision": 1.0,
69
+ "recall": 1.0,
70
+ "f1": 1.0,
71
+ "tp": 2,
72
+ "fp": 0,
73
+ "fn": 0
74
+ },
75
+ "POSTCODE": {
76
+ "precision": 1.0,
77
+ "recall": 1.0,
78
+ "f1": 1.0,
79
+ "tp": 3,
80
+ "fp": 0,
81
+ "fn": 0
82
+ },
83
+ "PPSN": {
84
+ "precision": 1.0,
85
+ "recall": 1.0,
86
+ "f1": 1.0,
87
+ "tp": 3,
88
+ "fp": 0,
89
+ "fn": 0
90
+ },
91
+ "SWIFT_BIC": {
92
+ "precision": 1.0,
93
+ "recall": 1.0,
94
+ "f1": 1.0,
95
+ "tp": 3,
96
+ "fp": 0,
97
+ "fn": 0
98
+ }
99
+ }
100
+ }
eval/q8_multilingual_ppsn_v1_all.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "models/irishcore-diffmask-135m-v1-rc6k-blend-0p30_onnx_q8",
3
+ "input": "eval/multilingual_ppsn_v1_all.jsonl",
4
+ "loader_type": "token_span_onnx_q8",
5
+ "examples": 168,
6
+ "min_score": 0.5,
7
+ "iou_threshold": 0.5,
8
+ "elapsed_seconds": 0.8391437649261206,
9
+ "examples_per_second": 200.20407351151675,
10
+ "overall": {
11
+ "precision": 0.8736842105263158,
12
+ "recall": 0.9880952380952381,
13
+ "f1": 0.9273743016759777,
14
+ "tp": 83,
15
+ "fp": 12,
16
+ "fn": 1
17
+ },
18
+ "by_label": {
19
+ "PPSN": {
20
+ "precision": 0.9325842696629213,
21
+ "recall": 0.9880952380952381,
22
+ "f1": 0.9595375722543353,
23
+ "tp": 83,
24
+ "fp": 6,
25
+ "fn": 1
26
+ }
27
+ }
28
+ }
eval/q8_runtime_profile_source.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "models/irishcore-diffmask-135m-v1-rc6k-blend-0p30_onnx_q8",
3
+ "input": "eval/runtime_profile_source.jsonl",
4
+ "loader_type": "token_span_onnx_q8",
5
+ "examples": 3223,
6
+ "min_score": 0.5,
7
+ "iou_threshold": 0.5,
8
+ "elapsed_seconds": 19.28253148100339,
9
+ "examples_per_second": 167.14610336175048,
10
+ "overall": {
11
+ "precision": 0.5172647257955315,
12
+ "recall": 0.21539329010431352,
13
+ "f1": 0.304140127388535,
14
+ "tp": 764,
15
+ "fp": 713,
16
+ "fn": 2783
17
+ },
18
+ "by_label": {
19
+ "PPSN": {
20
+ "precision": 0.7900723888314375,
21
+ "recall": 0.21539329010431352,
22
+ "f1": 0.3385024368630926,
23
+ "tp": 764,
24
+ "fp": 203,
25
+ "fn": 2783
26
+ }
27
+ }
28
+ }
eval/q8_user_raw_regression_cases_v1.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "models/irishcore-diffmask-135m-v1-rc6k-blend-0p30_onnx_q8",
3
+ "input": "eval/user_raw_regression_cases_v1.jsonl",
4
+ "loader_type": "token_span_onnx_q8",
5
+ "examples": 7,
6
+ "min_score": 0.5,
7
+ "iou_threshold": 0.5,
8
+ "elapsed_seconds": 0.04791205294895917,
9
+ "examples_per_second": 146.1010240462273,
10
+ "overall": {
11
+ "precision": 0.6,
12
+ "recall": 1.0,
13
+ "f1": 0.7499999999999999,
14
+ "tp": 3,
15
+ "fp": 2,
16
+ "fn": 0
17
+ },
18
+ "by_label": {
19
+ "PPSN": {
20
+ "precision": 0.75,
21
+ "recall": 1.0,
22
+ "f1": 0.8571428571428571,
23
+ "tp": 3,
24
+ "fp": 1,
25
+ "fn": 0
26
+ }
27
+ }
28
+ }
inference_mask.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import os
7
+
8
+ os.environ.setdefault("TRANSFORMERS_NO_TF", "1")
9
+ os.environ.setdefault("TRANSFORMERS_NO_FLAX", "1")
10
+ os.environ.setdefault("TRANSFORMERS_NO_TORCHVISION", "1")
11
+ os.environ["USE_TF"] = "0"
12
+ os.environ["USE_FLAX"] = "0"
13
+ os.environ["USE_TORCH"] = "1"
14
+
15
+ import torch
16
+ from transformers import AutoConfig
17
+
18
+ from common import (
19
+ boundary_label_thresholds_from_config,
20
+ decode_token_presence_segments,
21
+ label_max_span_tokens_from_config,
22
+ label_min_nonspace_chars_from_config,
23
+ label_names_from_config,
24
+ safe_auto_tokenizer,
25
+ token_extend_thresholds_from_config,
26
+ token_label_thresholds_from_config,
27
+ )
28
+ from multitask_model import IrishCoreTokenSpanModel
29
+
30
+
31
+ def replacement(label: str) -> str:
32
+ return f"[PII:{label}]"
33
+
34
+
35
+ def mask_text(text: str, spans: list[dict]) -> str:
36
+ out = text
37
+ for span in sorted(spans, key=lambda item: (item["start"], item["end"]), reverse=True):
38
+ out = out[: span["start"]] + replacement(span["label"]) + out[span["end"] :]
39
+ return out
40
+
41
+
42
+ def predict(text: str, model, tokenizer, min_score: float):
43
+ encoded = tokenizer(text, return_offsets_mapping=True, return_tensors="pt", truncation=True)
44
+ offsets = [tuple(item) for item in encoded.pop("offset_mapping")[0].tolist()]
45
+ device = next(model.parameters()).device
46
+ encoded = {key: value.to(device) for key, value in encoded.items()}
47
+ with torch.no_grad():
48
+ output = model(**encoded)
49
+ token_scores = torch.sigmoid(output.token_logits[0]).cpu().numpy()
50
+ start_scores = torch.sigmoid(output.start_logits[0]).cpu().numpy()
51
+ end_scores = torch.sigmoid(output.end_logits[0]).cpu().numpy()
52
+ label_names = label_names_from_config(model.config)
53
+ thresholds = token_label_thresholds_from_config(model.config, min_score)
54
+ extend_thresholds = token_extend_thresholds_from_config(model.config)
55
+ max_span_tokens = label_max_span_tokens_from_config(model.config)
56
+ min_nonspace_chars = label_min_nonspace_chars_from_config(model.config)
57
+ boundary_thresholds = boundary_label_thresholds_from_config(model.config)
58
+ spans = decode_token_presence_segments(
59
+ text,
60
+ offsets,
61
+ token_scores,
62
+ label_names,
63
+ min_score,
64
+ thresholds,
65
+ extend_thresholds,
66
+ max_span_tokens,
67
+ min_nonspace_chars,
68
+ boundary_thresholds,
69
+ start_scores=start_scores,
70
+ end_scores=end_scores,
71
+ )
72
+ for span in spans:
73
+ span["replacement"] = replacement(span["label"])
74
+ return spans
75
+
76
+
77
+ def main() -> None:
78
+ parser = argparse.ArgumentParser()
79
+ parser.add_argument("--model", required=True)
80
+ parser.add_argument("--text", required=True)
81
+ parser.add_argument("--min-score", type=float, default=0.5)
82
+ parser.add_argument("--device", choices=["auto", "cpu", "cuda"], default="auto")
83
+ parser.add_argument("--json", action="store_true")
84
+ args = parser.parse_args()
85
+
86
+ tokenizer = safe_auto_tokenizer(args.model)
87
+ config = AutoConfig.from_pretrained(args.model)
88
+ model = IrishCoreTokenSpanModel.from_pretrained(args.model, config=config)
89
+ if args.device == "auto":
90
+ device = "cuda" if torch.cuda.is_available() else "cpu"
91
+ else:
92
+ device = args.device
93
+ model.to(device)
94
+ model.eval()
95
+
96
+ spans = predict(args.text, model, tokenizer, args.min_score)
97
+ result = {
98
+ "model": args.model,
99
+ "backend": "transformers_token_span",
100
+ "min_score": args.min_score,
101
+ "spans": spans,
102
+ "masked_text": mask_text(args.text, spans),
103
+ }
104
+ if args.json:
105
+ print(json.dumps(result, indent=2, ensure_ascii=False))
106
+ else:
107
+ print(result["masked_text"])
108
+
109
+
110
+ if __name__ == "__main__":
111
+ main()
inference_mask_onnx.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import os
7
+
8
+ os.environ.setdefault("TRANSFORMERS_NO_TF", "1")
9
+ os.environ.setdefault("TRANSFORMERS_NO_FLAX", "1")
10
+ os.environ.setdefault("TRANSFORMERS_NO_TORCHVISION", "1")
11
+ os.environ["USE_TF"] = "0"
12
+ os.environ["USE_FLAX"] = "0"
13
+ os.environ["USE_TORCH"] = "1"
14
+
15
+ import numpy as np
16
+
17
+ from common import (
18
+ boundary_label_thresholds_from_config,
19
+ decode_token_presence_segments,
20
+ label_max_span_tokens_from_config,
21
+ label_min_nonspace_chars_from_config,
22
+ label_names_from_config,
23
+ load_onnx_session,
24
+ run_onnx_all,
25
+ token_extend_thresholds_from_config,
26
+ token_label_thresholds_from_config,
27
+ )
28
+
29
+
30
+ def replacement(label: str) -> str:
31
+ return f"[PII:{label}]"
32
+
33
+
34
+ def mask_text(text: str, spans: list[dict]) -> str:
35
+ out = text
36
+ for span in sorted(spans, key=lambda item: (item["start"], item["end"]), reverse=True):
37
+ out = out[: span["start"]] + replacement(span["label"]) + out[span["end"] :]
38
+ return out
39
+
40
+
41
+ def predict(text: str, session, tokenizer, config, min_score: float):
42
+ encoded = tokenizer(text, return_offsets_mapping=True, return_tensors="np", truncation=True)
43
+ offsets = [tuple(item) for item in encoded["offset_mapping"][0].tolist()]
44
+ token_logits, start_logits, end_logits = run_onnx_all(session, encoded)
45
+ token_scores = 1.0 / (1.0 + np.exp(-token_logits[0]))
46
+ start_scores = 1.0 / (1.0 + np.exp(-start_logits[0]))
47
+ end_scores = 1.0 / (1.0 + np.exp(-end_logits[0]))
48
+ label_names = label_names_from_config(config)
49
+ thresholds = token_label_thresholds_from_config(config, min_score)
50
+ extend_thresholds = token_extend_thresholds_from_config(config)
51
+ max_span_tokens = label_max_span_tokens_from_config(config)
52
+ min_nonspace_chars = label_min_nonspace_chars_from_config(config)
53
+ boundary_thresholds = boundary_label_thresholds_from_config(config)
54
+ spans = decode_token_presence_segments(
55
+ text,
56
+ offsets,
57
+ token_scores,
58
+ label_names,
59
+ min_score,
60
+ thresholds,
61
+ extend_thresholds,
62
+ max_span_tokens,
63
+ min_nonspace_chars,
64
+ boundary_thresholds,
65
+ start_scores=start_scores,
66
+ end_scores=end_scores,
67
+ )
68
+ for span in spans:
69
+ span["replacement"] = replacement(span["label"])
70
+ return spans
71
+
72
+
73
+ def main() -> None:
74
+ parser = argparse.ArgumentParser()
75
+ parser.add_argument("--model", required=True)
76
+ parser.add_argument("--text", required=True)
77
+ parser.add_argument("--min-score", type=float, default=0.5)
78
+ parser.add_argument("--json", action="store_true")
79
+ args = parser.parse_args()
80
+
81
+ session, tokenizer, config = load_onnx_session(args.model, onnx_file="model_quantized.onnx", onnx_subfolder="onnx")
82
+ spans = predict(args.text, session, tokenizer, config, args.min_score)
83
+ result = {
84
+ "model": args.model,
85
+ "backend": "onnx_token_span_q8",
86
+ "min_score": args.min_score,
87
+ "spans": spans,
88
+ "masked_text": mask_text(args.text, spans),
89
+ }
90
+ if args.json:
91
+ print(json.dumps(result, indent=2, ensure_ascii=False))
92
+ else:
93
+ print(result["masked_text"])
94
+
95
+
96
+ if __name__ == "__main__":
97
+ main()
model.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+ from typing import Optional
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+ from transformers import AutoConfig, AutoModel, PreTrainedModel
10
+ from transformers.utils import ModelOutput
11
+
12
+
13
+ def hidden_size_from_config(config) -> int:
14
+ return int(getattr(config, "hidden_size", getattr(config, "dim")))
15
+
16
+
17
+ @dataclass
18
+ class MultilabelSpanOutput(ModelOutput):
19
+ loss: Optional[torch.Tensor] = None
20
+ start_logits: Optional[torch.Tensor] = None
21
+ end_logits: Optional[torch.Tensor] = None
22
+
23
+
24
+ class IrishCoreSpanHeadModel(PreTrainedModel):
25
+ config_class = AutoConfig
26
+ base_model_prefix = "encoder"
27
+
28
+ def __init__(self, config):
29
+ super().__init__(config)
30
+ num_span_labels = int(getattr(config, "num_span_labels"))
31
+ self.encoder = AutoModel.from_config(config)
32
+ hidden_size = hidden_size_from_config(config)
33
+ dropout = float(getattr(config, "seq_classif_dropout", getattr(config, "dropout", 0.1)))
34
+ self.dropout = nn.Dropout(dropout)
35
+ self.start_classifier = nn.Linear(hidden_size, num_span_labels)
36
+ self.end_classifier = nn.Linear(hidden_size, num_span_labels)
37
+ pos_weight = float(getattr(config, "span_positive_weight", 6.0))
38
+ self.register_buffer("loss_pos_weight", torch.full((num_span_labels,), pos_weight), persistent=False)
39
+ self.post_init()
40
+
41
+ def forward(
42
+ self,
43
+ input_ids=None,
44
+ attention_mask=None,
45
+ token_type_ids=None,
46
+ start_positions=None,
47
+ end_positions=None,
48
+ token_mask=None,
49
+ **kwargs,
50
+ ) -> MultilabelSpanOutput:
51
+ encoder_kwargs = {
52
+ "input_ids": input_ids,
53
+ "attention_mask": attention_mask,
54
+ **kwargs,
55
+ }
56
+ if token_type_ids is not None and getattr(self.config, "model_type", "") not in {"distilbert", "roberta"}:
57
+ encoder_kwargs["token_type_ids"] = token_type_ids
58
+ outputs = self.encoder(**encoder_kwargs)
59
+ hidden = self.dropout(outputs.last_hidden_state)
60
+ start_logits = self.start_classifier(hidden)
61
+ end_logits = self.end_classifier(hidden)
62
+
63
+ loss = None
64
+ if start_positions is not None and end_positions is not None:
65
+ if token_mask is None:
66
+ token_mask = attention_mask
67
+ mask = token_mask.float().unsqueeze(-1)
68
+ pos_weight = self.loss_pos_weight.to(start_logits.device)
69
+ bce = nn.BCEWithLogitsLoss(reduction="none", pos_weight=pos_weight)
70
+ start_loss = bce(start_logits, start_positions.float()) * mask
71
+ end_loss = bce(end_logits, end_positions.float()) * mask
72
+ denom = mask.sum().clamp_min(1.0) * start_logits.shape[-1]
73
+ loss = (start_loss.sum() + end_loss.sum()) / (2.0 * denom)
74
+
75
+ return MultilabelSpanOutput(loss=loss, start_logits=start_logits, end_logits=end_logits)
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:50d5c48025ce05955cce8a480ce09b1051e55a363a58d73b124b89ff90774688
3
+ size 539050252
multitask_model.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+ import math
6
+ from typing import Optional
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ from transformers import AutoConfig, AutoModel, PreTrainedModel
11
+ from transformers.utils import ModelOutput
12
+
13
+ try:
14
+ from .model import hidden_size_from_config
15
+ except ImportError:
16
+ from model import hidden_size_from_config
17
+
18
+
19
+ @dataclass
20
+ class MultitaskSpanOutput(ModelOutput):
21
+ loss: Optional[torch.Tensor] = None
22
+ token_logits: Optional[torch.Tensor] = None
23
+ start_logits: Optional[torch.Tensor] = None
24
+ end_logits: Optional[torch.Tensor] = None
25
+
26
+
27
+ class IrishCoreTokenSpanModel(PreTrainedModel):
28
+ config_class = AutoConfig
29
+ base_model_prefix = "encoder"
30
+
31
+ def __init__(self, config):
32
+ super().__init__(config)
33
+ num_span_labels = int(getattr(config, "num_span_labels"))
34
+ self.encoder = AutoModel.from_config(config)
35
+ hidden_size = hidden_size_from_config(config)
36
+ dropout = float(getattr(config, "seq_classif_dropout", getattr(config, "dropout", 0.1)))
37
+ self.dropout = nn.Dropout(dropout)
38
+ self.token_classifier = nn.Linear(hidden_size, num_span_labels)
39
+ self.start_classifier = nn.Linear(hidden_size, num_span_labels)
40
+ self.end_classifier = nn.Linear(hidden_size, num_span_labels)
41
+ boundary_pos_weight = float(getattr(config, "span_positive_weight", 6.0))
42
+ presence_pos_weight = float(getattr(config, "token_positive_weight", 4.0))
43
+ self.register_buffer("boundary_pos_weight", torch.full((num_span_labels,), boundary_pos_weight), persistent=False)
44
+ self.register_buffer("presence_pos_weight", torch.full((num_span_labels,), presence_pos_weight), persistent=False)
45
+ self.post_init()
46
+
47
+ def forward(
48
+ self,
49
+ input_ids=None,
50
+ attention_mask=None,
51
+ token_type_ids=None,
52
+ token_labels=None,
53
+ start_positions=None,
54
+ end_positions=None,
55
+ token_mask=None,
56
+ **kwargs,
57
+ ) -> MultitaskSpanOutput:
58
+ encoder_kwargs = {
59
+ "input_ids": input_ids,
60
+ "attention_mask": attention_mask,
61
+ **kwargs,
62
+ }
63
+ if token_type_ids is not None and getattr(self.config, "model_type", "") not in {"distilbert", "roberta"}:
64
+ encoder_kwargs["token_type_ids"] = token_type_ids
65
+ outputs = self.encoder(**encoder_kwargs)
66
+ hidden = self.dropout(outputs.last_hidden_state)
67
+ token_logits = self.token_classifier(hidden)
68
+ start_logits = self.start_classifier(hidden)
69
+ end_logits = self.end_classifier(hidden)
70
+
71
+ loss = None
72
+ if token_labels is not None and start_positions is not None and end_positions is not None:
73
+ if token_mask is None:
74
+ token_mask = attention_mask
75
+ mask = token_mask.float().unsqueeze(-1)
76
+ boundary_pos_weight = self.boundary_pos_weight.to(token_logits.device)
77
+ presence_pos_weight = self.presence_pos_weight.to(token_logits.device)
78
+ bce_boundary = nn.BCEWithLogitsLoss(reduction="none", pos_weight=boundary_pos_weight)
79
+ bce_presence = nn.BCEWithLogitsLoss(reduction="none", pos_weight=presence_pos_weight)
80
+ token_targets = token_labels.float()
81
+ start_targets = start_positions.float()
82
+ end_targets = end_positions.float()
83
+ token_loss = bce_presence(token_logits, token_targets)
84
+ start_loss = bce_boundary(start_logits, start_targets)
85
+ end_loss = bce_boundary(end_logits, end_targets)
86
+ token_focal_gamma = float(getattr(self.config, "token_focal_gamma", getattr(self.config, "focal_gamma", 0.0)))
87
+ boundary_focal_gamma = float(getattr(self.config, "boundary_focal_gamma", getattr(self.config, "focal_gamma", 0.0)))
88
+ if token_focal_gamma > 0.0:
89
+ token_loss = apply_focal_weight(token_loss, token_logits, token_targets, token_focal_gamma)
90
+ if boundary_focal_gamma > 0.0:
91
+ start_loss = apply_focal_weight(start_loss, start_logits, start_targets, boundary_focal_gamma)
92
+ end_loss = apply_focal_weight(end_loss, end_logits, end_targets, boundary_focal_gamma)
93
+ token_hard_fraction = float(getattr(self.config, "token_hard_fraction", getattr(self.config, "hard_fraction", 1.0)))
94
+ boundary_hard_fraction = float(getattr(self.config, "boundary_hard_fraction", getattr(self.config, "hard_fraction", 1.0)))
95
+ token_loss = reduce_masked_loss(token_loss, mask, token_hard_fraction)
96
+ start_loss = reduce_masked_loss(start_loss, mask, boundary_hard_fraction)
97
+ end_loss = reduce_masked_loss(end_loss, mask, boundary_hard_fraction)
98
+ boundary_loss = 0.5 * (start_loss + end_loss)
99
+ token_weight = float(getattr(self.config, "token_presence_weight", 1.0))
100
+ boundary_weight = float(getattr(self.config, "boundary_loss_weight", 1.0))
101
+ loss = token_weight * token_loss + boundary_weight * boundary_loss
102
+
103
+ return MultitaskSpanOutput(
104
+ loss=loss,
105
+ token_logits=token_logits,
106
+ start_logits=start_logits,
107
+ end_logits=end_logits,
108
+ )
109
+
110
+
111
+ def apply_focal_weight(loss: torch.Tensor, logits: torch.Tensor, targets: torch.Tensor, gamma: float) -> torch.Tensor:
112
+ probs = torch.sigmoid(logits)
113
+ pt = probs * targets + (1.0 - probs) * (1.0 - targets)
114
+ return loss * (1.0 - pt).pow(gamma)
115
+
116
+
117
+ def reduce_masked_loss(loss: torch.Tensor, mask: torch.Tensor, hard_fraction: float) -> torch.Tensor:
118
+ expanded_mask = mask.expand_as(loss).bool()
119
+ masked = loss.masked_select(expanded_mask)
120
+ if masked.numel() == 0:
121
+ return loss.sum() * 0.0
122
+ if 0.0 < hard_fraction < 1.0:
123
+ keep = max(1, math.ceil(masked.numel() * hard_fraction))
124
+ masked = torch.topk(masked, keep).values
125
+ return masked.mean()
onnx/config.json ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation": "gelu",
3
+ "architectures": [
4
+ "IrishCoreTokenSpanModel"
5
+ ],
6
+ "attention_dropout": 0.1,
7
+ "boundary_focal_gamma": 2.0,
8
+ "boundary_hard_fraction": 0.25,
9
+ "boundary_label_thresholds": {
10
+ "ACCOUNT_NUMBER": 0.1,
11
+ "BANK_ROUTING_NUMBER": 0.25,
12
+ "CREDIT_DEBIT_CARD": 0.25,
13
+ "EMAIL": 0.2,
14
+ "FIRST_NAME": 0.1,
15
+ "LAST_NAME": 0.1,
16
+ "PASSPORT_NUMBER": 0.25,
17
+ "PHONE_NUMBER": 0.25,
18
+ "POSTCODE": 0.4,
19
+ "PPSN": 0.35,
20
+ "SWIFT_BIC": 0.25
21
+ },
22
+ "boundary_loss_weight": 1.0,
23
+ "decoder_profile": "rc3_focusv3_email_extend015_passport075",
24
+ "dim": 768,
25
+ "dropout": 0.1,
26
+ "dtype": "float32",
27
+ "hidden_dim": 3072,
28
+ "id2label": {
29
+ "0": "O",
30
+ "1": "B-account_number",
31
+ "2": "B-age",
32
+ "3": "B-api_key",
33
+ "4": "B-bank_routing_number",
34
+ "5": "B-biometric_identifier",
35
+ "6": "B-blood_type",
36
+ "7": "B-certificate_license_number",
37
+ "8": "B-city",
38
+ "9": "B-company_name",
39
+ "10": "B-coordinate",
40
+ "11": "B-country",
41
+ "12": "B-county",
42
+ "13": "B-credit_debit_card",
43
+ "14": "B-customer_id",
44
+ "15": "B-cvv",
45
+ "16": "B-date",
46
+ "17": "B-date_of_birth",
47
+ "18": "B-date_time",
48
+ "19": "B-device_identifier",
49
+ "20": "B-education_level",
50
+ "21": "B-email",
51
+ "22": "B-employee_id",
52
+ "23": "B-employment_status",
53
+ "24": "B-fax_number",
54
+ "25": "B-first_name",
55
+ "26": "B-gender",
56
+ "27": "B-health_plan_beneficiary_number",
57
+ "28": "B-http_cookie",
58
+ "29": "B-ipv4",
59
+ "30": "B-ipv6",
60
+ "31": "B-language",
61
+ "32": "B-last_name",
62
+ "33": "B-license_plate",
63
+ "34": "B-mac_address",
64
+ "35": "B-medical_record_number",
65
+ "36": "B-occupation",
66
+ "37": "B-password",
67
+ "38": "B-phone_number",
68
+ "39": "B-pin",
69
+ "40": "B-political_view",
70
+ "41": "B-postcode",
71
+ "42": "B-race_ethnicity",
72
+ "43": "B-religious_belief",
73
+ "44": "B-sexuality",
74
+ "45": "B-ssn",
75
+ "46": "B-state",
76
+ "47": "B-street_address",
77
+ "48": "B-swift_bic",
78
+ "49": "B-tax_id",
79
+ "50": "B-time",
80
+ "51": "B-unique_id",
81
+ "52": "B-url",
82
+ "53": "B-user_name",
83
+ "54": "B-vehicle_identifier",
84
+ "55": "I-account_number",
85
+ "56": "I-api_key",
86
+ "57": "I-biometric_identifier",
87
+ "58": "I-blood_type",
88
+ "59": "I-certificate_license_number",
89
+ "60": "I-city",
90
+ "61": "I-company_name",
91
+ "62": "I-coordinate",
92
+ "63": "I-country",
93
+ "64": "I-county",
94
+ "65": "I-credit_debit_card",
95
+ "66": "I-customer_id",
96
+ "67": "I-date",
97
+ "68": "I-date_of_birth",
98
+ "69": "I-date_time",
99
+ "70": "I-device_identifier",
100
+ "71": "I-education_level",
101
+ "72": "I-email",
102
+ "73": "I-employee_id",
103
+ "74": "I-employment_status",
104
+ "75": "I-fax_number",
105
+ "76": "I-first_name",
106
+ "77": "I-gender",
107
+ "78": "I-health_plan_beneficiary_number",
108
+ "79": "I-http_cookie",
109
+ "80": "I-ipv4",
110
+ "81": "I-ipv6",
111
+ "82": "I-language",
112
+ "83": "I-last_name",
113
+ "84": "I-license_plate",
114
+ "85": "I-mac_address",
115
+ "86": "I-medical_record_number",
116
+ "87": "I-occupation",
117
+ "88": "I-password",
118
+ "89": "I-phone_number",
119
+ "90": "I-pin",
120
+ "91": "I-political_view",
121
+ "92": "I-postcode",
122
+ "93": "I-race_ethnicity",
123
+ "94": "I-religious_belief",
124
+ "95": "I-sexuality",
125
+ "96": "I-ssn",
126
+ "97": "I-state",
127
+ "98": "I-street_address",
128
+ "99": "I-swift_bic",
129
+ "100": "I-tax_id",
130
+ "101": "I-time",
131
+ "102": "I-unique_id",
132
+ "103": "I-url",
133
+ "104": "I-user_name",
134
+ "105": "I-vehicle_identifier",
135
+ "106": "B-PPSN",
136
+ "107": "I-PPSN",
137
+ "108": "B-PASSPORT_NUMBER",
138
+ "109": "I-PASSPORT_NUMBER",
139
+ "110": "I-bank_routing_number"
140
+ },
141
+ "initializer_range": 0.02,
142
+ "label2id": {
143
+ "B-PASSPORT_NUMBER": 108,
144
+ "B-PPSN": 106,
145
+ "B-account_number": 1,
146
+ "B-age": 2,
147
+ "B-api_key": 3,
148
+ "B-bank_routing_number": 4,
149
+ "B-biometric_identifier": 5,
150
+ "B-blood_type": 6,
151
+ "B-certificate_license_number": 7,
152
+ "B-city": 8,
153
+ "B-company_name": 9,
154
+ "B-coordinate": 10,
155
+ "B-country": 11,
156
+ "B-county": 12,
157
+ "B-credit_debit_card": 13,
158
+ "B-customer_id": 14,
159
+ "B-cvv": 15,
160
+ "B-date": 16,
161
+ "B-date_of_birth": 17,
162
+ "B-date_time": 18,
163
+ "B-device_identifier": 19,
164
+ "B-education_level": 20,
165
+ "B-email": 21,
166
+ "B-employee_id": 22,
167
+ "B-employment_status": 23,
168
+ "B-fax_number": 24,
169
+ "B-first_name": 25,
170
+ "B-gender": 26,
171
+ "B-health_plan_beneficiary_number": 27,
172
+ "B-http_cookie": 28,
173
+ "B-ipv4": 29,
174
+ "B-ipv6": 30,
175
+ "B-language": 31,
176
+ "B-last_name": 32,
177
+ "B-license_plate": 33,
178
+ "B-mac_address": 34,
179
+ "B-medical_record_number": 35,
180
+ "B-occupation": 36,
181
+ "B-password": 37,
182
+ "B-phone_number": 38,
183
+ "B-pin": 39,
184
+ "B-political_view": 40,
185
+ "B-postcode": 41,
186
+ "B-race_ethnicity": 42,
187
+ "B-religious_belief": 43,
188
+ "B-sexuality": 44,
189
+ "B-ssn": 45,
190
+ "B-state": 46,
191
+ "B-street_address": 47,
192
+ "B-swift_bic": 48,
193
+ "B-tax_id": 49,
194
+ "B-time": 50,
195
+ "B-unique_id": 51,
196
+ "B-url": 52,
197
+ "B-user_name": 53,
198
+ "B-vehicle_identifier": 54,
199
+ "I-PASSPORT_NUMBER": 109,
200
+ "I-PPSN": 107,
201
+ "I-account_number": 55,
202
+ "I-api_key": 56,
203
+ "I-bank_routing_number": 110,
204
+ "I-biometric_identifier": 57,
205
+ "I-blood_type": 58,
206
+ "I-certificate_license_number": 59,
207
+ "I-city": 60,
208
+ "I-company_name": 61,
209
+ "I-coordinate": 62,
210
+ "I-country": 63,
211
+ "I-county": 64,
212
+ "I-credit_debit_card": 65,
213
+ "I-customer_id": 66,
214
+ "I-date": 67,
215
+ "I-date_of_birth": 68,
216
+ "I-date_time": 69,
217
+ "I-device_identifier": 70,
218
+ "I-education_level": 71,
219
+ "I-email": 72,
220
+ "I-employee_id": 73,
221
+ "I-employment_status": 74,
222
+ "I-fax_number": 75,
223
+ "I-first_name": 76,
224
+ "I-gender": 77,
225
+ "I-health_plan_beneficiary_number": 78,
226
+ "I-http_cookie": 79,
227
+ "I-ipv4": 80,
228
+ "I-ipv6": 81,
229
+ "I-language": 82,
230
+ "I-last_name": 83,
231
+ "I-license_plate": 84,
232
+ "I-mac_address": 85,
233
+ "I-medical_record_number": 86,
234
+ "I-occupation": 87,
235
+ "I-password": 88,
236
+ "I-phone_number": 89,
237
+ "I-pin": 90,
238
+ "I-political_view": 91,
239
+ "I-postcode": 92,
240
+ "I-race_ethnicity": 93,
241
+ "I-religious_belief": 94,
242
+ "I-sexuality": 95,
243
+ "I-ssn": 96,
244
+ "I-state": 97,
245
+ "I-street_address": 98,
246
+ "I-swift_bic": 99,
247
+ "I-tax_id": 100,
248
+ "I-time": 101,
249
+ "I-unique_id": 102,
250
+ "I-url": 103,
251
+ "I-user_name": 104,
252
+ "I-vehicle_identifier": 105,
253
+ "O": 0
254
+ },
255
+ "max_position_embeddings": 512,
256
+ "model_type": "distilbert",
257
+ "n_heads": 12,
258
+ "n_layers": 6,
259
+ "num_span_labels": 11,
260
+ "output_past": true,
261
+ "pad_token_id": 0,
262
+ "qa_dropout": 0.1,
263
+ "seq_classif_dropout": 0.2,
264
+ "sinusoidal_pos_embds": false,
265
+ "span_label_max_span_tokens": {
266
+ "ACCOUNT_NUMBER": 19,
267
+ "BANK_ROUTING_NUMBER": 6,
268
+ "CREDIT_DEBIT_CARD": 13,
269
+ "EMAIL": 16,
270
+ "FIRST_NAME": 5,
271
+ "LAST_NAME": 8,
272
+ "PASSPORT_NUMBER": 9,
273
+ "PHONE_NUMBER": 10,
274
+ "POSTCODE": 8,
275
+ "PPSN": 9,
276
+ "SWIFT_BIC": 8
277
+ },
278
+ "span_label_names": [
279
+ "ACCOUNT_NUMBER",
280
+ "BANK_ROUTING_NUMBER",
281
+ "CREDIT_DEBIT_CARD",
282
+ "EMAIL",
283
+ "FIRST_NAME",
284
+ "LAST_NAME",
285
+ "PASSPORT_NUMBER",
286
+ "PHONE_NUMBER",
287
+ "POSTCODE",
288
+ "PPSN",
289
+ "SWIFT_BIC"
290
+ ],
291
+ "span_label_thresholds": {
292
+ "ACCOUNT_NUMBER": 0.5,
293
+ "BANK_ROUTING_NUMBER": 0.5,
294
+ "CREDIT_DEBIT_CARD": 0.5,
295
+ "EMAIL": 0.5,
296
+ "FIRST_NAME": 0.5,
297
+ "LAST_NAME": 0.5,
298
+ "PASSPORT_NUMBER": 0.5,
299
+ "PHONE_NUMBER": 0.5,
300
+ "POSTCODE": 0.5,
301
+ "PPSN": 0.5,
302
+ "SWIFT_BIC": 0.5
303
+ },
304
+ "span_positive_weight": 6.0,
305
+ "tie_weights_": true,
306
+ "token_extend_thresholds": {
307
+ "ACCOUNT_NUMBER": 0.08,
308
+ "BANK_ROUTING_NUMBER": 0.3,
309
+ "CREDIT_DEBIT_CARD": 0.3,
310
+ "EMAIL": 0.15,
311
+ "FIRST_NAME": 0.3,
312
+ "LAST_NAME": 0.3,
313
+ "PASSPORT_NUMBER": 0.15,
314
+ "PHONE_NUMBER": 0.15,
315
+ "POSTCODE": 0.3,
316
+ "PPSN": 0.3,
317
+ "SWIFT_BIC": 0.3
318
+ },
319
+ "token_focal_gamma": 1.0,
320
+ "token_hard_fraction": 0.4,
321
+ "token_label_thresholds": {
322
+ "ACCOUNT_NUMBER": 0.18,
323
+ "BANK_ROUTING_NUMBER": 0.8,
324
+ "CREDIT_DEBIT_CARD": 0.8,
325
+ "EMAIL": 0.95,
326
+ "FIRST_NAME": 0.3,
327
+ "LAST_NAME": 0.4,
328
+ "PASSPORT_NUMBER": 0.75,
329
+ "PHONE_NUMBER": 0.65,
330
+ "POSTCODE": 0.9,
331
+ "PPSN": 0.7,
332
+ "SWIFT_BIC": 0.8
333
+ },
334
+ "token_positive_weight": 4.0,
335
+ "token_presence_weight": 1.0,
336
+ "transformers_version": "4.57.6",
337
+ "vocab_size": 119547
338
+ }
onnx/model.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eaa4cd93ce1f81d78c46f09a7813c88f5bc3447f4694a0ff8326f452d36e6b8d
3
+ size 539156462
onnx/model_quantized.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b62273cd056ccc4056e98d74133919492af0ddfc7acc29119ac7b7a06d50d6d6
3
+ size 411983965
onnx/onnx_export.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "source_model": "models/irishcore-diffmask-135m-v1-rc6k-blend-0p30",
3
+ "onnx_path": "tmp_rc6k_onnx/model.onnx",
4
+ "task": "multitask-token-span-extraction",
5
+ "opset": 18,
6
+ "max_length": 256,
7
+ "output_names": [
8
+ "token_logits",
9
+ "start_logits",
10
+ "end_logits"
11
+ ]
12
+ }
onnx/quantization.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "source_dir": "tmp_rc6k_onnx",
3
+ "input_model": "tmp_rc6k_q8/model.onnx",
4
+ "preprocessed_input_model": "",
5
+ "output_model": "tmp_rc6k_q8/model_quantized.onnx",
6
+ "weight_type": "qint8",
7
+ "per_channel": true,
8
+ "reduce_range": false,
9
+ "preprocess_applied": false,
10
+ "op_types": [
11
+ "MatMul",
12
+ "Gemm",
13
+ "Attention"
14
+ ],
15
+ "copied_assets": [
16
+ "tmp_rc6k_onnx/model.onnx",
17
+ "onnx_export.json",
18
+ "config.json",
19
+ "special_tokens_map.json",
20
+ "tokenizer.json",
21
+ "tokenizer_config.json",
22
+ "vocab.txt"
23
+ ],
24
+ "format": "onnx_dynamic_quantized",
25
+ "task": "token-classification"
26
+ }
onnx/special_tokens_map.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": {
3
+ "content": "[CLS]",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "mask_token": {
10
+ "content": "[MASK]",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "[PAD]",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "sep_token": {
24
+ "content": "[SEP]",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "unk_token": {
31
+ "content": "[UNK]",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ }
37
+ }
onnx/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
onnx/tokenizer_config.json ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "100": {
12
+ "content": "[UNK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "101": {
20
+ "content": "[CLS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "102": {
28
+ "content": "[SEP]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "103": {
36
+ "content": "[MASK]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": false,
45
+ "cls_token": "[CLS]",
46
+ "do_lower_case": false,
47
+ "extra_special_tokens": {},
48
+ "fix_mistral_regex": true,
49
+ "mask_token": "[MASK]",
50
+ "max_length": 512,
51
+ "model_max_length": 512,
52
+ "pad_to_multiple_of": null,
53
+ "pad_token": "[PAD]",
54
+ "pad_token_type_id": 0,
55
+ "padding_side": "right",
56
+ "sep_token": "[SEP]",
57
+ "stride": 0,
58
+ "strip_accents": null,
59
+ "tokenize_chinese_chars": true,
60
+ "tokenizer_class": "DistilBertTokenizer",
61
+ "truncation_side": "right",
62
+ "truncation_strategy": "longest_first",
63
+ "unk_token": "[UNK]"
64
+ }
onnx/vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
pyproject.toml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "irishcore-diffmask"
3
+ version = "0.1.0"
4
+ description = "IrishCore DiffMask token-span release with dynamic q8 ONNX export"
5
+ requires-python = ">=3.10"
6
+ readme = "README.md"
7
+ license = { text = "Apache-2.0" }
8
+ dependencies = [
9
+ "transformers>=4.41.0",
10
+ "torch",
11
+ "numpy>=1.26.0",
12
+ "onnxruntime>=1.20.0",
13
+ "huggingface_hub>=0.36.0",
14
+ ]
15
+
16
+ [tool.uv]
17
+ package = false
qa_config.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "release": "IrishCore-DiffMask-135M-v1-rc6",
3
+ "repo_id": "temsa/IrishCore-DiffMask-135M-v1-rc6",
4
+ "decoder": "raw_only_diffmask_token_span",
5
+ "diffusion_style_training": true,
6
+ "runtime_diffusion": false,
7
+ "min_score": 0.5,
8
+ "recommended_backend": "onnx_q8_cpu",
9
+ "onnx_file": "onnx/model_quantized.onnx",
10
+ "full_example": "My PPSN is 1234567TW, my Eircode is D02 X285, and my phone is 087 123 4567.",
11
+ "notes": [
12
+ "No scanner or validator layer is required for release behavior.",
13
+ "Use the bundled inference scripts or import common.decode_token_presence_segments.",
14
+ "The bundled scripts mask with [PII:LABEL] placeholders."
15
+ ]
16
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": {
3
+ "content": "[CLS]",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "mask_token": {
10
+ "content": "[MASK]",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "[PAD]",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "sep_token": {
24
+ "content": "[SEP]",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "unk_token": {
31
+ "content": "[UNK]",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ }
37
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "100": {
12
+ "content": "[UNK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "101": {
20
+ "content": "[CLS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "102": {
28
+ "content": "[SEP]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "103": {
36
+ "content": "[MASK]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": false,
45
+ "cls_token": "[CLS]",
46
+ "do_lower_case": false,
47
+ "extra_special_tokens": {},
48
+ "fix_mistral_regex": true,
49
+ "mask_token": "[MASK]",
50
+ "max_length": 512,
51
+ "model_max_length": 512,
52
+ "pad_to_multiple_of": null,
53
+ "pad_token": "[PAD]",
54
+ "pad_token_type_id": 0,
55
+ "padding_side": "right",
56
+ "sep_token": "[SEP]",
57
+ "stride": 0,
58
+ "strip_accents": null,
59
+ "tokenize_chinese_chars": true,
60
+ "tokenizer_class": "DistilBertTokenizer",
61
+ "truncation_side": "right",
62
+ "truncation_strategy": "longest_first",
63
+ "unk_token": "[UNK]"
64
+ }
training_sources.json ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "release": "IrishCore-DiffMask-135M-v1-rc6",
3
+ "base_model": "OpenMed/OpenMed-PII-mLiteClinical-Base-135M-v1",
4
+ "public_references": {
5
+ "rc5": "temsa/OpenMed-mLiteClinical-IrishCorePII-135M-v2-rc5",
6
+ "rc8": "temsa/OpenMed-mLiteClinical-IrishCorePII-135M-v2-rc8"
7
+ },
8
+ "task": "Irish core PII detection and masking in English and Irish Gaelic",
9
+ "coverage": [
10
+ "PPSN",
11
+ "ACCOUNT_NUMBER",
12
+ "BANK_ROUTING_NUMBER",
13
+ "CREDIT_DEBIT_CARD",
14
+ "PASSPORT_NUMBER",
15
+ "POSTCODE",
16
+ "PHONE_NUMBER",
17
+ "EMAIL",
18
+ "FIRST_NAME",
19
+ "LAST_NAME",
20
+ "SWIFT_BIC"
21
+ ],
22
+ "architecture": {
23
+ "family": "DistilBERT-size token-span extractor",
24
+ "diffusion_style_training": true,
25
+ "runtime_diffusion": false,
26
+ "scanner_free": true,
27
+ "validator_free": true,
28
+ "heads": [
29
+ "token_presence_head",
30
+ "typed_start_boundary_head",
31
+ "typed_end_boundary_head"
32
+ ]
33
+ },
34
+ "training_data": {
35
+ "published": [
36
+ "temsa/OpenMed-Irish-CorePII-TrainMix-v1",
37
+ "temsa/OpenMed-Irish-PPSN-Eircode-Spec-v1",
38
+ "joelniklaus/mapa",
39
+ "gretelai/synthetic_pii_finance_multilingual"
40
+ ],
41
+ "local_synthetic_hardening_sets": [
42
+ "irish_dllm_hardening_v1",
43
+ "dllm_gap_patch_v1",
44
+ "dllm_gap_patch_v2",
45
+ "dllm_gap_patch_v3",
46
+ "irish_core_diffmask_v2_mix",
47
+ "irish_core_diffmask_v3_mix",
48
+ "irish_core_diffmask_v4_mix"
49
+ ],
50
+ "selection_note": "The published checkpoint was selected from multiple continuation and interpolation runs to balance Irish core, multilingual PPSN, and hardening performance."
51
+ },
52
+ "training_recipe": {
53
+ "noise_schedule_family": "linear masked denoising schedule",
54
+ "runtime_diffusion": false,
55
+ "train_time_diffusion_steps": 4,
56
+ "start_noise_fraction": 0.65,
57
+ "end_noise_fraction": 0.05,
58
+ "loss": "average BCE losses over token presence and typed boundaries across noised passes"
59
+ },
60
+ "references": [
61
+ {
62
+ "title": "BERT",
63
+ "url": "https://arxiv.org/abs/1810.04805"
64
+ },
65
+ {
66
+ "title": "DistilBERT",
67
+ "url": "https://arxiv.org/abs/1910.01108"
68
+ },
69
+ {
70
+ "title": "Boundary Smoothing for Named Entity Recognition",
71
+ "url": "https://aclanthology.org/2022.acl-long.490/"
72
+ },
73
+ {
74
+ "title": "SPANNER: Named Entity Re-/Recognition as Span Prediction",
75
+ "url": "https://aclanthology.org/2021.acl-long.558/"
76
+ },
77
+ {
78
+ "title": "LLaDA 2.0: Scaling Up Diffusion Language Models to 100B",
79
+ "url": "https://arxiv.org/abs/2512.15745"
80
+ },
81
+ {
82
+ "title": "Scaling Diffusion Language Models via Adaptation from Autoregressive Models",
83
+ "url": "https://arxiv.org/abs/2410.17891"
84
+ }
85
+ ]
86
+ }
vocab.txt ADDED
The diff for this file is too large to render. See raw diff