brevitech commited on
Commit
590bec9
·
verified ·
1 Parent(s): 40e2a3e

Unmodified mirror of rbsriram/nullify-68m@12448353ecdd

Browse files
Files changed (10) hide show
  1. LICENSE +199 -0
  2. NOTICE +53 -0
  3. README.md +153 -0
  4. config.json +192 -0
  5. eval/piitrace_adapter.py +170 -0
  6. model.safetensors +3 -0
  7. nullify.py +357 -0
  8. onnx/model.onnx +3 -0
  9. tokenizer.json +0 -0
  10. tokenizer_config.json +21 -0
LICENSE ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this section, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim) in a lawsuit alleging that the Work
84
+ or any portion thereof infringes a patent, then You must stop
85
+ exercising any licenses granted here under.
86
+
87
+ 4. Redistribution. You may reproduce and distribute copies of the
88
+ Work or Derivative Works thereof in any medium, with or without
89
+ modifications, and in Source or Object form, provided that You
90
+ meet the following conditions:
91
+
92
+ (a) You must give any other recipients of the Work or
93
+ Derivative Works a copy of this License; and
94
+
95
+ (b) You must cause any modified files to carry prominent notices
96
+ stating that You changed the files; and
97
+
98
+ (c) You must retain, in the Source form of any Derivative Works
99
+ that You distribute, all copyright, patent, trademark, and
100
+ attribution notices from the Source form of the Work,
101
+ excluding those notices that do not pertain to any part of
102
+ the Derivative Works; and
103
+
104
+ (d) If the Work includes a "NOTICE" text file as part of its
105
+ distribution, then any Derivative Works that You distribute must
106
+ include a readable copy of the attribution notices contained
107
+ within such NOTICE file, excluding those notices that do not
108
+ pertain to any part of the Derivative Works, in at least one
109
+ of the following places: within a NOTICE text file distributed
110
+ as part of the Derivative Works; within the Source form or
111
+ documentation, if provided along with the Derivative Works; or,
112
+ within a display generated by the Derivative Works, if and
113
+ wherever such third-party notices normally appear. The contents
114
+ of the NOTICE file are for informational purposes only and
115
+ do not, within the notices, give attribution information to any
116
+ recipients, including Derivative Works. You may not use the
117
+ NOTICE file as a source of derivative works, and this paragraph
118
+ does not create any requirement to update or include
119
+ attribution notices in any Derivative Works, provided that the
120
+ NOTICE file is a file, and not merely a text file, and does not
121
+ include attribution information (other than incidental
122
+ attribution notices) that would otherwise be required to be
123
+ included in the NOTICE file.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work by
134
+ You to the Licensor shall be under the terms and conditions of this
135
+ License, notwithstanding the above, with the following addition:
136
+ that You may provide additional notices, disclaimers, or other
137
+ language to clearly indicate that no other contributor can
138
+ have any rights to the Submission.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for reasonable and customary use in describing the
143
+ origin of the Work and reproducing the content of the License.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides) "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
148
+ OF ANY KIND, either express or implied, including, without
149
+ limitation, any warranties or conditions of TITLE,
150
+ NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR
151
+ PURPOSE. You are entirely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your use of the Work and the exercise of
154
+ permissions under the License.
155
+
156
+ 8. Limitation of Liability. In no event and under no legal theory,
157
+ whether in tort (including negligence), contract, or otherwise,
158
+ unless required by applicable law (such as deliberate and grossly
159
+ negligent acts) or agreed to in writing, shall any Contributor be
160
+ liable for any incidental, indirect, special, consequential, or
161
+ exemplary damages, including, but not limited to, punitive
162
+ damages; reasonable attorney's fees; or for any loss or damages
163
+ arising out of the use or inability to use the Work or any
164
+ Derivative Works.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works, You can choose to accept this License
168
+ or additional liability as a condition of its reproduction or
169
+ distribution. By copying, modifying or otherwise using the Work or
170
+ Derivative Works, You accept and agree to be bound by the terms of
171
+ this License, and are not permitted to exercise any right or
172
+ remedies under the License.
173
+
174
+ END OF TERMS AND CONDITIONS
175
+
176
+ APPENDIX: How to apply the Apache License to your work.
177
+
178
+ To apply the Apache License to your work, attach the following
179
+ boilerplate notice, with the fields enclosed by brackets "[]"
180
+ replaced with your own identifying information. (Don't include
181
+ the brackets!) The text should be enclosed in the appropriate
182
+ comment syntax for the file format. We also recommend that a
183
+ file or class name and description of purpose be included on the
184
+ same "printed page" as the copyright notice for easier
185
+ identification within third-party archives.
186
+
187
+ Copyright [yyyy] [name of copyright owner]
188
+
189
+ Licensed under the Apache License, Version 2.0 (the "License");
190
+ you may not use this file except in compliance with the License.
191
+ You may obtain a copy of the License at
192
+
193
+ http://www.apache.org/licenses/LICENSE-2.0
194
+
195
+ Unless required by applicable law or agreed to in writing, software
196
+ distributed under the License is distributed on an "AS IS" BASIS,
197
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
198
+ See the License for the specific language governing permissions and
199
+ limitations under the License.
NOTICE ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Nullify 68M
2
+ Copyright 2026 Null Velocity
3
+
4
+ This model is licensed under the Apache License, Version 2.0 (see LICENSE).
5
+ It was built with the following third-party material.
6
+
7
+ Base model
8
+ ettin-encoder-68m, https://huggingface.co/jhu-clsp/ettin-encoder-68m
9
+ Licensed under the MIT License, as stated on its model card.
10
+ The model weights in this repository are a fine-tuned derivative of it.
11
+
12
+ Training data
13
+ Nemotron-PII by NVIDIA, https://huggingface.co/datasets/nvidia/Nemotron-PII
14
+ (revision b70ffaf5ff39e079776134c5bf4381f00a9fd1ed)
15
+ Licensed under Creative Commons Attribution 4.0 International (CC BY 4.0),
16
+ https://creativecommons.org/licenses/by/4.0/
17
+ Changes: examples were sampled, relabeled into this model's classes, and used for training.
18
+ The dataset itself is not redistributed here.
19
+
20
+ SPY, https://huggingface.co/datasets/mks-logic/SPY
21
+ Licensed under CC BY 4.0, as declared in its dataset card metadata.
22
+ Changes: examples were relabeled into this model's classes and used for training.
23
+ The dataset itself is not redistributed here.
24
+
25
+ gretel-pii-masking-en-v1 by Gretel, https://huggingface.co/datasets/gretelai/gretel-pii-masking-en-v1
26
+ Licensed under the Apache License, Version 2.0.
27
+ Changes: examples were relabeled into this model's classes and used for training.
28
+ The dataset itself is not redistributed here.
29
+
30
+ Software
31
+ nullify.py includes code written for this release. Its runtime dependencies
32
+ (numpy, tokenizers, huggingface_hub, and either torch with transformers or
33
+ onnxruntime) are installed separately under their own licences.
34
+
35
+ MIT License (applies to the base model ettin-encoder-68m)
36
+
37
+ Permission is hereby granted, free of charge, to any person obtaining a copy
38
+ of this software and associated documentation files (the "Software"), to deal
39
+ in the Software without restriction, including without limitation the rights
40
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
41
+ copies of the Software, and to permit persons to whom the Software is
42
+ furnished to do so, subject to the following conditions:
43
+
44
+ The above copyright notice and this permission notice shall be included in all
45
+ copies or substantial portions of the Software.
46
+
47
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
48
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
49
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
50
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
51
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
52
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
53
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ license: apache-2.0
5
+ base_model: jhu-clsp/ettin-encoder-68m
6
+ pipeline_tag: token-classification
7
+ library_name: generic
8
+ tags:
9
+ - brevitech
10
+ - mirror
11
+ - pii
12
+ - phi
13
+ - ner
14
+ - named-entity-recognition
15
+ - privacy
16
+ - redaction
17
+ - security
18
+ - onnx
19
+ - ettin
20
+ datasets:
21
+ - nvidia/Nemotron-PII
22
+ - gretelai/gretel-pii-masking-en-v1
23
+ - mks-logic/SPY
24
+ ---
25
+
26
+ # Nullify 68M — Brevitech Unmodified Mirror
27
+
28
+ > **Unmodified Mirror Notice:** Hosted by **Brevitech** (`brevitech`) as an unmodified mirror of [**`rbsriram/nullify-68m`**](https://huggingface.co/rbsriram/nullify-68m) (Copyright 2026 Null Velocity; base model `jhu-clsp/ettin-encoder-68m`) under the **Apache License 2.0**. Original `LICENSE`, `NOTICE`, weights, ONNX export, and `nullify.py` are preserved verbatim.
29
+
30
+ **Upstream repository:** `rbsriram/nullify-68m` (`12448353ecdd9806e8b2d67a981d757bcb3f5611`)
31
+
32
+ A 68-million-parameter model that identifies personal and sensitive information in text. It runs locally, in 8.5 ms per message on a laptop CPU, and returns the exact position of each span.
33
+
34
+ ## Quick start
35
+
36
+ ```bash
37
+ pip install numpy tokenizers huggingface_hub torch transformers # PyTorch backend
38
+ pip install numpy tokenizers huggingface_hub onnxruntime # or: ONNX backend, no PyTorch
39
+ ```
40
+
41
+ ```python
42
+ import sys
43
+ from huggingface_hub import snapshot_download
44
+
45
+ folder = snapshot_download("brevitech/nullify-68m")
46
+ sys.path.insert(0, folder)
47
+ from nullify import Nullify
48
+
49
+ nf = Nullify.from_pretrained(folder, backend="onnx") # omit backend to use PyTorch
50
+ text = ("Hi, this is Priya Raman from Acme Logistics. Call me on +1 415 555 0134 "
51
+ "or write to priya.raman@example.com about order 88213 before Friday.")
52
+
53
+ print(nf.mask(text))
54
+ # Hi, this is [PERSON] from [ORGANIZATION]. Call me on [PHONE] or write to [EMAIL] about order 88213 before Friday.
55
+
56
+ for span in nf.detect(text):
57
+ print(span["start"], span["end"], span["label"], span["text"])
58
+ # 12 23 PERSON Priya Raman
59
+ # 29 43 ORGANIZATION Acme Logistics
60
+ # 56 71 PHONE +1 415 555 0134
61
+ # 84 107 EMAIL priya.raman@example.com
62
+ ```
63
+
64
+ `detect` returns spans with `start`, `end` (half-open Unicode code-point offsets), `label`, `score`, and `text`. A given name and a family name next to each other come back as one `PERSON` span, with the parts under `parts`. `mask(text, profile="default")` leaves dates and places visible; `profile="all"` masks every class. Inputs longer than 1,024 tokens are processed in windows cut at line boundaries.
65
+
66
+ ## Results
67
+
68
+ | | Nullify 68M | PII-Tracer 0.6B | OpenAI Privacy Filter 1.5B | GLiNER2 PII 307M |
69
+ |---|---:|---:|---:|---:|
70
+ | Privacy-Bench, official F1 | **86.6** | 77.8 | 73.3 | 84.6 |
71
+ | PII-TRACE, exact-span F1, same post-processing for every system | 93.4 | **97.0** | 89.4 | 68.7 |
72
+ | PII-TRACE, exact-span F1, default output | 92.7 | | | |
73
+ | PII-TRACE, exact-span F1, raw output | 66.4 | 96.8 | 89.4 | 60.9 |
74
+ | PII-TRACE, clean conversations flagged (of 50, lower is better) | 21 | **5** | 9 | 21 |
75
+ | RedactionBench, R-Score, default setting | 0.539 | **0.601** | 0.536 | 0.445 |
76
+ | RedactionBench, R-Score, every class masked | 0.446 | | | |
77
+ | RedactionBench, 101 real documents, must-hide content hidden (default / every class) | 68.7% / 77.9% | | 69.3% | |
78
+
79
+ Batch size 1, float32, no threshold, one pass. Privacy-Bench and PII-TRACE: all four systems run by us. RedactionBench: our runs for Nullify and the OpenAI Privacy Filter (published: 0.533); the published leaderboard for PII-Tracer and GLiNER2 PII, where the authors tune a threshold on the benchmark for models that have one; Nullify uses none. PII-Tracer was built by the authors of PII-TRACE. PII-Tracer and the OpenAI Privacy Filter have no organization class, which Privacy-Bench counts. On PII-TRACE the scorer requires an exact span plus a matching label in its own label space (`private_person`, `account_number`, and so on). "Raw" reports the model's native labels unchanged: a person name comes out as `NAME_GIVEN` "Priya" plus `NAME_FAMILY` "Raman", so one `private_person` "Priya Raman" gold span counts as two misses. The shared post-processing pass maps every system's output to the benchmark's labels and span conventions, the same mapping `nullify.py` applies by default ([`eval/piitrace_adapter.py`](https://huggingface.co/rbsriram/nullify-68m/blob/main/eval/piitrace_adapter.py)) — which is why the same model scores 66.4 raw and 93.4 with shared mapping.
80
+
81
+ Published Privacy-Bench results, same scorer: Tonic Identity Synthesis 92.5, Tonic Textual 92.1, Claude Opus 5 88.3, Claude Sonnet 5 87.0, GPT-6 astra 86.8, GPT-5.6 sol 86.1, GPT-5.6 terra 84.8, Presidio 82.8, GLiNER2 75.1 in its authors' configuration.
82
+
83
+ Exact-span precision, recall, and F1 per class on our held-out test set (239 documents). `NAME_GIVEN` and `NAME_FAMILY` are the two halves of `PERSON` in default output.
84
+
85
+ | Class | Precision | Recall | F1 |
86
+ |---|---:|---:|---:|
87
+ | EMAIL | 97.6 | 100 | 98.8 |
88
+ | NAME_GIVEN | 98.3 | 98.8 | 98.6 |
89
+ | NAME_FAMILY | 97.6 | 98.2 | 97.9 |
90
+ | DATE | 100 | 95.5 | 97.7 |
91
+ | URL | 88.9 | 100 | 94.1 |
92
+ | ADDRESS | 94.7 | 90.0 | 92.3 |
93
+ | PHONE | 89.7 | 87.5 | 88.6 |
94
+ | IP | 84.6 | 88.0 | 86.3 |
95
+ | SECRET | 96.8 | 75.0 | 84.5 |
96
+ | USERNAME | 100 | 73.1 | 84.4 |
97
+ | LOCATION | 88.2 | 78.9 | 83.3 |
98
+ | ID | 59.3 | 95.2 | 73.1 |
99
+ | ORGANIZATION | 55.8 | 92.8 | 69.7 |
100
+
101
+ ## Classes and scope
102
+
103
+ | Masked by default | Visible by default |
104
+ |---|---|
105
+ | `PERSON` (from `NAME_GIVEN` and `NAME_FAMILY`), `EMAIL`, `PHONE`, `ADDRESS`, `ID`, `USERNAME`, `URL`, `IP`, `SECRET`, `ORGANIZATION` | `DATE`, `LOCATION` |
106
+
107
+ In scope: every string that reads as a person's name; company and brand names in any use; identifiers tied to a person, an account, a device, a vehicle, a bank, or a registry; credentials and keys; calendar dates; named places. Out of scope: departments and roles, generic nouns, product names that are not company names, operational references (order, invoice, shipment, ticket, SKU, part, and build numbers), public security identifiers, and version strings.
108
+
109
+ ## Speed and footprint
110
+
111
+ Apple M4 laptop, batch size 1, four CPU threads. Median 8.5 ms per message on the CPU with ONNX and 8.0 ms on the GPU with PyTorch (434 messages, median 39 tokens). A 1,024-token input takes 307 ms and 84 ms. 0.40 s from start to first result with ONNX. About 0.7 GB of memory on the CPU up to 1,024 tokens, 1.5 GB on the GPU. The ONNX file gives the same output as the PyTorch checkpoint on 1,931 test texts.
112
+
113
+ ## Model
114
+
115
+ Token classifier fine-tuned from [`jhu-clsp/ettin-encoder-68m`](https://huggingface.co/jhu-clsp/ettin-encoder-68m) with a 53-tag BIOES head over 13 classes, decoded with a constrained Viterbi pass (in `nullify.py`). Training ran on one MacBook Air.
116
+
117
+ ## Training data and licences
118
+
119
+ [Nemotron-PII](https://huggingface.co/datasets/nvidia/Nemotron-PII) (NVIDIA, CC BY 4.0), [gretel-pii-masking-en-v1](https://huggingface.co/datasets/gretelai/gretel-pii-masking-en-v1) (Gretel, Apache 2.0), [SPY](https://huggingface.co/datasets/mks-logic/SPY) (CC BY 4.0), and our own generated text with values from Faker and word lists. Attribution details are in `NOTICE`.
120
+
121
+ The model is released under the Apache 2.0 licence (`LICENSE`).
122
+
123
+ ## Intended use
124
+
125
+ A local filter in front of cloud LLM calls, redaction of business text, and a base for fine-tuning on an organization's own data.
126
+
127
+ It is not a guarantee of complete redaction. On 101 real documents in RedactionBench it hid 68.7% of must-hide content with the default classes and 77.9% with every class masked; the remaining gap needs a second pass, human review, or fine-tuning on your documents. Do not rely on it alone where a single missed span is unacceptable.
128
+
129
+ ## Files
130
+
131
+ | File | SHA256 |
132
+ |---|---|
133
+ | `model.safetensors` | `36b28fe7717cab1e0c758000459c96f92b8bbf7dcd10f022d911b6f1477e5083` |
134
+ | `onnx/model.onnx` | `dc9be21937983956c55235af106ed56f0730ffe6218245c63d9c5325b78543f2` |
135
+
136
+ ## Limitations
137
+
138
+ - Tested on English text only.
139
+ - Flags all personal names, including public figures.
140
+ - Less reliable on non-prose formats like source code, logs, and file listings.
141
+ - Can miss domain-specific entities or over-flag clean text without fine-tuning.
142
+
143
+ ## Citation
144
+
145
+ ```bibtex
146
+ @misc{nullvelocity2026nullify68m,
147
+ author = {Sriram},
148
+ title = {Nullify 68M: Fast Local PII Detection with Constrained Viterbi Decoding},
149
+ year = {2026},
150
+ publisher = {Hugging Face},
151
+ url = {https://huggingface.co/rbsriram/nullify-68m}
152
+ }
153
+ ```
config.json ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ModernBertForTokenClassification"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 50281,
8
+ "causal_mask": false,
9
+ "classifier_activation": "gelu",
10
+ "classifier_bias": false,
11
+ "classifier_dropout": 0.0,
12
+ "classifier_pooling": "mean",
13
+ "cls_token_id": 50281,
14
+ "decoder_bias": true,
15
+ "deterministic_flash_attn": false,
16
+ "dtype": "float32",
17
+ "embedding_dropout": 0.0,
18
+ "eos_token_id": 50282,
19
+ "global_attn_every_n_layers": 3,
20
+ "gradient_checkpointing": false,
21
+ "hidden_activation": "gelu",
22
+ "hidden_size": 512,
23
+ "id2label": {
24
+ "0": "O",
25
+ "1": "B-NAME_GIVEN",
26
+ "2": "I-NAME_GIVEN",
27
+ "3": "E-NAME_GIVEN",
28
+ "4": "S-NAME_GIVEN",
29
+ "5": "B-EMAIL",
30
+ "6": "I-EMAIL",
31
+ "7": "E-EMAIL",
32
+ "8": "S-EMAIL",
33
+ "9": "B-PHONE",
34
+ "10": "I-PHONE",
35
+ "11": "E-PHONE",
36
+ "12": "S-PHONE",
37
+ "13": "B-ADDRESS",
38
+ "14": "I-ADDRESS",
39
+ "15": "E-ADDRESS",
40
+ "16": "S-ADDRESS",
41
+ "17": "B-ID",
42
+ "18": "I-ID",
43
+ "19": "E-ID",
44
+ "20": "S-ID",
45
+ "21": "B-USERNAME",
46
+ "22": "I-USERNAME",
47
+ "23": "E-USERNAME",
48
+ "24": "S-USERNAME",
49
+ "25": "B-URL",
50
+ "26": "I-URL",
51
+ "27": "E-URL",
52
+ "28": "S-URL",
53
+ "29": "B-IP",
54
+ "30": "I-IP",
55
+ "31": "E-IP",
56
+ "32": "S-IP",
57
+ "33": "B-DATE",
58
+ "34": "I-DATE",
59
+ "35": "E-DATE",
60
+ "36": "S-DATE",
61
+ "37": "B-SECRET",
62
+ "38": "I-SECRET",
63
+ "39": "E-SECRET",
64
+ "40": "S-SECRET",
65
+ "41": "B-ORGANIZATION",
66
+ "42": "I-ORGANIZATION",
67
+ "43": "E-ORGANIZATION",
68
+ "44": "S-ORGANIZATION",
69
+ "45": "B-NAME_FAMILY",
70
+ "46": "I-NAME_FAMILY",
71
+ "47": "E-NAME_FAMILY",
72
+ "48": "S-NAME_FAMILY",
73
+ "49": "B-LOCATION",
74
+ "50": "I-LOCATION",
75
+ "51": "E-LOCATION",
76
+ "52": "S-LOCATION"
77
+ },
78
+ "initializer_cutoff_factor": 2.0,
79
+ "initializer_range": 0.02,
80
+ "intermediate_size": 768,
81
+ "is_causal": false,
82
+ "label2id": {
83
+ "B-ADDRESS": 13,
84
+ "B-DATE": 33,
85
+ "B-EMAIL": 5,
86
+ "B-ID": 17,
87
+ "B-IP": 29,
88
+ "B-LOCATION": 49,
89
+ "B-NAME_FAMILY": 45,
90
+ "B-NAME_GIVEN": 1,
91
+ "B-ORGANIZATION": 41,
92
+ "B-PHONE": 9,
93
+ "B-SECRET": 37,
94
+ "B-URL": 25,
95
+ "B-USERNAME": 21,
96
+ "E-ADDRESS": 15,
97
+ "E-DATE": 35,
98
+ "E-EMAIL": 7,
99
+ "E-ID": 19,
100
+ "E-IP": 31,
101
+ "E-LOCATION": 51,
102
+ "E-NAME_FAMILY": 47,
103
+ "E-NAME_GIVEN": 3,
104
+ "E-ORGANIZATION": 43,
105
+ "E-PHONE": 11,
106
+ "E-SECRET": 39,
107
+ "E-URL": 27,
108
+ "E-USERNAME": 23,
109
+ "I-ADDRESS": 14,
110
+ "I-DATE": 34,
111
+ "I-EMAIL": 6,
112
+ "I-ID": 18,
113
+ "I-IP": 30,
114
+ "I-LOCATION": 50,
115
+ "I-NAME_FAMILY": 46,
116
+ "I-NAME_GIVEN": 2,
117
+ "I-ORGANIZATION": 42,
118
+ "I-PHONE": 10,
119
+ "I-SECRET": 38,
120
+ "I-URL": 26,
121
+ "I-USERNAME": 22,
122
+ "O": 0,
123
+ "S-ADDRESS": 16,
124
+ "S-DATE": 36,
125
+ "S-EMAIL": 8,
126
+ "S-ID": 20,
127
+ "S-IP": 32,
128
+ "S-LOCATION": 52,
129
+ "S-NAME_FAMILY": 48,
130
+ "S-NAME_GIVEN": 4,
131
+ "S-ORGANIZATION": 44,
132
+ "S-PHONE": 12,
133
+ "S-SECRET": 40,
134
+ "S-URL": 28,
135
+ "S-USERNAME": 24
136
+ },
137
+ "layer_norm_eps": 1e-05,
138
+ "layer_types": [
139
+ "full_attention",
140
+ "sliding_attention",
141
+ "sliding_attention",
142
+ "full_attention",
143
+ "sliding_attention",
144
+ "sliding_attention",
145
+ "full_attention",
146
+ "sliding_attention",
147
+ "sliding_attention",
148
+ "full_attention",
149
+ "sliding_attention",
150
+ "sliding_attention",
151
+ "full_attention",
152
+ "sliding_attention",
153
+ "sliding_attention",
154
+ "full_attention",
155
+ "sliding_attention",
156
+ "sliding_attention",
157
+ "full_attention"
158
+ ],
159
+ "local_attention": 128,
160
+ "max_position_embeddings": 8192,
161
+ "mlp_bias": false,
162
+ "mlp_dropout": 0.0,
163
+ "model_type": "modernbert",
164
+ "norm_bias": false,
165
+ "norm_eps": 1e-05,
166
+ "num_attention_heads": 8,
167
+ "num_hidden_layers": 19,
168
+ "nv_init_scope": "Phase4b encoder only; fresh prediction head and 45-way classifier",
169
+ "nv_max_sequence_length": 8192,
170
+ "nv_requires_training": false,
171
+ "nv_tag_scheme": "BIOES-53",
172
+ "nv_text_window": 8190,
173
+ "pad_token_id": 50283,
174
+ "position_embedding_type": "sans_pos",
175
+ "rope_parameters": {
176
+ "full_attention": {
177
+ "rope_theta": 160000.0,
178
+ "rope_type": "default"
179
+ },
180
+ "sliding_attention": {
181
+ "rope_theta": 160000.0,
182
+ "rope_type": "default"
183
+ }
184
+ },
185
+ "sep_token_id": 50282,
186
+ "sparse_pred_ignore_index": -100,
187
+ "sparse_prediction": false,
188
+ "tie_word_embeddings": true,
189
+ "transformers_version": "5.21.0",
190
+ "vocab_size": 50368,
191
+ "_name_or_path": "jhu-clsp/ettin-encoder-68m"
192
+ }
eval/piitrace_adapter.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pinned PII-TRACE full-conversation retrospective evaluation.
2
+
3
+ All message text, including later turns, is model input. This track cannot test
4
+ causal online detection or prove context memory. Gold is kept outside text.
5
+ Native scoring uses exact Python Unicode offsets, without whitespace trimming.
6
+ """
7
+ from collections import Counter
8
+ from pathlib import Path
9
+
10
+ REVISION = '1c3eb67bbd43e8571b4433a9d3d76271f9970eb9'
11
+ DATA = Path(__file__).parent / 'data/external/piitrace/data/train.parquet'
12
+ NATIVE_TO_COMMON = {
13
+ 'private_person': 'PERSON', 'private_date': 'DATE', 'private_url': 'URL',
14
+ 'private_address': 'ADDRESS', 'account_number': 'ID',
15
+ 'private_email': 'EMAIL', 'private_phone': 'PHONE', 'other_pii': 'ID',
16
+ 'secret': 'SECRET',
17
+ }
18
+
19
+
20
+ def _offsets(start, end, length):
21
+ if type(start) is not int or type(end) is not int or not 0 <= start < end <= length:
22
+ raise ValueError('Expected nonempty integer Unicode interval inside message')
23
+
24
+
25
+ def build_document(row):
26
+ """Build reversible message ranges. Common labels are privacy diagnostics only."""
27
+ parts, ranges, index = [], [], {}
28
+ cursor = 0
29
+ for position, turn in enumerate(row['turns']):
30
+ if type(turn['turn']) is not int or turn['turn'] != position:
31
+ raise ValueError('Expected ordered zero-based native turn IDs')
32
+ for source in ('user', 'assistant'):
33
+ message = turn[source]
34
+ if not isinstance(message, str):
35
+ raise ValueError('Message must be a string')
36
+ delimiter = f'\n<<<TURN {position} ROLE {source}>>>\n'
37
+ parts.append(delimiter)
38
+ cursor += len(delimiter)
39
+ record = {'turn': position, 'source': source, 'start': cursor,
40
+ 'end': cursor + len(message)}
41
+ ranges.append(record)
42
+ index[position, source] = record
43
+ parts.append(message)
44
+ cursor += len(message)
45
+ text = ''.join(parts)
46
+ spans = []
47
+ native = []
48
+ for gold in row['spans']:
49
+ label = gold['label']
50
+ if label not in NATIVE_TO_COMMON:
51
+ raise ValueError(f'Unsupported native gold label: {label}')
52
+ region = index[gold['turn'], gold['source']]
53
+ _offsets(gold['start'], gold['end'], region['end'] - region['start'])
54
+ start, end = region['start'] + gold['start'], region['start'] + gold['end']
55
+ if text[start:end] != gold['text']:
56
+ raise ValueError('Native gold substring mismatch')
57
+ native.append(dict(gold))
58
+ spans.append({'start': start, 'end': end, 'category': NATIVE_TO_COMMON[label],
59
+ 'native_label': label, 'text': gold['text']})
60
+ return {'id': row['id'], 'text': text, 'spans': spans,
61
+ 'meta': {'conversation_id': row['id'], 'group_id': row['id'],
62
+ 'revision': REVISION, 'track': 'full-conversation-retrospective',
63
+ 'message_ranges': ranges, 'native_gold': native,
64
+ 'common_mapping_scope': 'privacy diagnostic only; other_pii -> ID is lossy'}}
65
+
66
+
67
+ def build_documents(path=None):
68
+ """Read every row. No train/dev split, row selection, or gold in model text."""
69
+ import pyarrow.parquet as pq
70
+ rows = pq.read_table(path or DATA).to_pylist()
71
+ documents = [build_document(row) for row in rows]
72
+ if len({doc['id'] for doc in documents}) != len(documents):
73
+ raise ValueError('Duplicate conversation IDs')
74
+ return documents
75
+
76
+
77
+ def map_predictions_to_messages(document, predictions):
78
+ """Return {spans, failures}; never silently discard unmappable spans.
79
+
80
+ Each valid output preserves all prediction fields, changes start/end to
81
+ message offsets, and adds native turn/source. Separator and crossing spans
82
+ are explicit failures. Callers must report failures with native scores.
83
+ """
84
+ mapped, failures = [], []
85
+ for position, prediction in enumerate(predictions):
86
+ try:
87
+ start, end = prediction['start'], prediction['end']
88
+ _offsets(start, end, len(document['text']))
89
+ regions = [r for r in document['meta']['message_ranges']
90
+ if r['start'] <= start < end <= r['end']]
91
+ if len(regions) != 1:
92
+ raise ValueError('Span crosses a message boundary or includes a separator')
93
+ region = regions[0]
94
+ mapped.append({**prediction, 'start': start - region['start'],
95
+ 'end': end - region['start'], 'turn': region['turn'],
96
+ 'source': region['source']})
97
+ except (KeyError, TypeError, ValueError) as exc:
98
+ failures.append({'prediction_index': position, 'prediction': prediction,
99
+ 'error': str(exc)})
100
+ return {'spans': mapped, 'failures': failures}
101
+
102
+
103
+ def _prf(tp, predicted, gold):
104
+ # Explicit zero convention, including empty controls. Macro includes all rows.
105
+ precision = tp / predicted if predicted else 0.0
106
+ recall = tp / gold if gold else 0.0
107
+ return {'tp': tp, 'predicted': predicted, 'gold': gold,
108
+ 'precision': precision, 'recall': recall,
109
+ 'f1': 2 * tp / (predicted + gold) if predicted + gold else 0.0}
110
+
111
+
112
+ def native_exact_scores(documents, predictions_by_id):
113
+ """Native micro, typed label macro, and conversation diagnostic metrics.
114
+
115
+ Predictions MUST use native message offsets and an explicitly projected
116
+ scalar native `label`. No common-to-native projection is inferred here.
117
+ Identical tuples deduplicate before one-to-one set intersection. Unsupported
118
+ predicted labels remain false positives for typed scoring and are reported.
119
+ No-gold/empty precision, recall, and F1 use zero in every macro average.
120
+ Typed label macro includes all nine known labels; unknown labels are excluded
121
+ from that macro, but remain micro false positives and unsupported counts.
122
+ Missing/extra IDs fail, rather than quietly changing benchmark membership.
123
+ """
124
+ if len({d['id'] for d in documents}) != len(documents):
125
+ raise ValueError('Duplicate conversation IDs')
126
+ if set(predictions_by_id) != {d['id'] for d in documents} or not documents:
127
+ raise ValueError('Predictions must include exactly all conversation IDs')
128
+ totals = {'typed': [0, 0, 0], 'untyped': [0, 0, 0]}
129
+ label_totals = {label: [0, 0, 0] for label in NATIVE_TO_COMMON}
130
+ per_document, unsupported = [], Counter()
131
+ for document in documents:
132
+ gold = document['meta']['native_gold']
133
+ predictions = predictions_by_id[document['id']]
134
+ regions = {(r['turn'], r['source']): r for r in document['meta']['message_ranges']}
135
+ for p in predictions:
136
+ region = regions[p['turn'], p['source']]
137
+ _offsets(p['start'], p['end'], region['end'] - region['start'])
138
+ if not isinstance(p['label'], str):
139
+ raise ValueError('Native prediction label must be a scalar string')
140
+ if p['label'] not in NATIVE_TO_COMMON:
141
+ unsupported[p['label']] += 1
142
+ record = {'id': document['id']}
143
+ for kind in totals:
144
+ fields = ('turn', 'source', 'start', 'end') + (('label',) if kind == 'typed' else ())
145
+ target = {tuple(s[k] for k in fields) for s in gold}
146
+ predicted = {tuple(s[k] for k in fields) for s in predictions}
147
+ if kind == 'typed':
148
+ for label in label_totals:
149
+ label_gold = {s for s in target if s[-1] == label}
150
+ label_pred = {s for s in predicted if s[-1] == label}
151
+ label_counts = (len(label_gold & label_pred), len(label_pred), len(label_gold))
152
+ label_totals[label] = [a + b for a, b in zip(label_totals[label], label_counts)]
153
+ counts = (len(target & predicted), len(predicted), len(target))
154
+ totals[kind] = [a + b for a, b in zip(totals[kind], counts)]
155
+ record[kind] = _prf(*counts)
156
+ per_document.append(record)
157
+ result = {'documents': len(documents), 'unsupported_labels': dict(unsupported),
158
+ 'deduplication': 'identical native tuples use set semantics',
159
+ 'macro_unit': 'conversation diagnostic, including empty controls; undefined ratios use zero',
160
+ 'label_macro_scope': 'typed exact; all nine known labels; undefined ratios use zero; unknown prediction labels excluded from label macro but retained as micro false positives',
161
+ 'per_document': per_document}
162
+ for kind in totals:
163
+ result[kind] = {'micro': _prf(*totals[kind]),
164
+ 'macro': {key: sum(row[kind][key] for row in per_document) / len(documents)
165
+ for key in ('precision', 'recall', 'f1')}}
166
+ result['typed']['per_label_counts'] = {label: _prf(*counts) for label, counts in label_totals.items()}
167
+ result['typed']['label_macro'] = {
168
+ key: sum(row[key] for row in result['typed']['per_label_counts'].values()) / len(label_totals)
169
+ for key in ('precision', 'recall', 'f1')}
170
+ return result
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:36b28fe7717cab1e0c758000459c96f92b8bbf7dcd10f022d911b6f1477e5083
3
+ size 273750236
nullify.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Nullify PII detection and masking, self-contained inference helper.
2
+
3
+ Backends:
4
+ "torch" (default): transformers AutoModelForTokenClassification, float32,
5
+ device cuda > mps > cpu.
6
+ "onnx": onnxruntime CPUExecutionProvider, 4 intra-op threads.
7
+ Both backends tokenize with tokenizers.Tokenizer.from_file("tokenizer.json")
8
+ and run the same constrained BIOES Viterbi decoder.
9
+
10
+ Long inputs are cut into non-overlapping windows of at most 1,024 tokens at
11
+ the last newline inside the budget; a single longer line is cut at the token
12
+ limit. Spans are shifted back to full-text offsets.
13
+
14
+ Usage:
15
+ from nullify import Nullify
16
+ nf = Nullify.from_pretrained("rbsriram/nullify-68m") # or local path
17
+ spans = nf.detect(text)
18
+ masked = nf.mask(text, profile="default") # "default" or "all"
19
+ """
20
+
21
+ import bisect
22
+ import json
23
+ import math
24
+ from pathlib import Path
25
+
26
+ import numpy as np
27
+
28
+ MAX_TOKENS = 1024
29
+ NAME_LABELS = frozenset(("NAME_GIVEN", "NAME_FAMILY"))
30
+ IDENTITY_DROP = frozenset(("DATE", "LOCATION"))
31
+
32
+
33
+ # ---- BIOES schema and constrained Viterbi (numpy path of bioes_decode_fast) ----
34
+
35
+ def _schema(tags):
36
+ tags = tuple(tags)
37
+ if len(set(tags)) != len(tags) or tags.count('O') != 1:
38
+ raise ValueError('Need one O and unique BIOES tags')
39
+ parsed = []
40
+ groups = {}
41
+ for tag in tags:
42
+ if tag == 'O':
43
+ parsed.append(('O', None))
44
+ continue
45
+ prefix, sep, kind = tag.partition('-')
46
+ if not sep or prefix not in ('B', 'I', 'E', 'S') or not kind:
47
+ raise ValueError('Invalid BIOES tag')
48
+ parsed.append((prefix, kind))
49
+ groups.setdefault(kind, set()).add(prefix)
50
+ if not groups or any(v != set('BIES') for v in groups.values()):
51
+ raise ValueError('Each category needs B, I, E, and S')
52
+ return parsed
53
+
54
+
55
+ def _legal_transition(left, right):
56
+ a, c = left
57
+ b, d = right
58
+ return (b in ('O', 'B', 'S')) if a in ('O', 'E', 'S') else (b in ('I', 'E') and c == d)
59
+
60
+
61
+ def _masks(parsed):
62
+ k = len(parsed)
63
+ full = np.zeros((k, k), dtype=bool)
64
+ for i, right in enumerate(parsed):
65
+ for j, left in enumerate(parsed):
66
+ full[j, i] = _legal_transition(left, right)
67
+ restricted = full.copy()
68
+ for i, (pi, ci) in enumerate(parsed):
69
+ for j, (pj, cj) in enumerate(parsed):
70
+ if restricted[j, i]:
71
+ restricted[j, i] = (pj == 'O' and pi == 'O') or (
72
+ pj in ('B', 'I') and pi in ('I', 'E') and cj == ci)
73
+ return full, restricted
74
+
75
+
76
+ _scheme_cache = {}
77
+
78
+
79
+ def _scheme(tags):
80
+ tags = tuple(tags)
81
+ if tags in _scheme_cache:
82
+ return _scheme_cache[tags]
83
+ parsed = _schema(tags)
84
+ first_ok = np.array([p in ('O', 'B', 'S') for p, _ in parsed], dtype=bool)
85
+ end_ok = np.array([p in ('O', 'E', 'S') for p, _ in parsed], dtype=bool)
86
+ full, restricted = _masks(parsed)
87
+ scheme = {'parsed': parsed, 'k': len(parsed), 'full': full,
88
+ 'restricted': restricted, 'first_ok': first_ok, 'end_ok': end_ok}
89
+ _scheme_cache[tags] = scheme
90
+ return scheme
91
+
92
+
93
+ def _viterbi(a, scheme, boundary_allowed):
94
+ """Hard-legal BIOES Viterbi forward pass, vectorized numpy.
95
+
96
+ First maximal legal predecessor wins ties (numpy argmax on ascending tag
97
+ index), matching the reference decoder.
98
+ """
99
+ neg = -math.inf
100
+ legal = np.where(scheme['full'], 0.0, neg)
101
+ legal_r = np.where(scheme['restricted'], 0.0, neg)
102
+ n, k = a.shape
103
+ if n == 0:
104
+ return []
105
+ previous = np.where(scheme['first_ok'], a[0], neg)
106
+ back = np.zeros((n - 1, k), dtype=np.intp)
107
+ for t in range(1, n):
108
+ masked = previous[:, None] + (legal if boundary_allowed[t - 1] else legal_r)
109
+ back[t - 1] = masked.argmax(axis=0)
110
+ previous = masked.max(axis=0) + a[t]
111
+ end = int(np.where(scheme['end_ok'], previous, neg).argmax())
112
+ path = [end]
113
+ for step in reversed(back):
114
+ path.append(int(step[path[-1]]))
115
+ return list(reversed(path))
116
+
117
+
118
+ def _snap_boundaries(text, span):
119
+ """Shift only outer whitespace inward, using exact source-character counts."""
120
+ start, end = span['start'], span['end']
121
+ raw = text[start:end]
122
+ stripped = raw.strip()
123
+ if not stripped:
124
+ return None
125
+ leading = len(raw) - len(raw.lstrip())
126
+ trailing = len(raw) - len(raw.rstrip())
127
+ snapped = {**span, 'start': start + leading, 'end': end - trailing, 'text': stripped}
128
+ assert text[snapped['start']:snapped['end']] == stripped
129
+ return snapped
130
+
131
+
132
+ def _decode(text, offsets, logits, tags, attention_mask, special_tokens_mask):
133
+ """Decode token logits into labeled character spans.
134
+
135
+ Span scores are the mean per-token softmax probability of the chosen tag
136
+ over the tokens inside the span (reference formula).
137
+ """
138
+ offsets = list(offsets)
139
+ n = len(offsets)
140
+ tags = tuple(tags)
141
+ scheme = _scheme(tags)
142
+ k = scheme['k']
143
+ if len(logits) != n:
144
+ raise ValueError('Offset/logit length mismatch')
145
+ active = []
146
+ for i, (offset, on, special) in enumerate(zip(offsets, attention_mask, special_tokens_mask)):
147
+ a, b = offset
148
+ if not on or special or (a, b) == (0, 0):
149
+ continue
150
+ active.append(i)
151
+ base = np.asarray(logits, dtype=np.float64)
152
+ rows_arr = np.ascontiguousarray(base[active]) if active else np.empty((0, k))
153
+ rows = [base[i] for i in active]
154
+ boundary_allowed = [offsets[right][0] >= offsets[left][1]
155
+ for left, right in zip(active, active[1:])]
156
+ path = _viterbi(rows_arr, scheme, boundary_allowed)
157
+ result = []
158
+ start = None
159
+ kind = None
160
+ values = []
161
+ for j, index in enumerate(path):
162
+ tag = tags[index]
163
+ prefix, label = ('O', None) if tag == 'O' else tag.split('-', 1)
164
+ if prefix in ('B', 'S'):
165
+ start = offsets[active[j]][0]
166
+ kind = label
167
+ values = []
168
+ if prefix != 'O':
169
+ row = list(map(float, rows[j]))
170
+ peak = max(row)
171
+ den = sum(math.exp(v - peak) for v in row)
172
+ values.append(math.exp(row[index] - peak) / den)
173
+ if prefix in ('E', 'S'):
174
+ span = {'start': start, 'end': offsets[active[j]][1], 'label': kind,
175
+ 'score': sum(values) / len(values)}
176
+ snapped = _snap_boundaries(text, span)
177
+ if snapped is not None:
178
+ result.append(snapped)
179
+ start = None
180
+ kind = None
181
+ values = []
182
+ return result
183
+
184
+
185
+ # ---- PERSON join (joined mode of sota_name_output.format_spans) ----
186
+
187
+ def _join_person(text, spans):
188
+ """Merge overlapping, touching, or whitespace-separated name intervals into
189
+ PERSON spans. Other spans stay unchanged. PERSON score is the minimum
190
+ component score (None if any component score is unknown)."""
191
+ names = sorted((s for s in spans if s['label'] in NAME_LABELS),
192
+ key=lambda s: (s['start'], s['end']))
193
+ groups = []
194
+ for span in names:
195
+ if groups and (span['start'] <= groups[-1]['end']
196
+ or text[groups[-1]['end']:span['start']].isspace()):
197
+ groups[-1]['end'] = max(groups[-1]['end'], span['end'])
198
+ groups[-1]['components'].append(span)
199
+ else:
200
+ groups.append({'start': span['start'], 'end': span['end'],
201
+ 'components': [span]})
202
+ output = [s for s in spans if s['label'] not in NAME_LABELS]
203
+ for group in groups:
204
+ values = [s.get('score') for s in group['components']]
205
+ output.append({'start': group['start'], 'end': group['end'], 'label': 'PERSON',
206
+ 'text': text[group['start']:group['end']],
207
+ 'score': min(values) if all(v is not None for v in values) else None,
208
+ 'parts': group['components']})
209
+ return sorted(output, key=lambda s: (s['start'], s['end'], s['label']))
210
+
211
+
212
+ # ---- Windowing (same rule as redactionbench_predict.cut_windows) ----
213
+
214
+ def _cut_windows(text, offsets, max_tokens=MAX_TOKENS):
215
+ """Non-overlapping windows of at most max_tokens tokens over the whole
216
+ encoding (special tokens included). Cuts land at the last newline inside
217
+ the budget; a single longer line is cut at the token limit.
218
+ Returns [(char_start, char_end, token_start, token_end)] covering text."""
219
+ n = len(offsets)
220
+ starts = [s for s, _ in offsets]
221
+ windows = []
222
+ i = 0
223
+ while i < n:
224
+ e = min(i + max_tokens, n)
225
+ if e < n:
226
+ newline = text.rfind("\n", offsets[i][0], offsets[e][0])
227
+ if newline != -1:
228
+ cut = bisect.bisect_right(starts, newline)
229
+ if cut > i:
230
+ e = cut
231
+ char_start = offsets[i][0]
232
+ char_end = offsets[e][0] if e < n else len(text)
233
+ windows.append((char_start, char_end, i, e))
234
+ i = e
235
+ if not windows and n == 0:
236
+ windows.append((0, len(text), 0, 0))
237
+ return windows
238
+
239
+
240
+ class Nullify:
241
+ """PII detector. Load with Nullify.from_pretrained(...)."""
242
+
243
+ def __init__(self, folder, backend="torch"):
244
+ self.folder = Path(folder)
245
+ self.backend = backend
246
+ config = json.loads((self.folder / 'config.json').read_text())
247
+ id2label = config['id2label']
248
+ self.tags = tuple(id2label[str(i)] for i in range(len(id2label)))
249
+ _scheme(self.tags) # validate tag scheme eagerly
250
+ from tokenizers import Tokenizer
251
+ self._tokenizer = Tokenizer.from_file(str(self.folder / 'tokenizer.json'))
252
+ self._tokenizer.no_padding()
253
+ self._tokenizer.no_truncation()
254
+ if backend == "torch":
255
+ import torch
256
+ from transformers import AutoModelForTokenClassification
257
+ if torch.cuda.is_available():
258
+ device = torch.device("cuda")
259
+ elif torch.backends.mps.is_available():
260
+ device = torch.device("mps")
261
+ else:
262
+ device = torch.device("cpu")
263
+ self._device = device
264
+ self._torch = torch
265
+ self._model = AutoModelForTokenClassification.from_pretrained(
266
+ str(self.folder), dtype=torch.float32).eval().to(device)
267
+ elif backend == "onnx":
268
+ import onnxruntime as ort
269
+ options = ort.SessionOptions()
270
+ options.intra_op_num_threads = 4
271
+ options.inter_op_num_threads = 1
272
+ self._session = ort.InferenceSession(
273
+ str(self.folder / 'onnx' / 'model.onnx'), options,
274
+ providers=['CPUExecutionProvider'])
275
+ else:
276
+ raise ValueError('backend must be "torch" or "onnx"')
277
+
278
+ @classmethod
279
+ def from_pretrained(cls, src, backend="torch"):
280
+ """Load from a local folder path, or a Hugging Face repo id."""
281
+ if Path(str(src)).exists():
282
+ folder = Path(str(src))
283
+ else:
284
+ from huggingface_hub import snapshot_download
285
+ folder = Path(snapshot_download(repo_id=str(src)))
286
+ return cls(folder, backend=backend)
287
+
288
+ def _encode(self, text):
289
+ e = self._tokenizer.encode(text)
290
+ return (list(e.ids), list(e.attention_mask),
291
+ list(e.special_tokens_mask), [tuple(p) for p in e.offsets])
292
+
293
+ def _forward(self, ids, mask):
294
+ if self.backend == "onnx":
295
+ logits = self._session.run(
296
+ ['logits'], {'input_ids': np.asarray([ids], dtype=np.int64),
297
+ 'attention_mask': np.asarray([mask], dtype=np.int64)})[0][0]
298
+ return np.asarray(logits, dtype=np.float32)
299
+ torch = self._torch
300
+ with torch.inference_mode():
301
+ out = self._model(
302
+ input_ids=torch.tensor([ids], dtype=torch.long, device=self._device),
303
+ attention_mask=torch.tensor([mask], dtype=torch.long, device=self._device))
304
+ return out.logits[0].float().cpu().numpy()
305
+
306
+ def _parts(self, text):
307
+ """Raw labeled spans (parts mode): decode every window, shift offsets
308
+ back to full-text coordinates, verify every span's text."""
309
+ ids, mask, special, offsets = self._encode(text)
310
+ spans = []
311
+ for char_start, char_end, tok_start, tok_end in _cut_windows(text, offsets):
312
+ w_ids = ids[tok_start:tok_end]
313
+ w_mask = mask[tok_start:tok_end]
314
+ w_special = special[tok_start:tok_end]
315
+ w_offsets = [(a - char_start, b - char_start)
316
+ for a, b in offsets[tok_start:tok_end]]
317
+ w_text = text[char_start:char_end]
318
+ logits = self._forward(w_ids, w_mask)
319
+ for span in _decode(w_text, w_offsets, logits, self.tags, w_mask, w_special):
320
+ shifted = {**span,
321
+ 'start': span['start'] + char_start,
322
+ 'end': span['end'] + char_start}
323
+ if text[shifted['start']:shifted['end']] != w_text[span['start']:span['end']]:
324
+ raise ValueError('Window offset shift failed')
325
+ shifted['text'] = text[shifted['start']:shifted['end']]
326
+ spans.append(shifted)
327
+ return sorted(spans, key=lambda s: (s['start'], s['end'], s['label']))
328
+
329
+ def detect(self, text, name_output="person"):
330
+ """Detect PII spans. Returns dicts with start, end, label, score, text;
331
+ joined person spans carry label PERSON plus 'parts' (component spans).
332
+ name_output="parts" returns the raw NAME_GIVEN/NAME_FAMILY spans."""
333
+ spans = self._parts(text)
334
+ if name_output == "parts":
335
+ return [{k: v for k, v in s.items()} for s in spans]
336
+ if name_output != "person":
337
+ raise ValueError('name_output must be "person" or "parts"')
338
+ return _join_person(text, spans)
339
+
340
+ def mask(self, text, profile="default"):
341
+ """Replace detected spans with "[LABEL]".
342
+ profile="default" leaves DATE and LOCATION visible; "all" masks every
343
+ class."""
344
+ if profile not in ("default", "all"):
345
+ raise ValueError('profile must be "default" or "all"')
346
+ drop = frozenset() if profile == "all" else IDENTITY_DROP
347
+ spans = [s for s in self.detect(text) if s['label'] not in drop]
348
+ out = []
349
+ pos = 0
350
+ for span in sorted(spans, key=lambda s: s['start']):
351
+ if span['start'] < pos:
352
+ continue
353
+ out.append(text[pos:span['start']])
354
+ out.append(f"[{span['label']}]")
355
+ pos = span['end']
356
+ out.append(text[pos:])
357
+ return ''.join(out)
onnx/model.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dc9be21937983956c55235af106ed56f0730ffe6218245c63d9c5325b78543f2
3
+ size 274268809
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "clean_up_tokenization_spaces": true,
4
+ "cls_token": "[CLS]",
5
+ "is_local": true,
6
+ "local_files_only": true,
7
+ "mask_token": "[MASK]",
8
+ "max_length": 8192,
9
+ "model_input_names": [
10
+ "input_ids",
11
+ "attention_mask"
12
+ ],
13
+ "model_max_length": 8192,
14
+ "pad_token": "[PAD]",
15
+ "sep_token": "[SEP]",
16
+ "stride": 0,
17
+ "tokenizer_class": "TokenizersBackend",
18
+ "truncation_side": "right",
19
+ "truncation_strategy": "longest_first",
20
+ "unk_token": "[UNK]"
21
+ }