Instructions to use SlayerLab/NERGAL with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use SlayerLab/NERGAL with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("token-classification", model="SlayerLab/NERGAL")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForTokenClassification tokenizer = AutoTokenizer.from_pretrained("SlayerLab/NERGAL") model = AutoModelForTokenClassification.from_pretrained("SlayerLab/NERGAL", device_map="auto") - Notebooks
- Google Colab
- Kaggle
2.0.0: opt-in FastPDN person names (names/, CC-BY-4.0)
Browse filesCo-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- hybrid.json +18 -0
- names/NOTICE.md +29 -0
- names/config.json +60 -0
- names/model.safetensors +3 -0
- names/tokenizer.json +3 -0
- nergal.py +84 -16
- test_nergal.py +64 -0
hybrid.json
CHANGED
|
@@ -46,5 +46,23 @@
|
|
| 46 |
"backbone": {
|
| 47 |
"repo": "FacebookAI/xlm-roberta-large",
|
| 48 |
"revision": "c23d21b0620b635a76227c604d44e43a9f0ee389"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
}
|
| 50 |
}
|
|
|
|
| 46 |
"backbone": {
|
| 47 |
"repo": "FacebookAI/xlm-roberta-large",
|
| 48 |
"revision": "c23d21b0620b635a76227c604d44e43a9f0ee389"
|
| 49 |
+
},
|
| 50 |
+
"names": {
|
| 51 |
+
"repo": "ArkadiuszPawlak/fastpdn-ner-polish-pii",
|
| 52 |
+
"revision": "636c57fe77b0afad8f065e7c76243dc051437035",
|
| 53 |
+
"license": "CC-BY-4.0",
|
| 54 |
+
"max_length": 512,
|
| 55 |
+
"stride": 128,
|
| 56 |
+
"dtype": "float32",
|
| 57 |
+
"decode": "argmax, union over windows, expanded to whole words",
|
| 58 |
+
"converted_from": {
|
| 59 |
+
"model.onnx": "11924bfd20eb478ee614e5e1184536825db4747753d341af7c04b940efa84645",
|
| 60 |
+
"convert.py": "a698bc993b253fc70d960aa14af37a5088afb79c77dae70557c7056ce394333e"
|
| 61 |
+
},
|
| 62 |
+
"sha256": {
|
| 63 |
+
"config.json": "3cef51cd7d184478adbdec9f68730db279386fe145cb32473a0622edea923578",
|
| 64 |
+
"model.safetensors": "2fa84ec6abd0c1b12ba0ba1548e89c9fca36fc58f03e66074db423b0e98ec8e6",
|
| 65 |
+
"tokenizer.json": "3a690c2d605076ad3901d946d4c0145fbfb19fef2f01370c7388430aa9f31edf"
|
| 66 |
+
}
|
| 67 |
}
|
| 68 |
}
|
names/NOTICE.md
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# names/: FastPDN NER — Polish PII
|
| 2 |
+
|
| 3 |
+
- Source: [ArkadiuszPawlak/fastpdn-ner-polish-pii](https://huggingface.co/ArkadiuszPawlak/fastpdn-ner-polish-pii),
|
| 4 |
+
revision `636c57fe77b0afad8f065e7c76243dc051437035`.
|
| 5 |
+
- License: [CC-BY-4.0](https://creativecommons.org/licenses/by/4.0/).
|
| 6 |
+
- Attribution: "FastPDN NER — Polish PII (ONNX)" by ArkadiuszPawlak, fine-tuned from
|
| 7 |
+
[clarin-pl/FastPDN](https://huggingface.co/clarin-pl/FastPDN) on filtered KPWr
|
| 8 |
+
([clarin-pl/kpwr-ner](https://huggingface.co/datasets/clarin-pl/kpwr-ner)) plus LLM-synthetic data.
|
| 9 |
+
Upstream model card README.md sha256 `9ca776b1157e5dedfb9d404ee17a584ebfc80f4dc426beb68f69200a52522c6f`.
|
| 10 |
+
|
| 11 |
+
## Changes
|
| 12 |
+
|
| 13 |
+
- `config.json` and `tokenizer.json` unchanged.
|
| 14 |
+
- `model.safetensors` is upstream `model.onnx` (FP32, sha256
|
| 15 |
+
`11924bfd20eb478ee614e5e1184536825db4747753d341af7c04b940efa84645`) converted by `convert.py` (sha256
|
| 16 |
+
`a698bc993b253fc70d960aa14af37a5088afb79c77dae70557c7056ce394333e`): 199 tensors copied, 73 linear weights
|
| 17 |
+
transposed from ONNX [in, out] to torch [out, in], no value changed.
|
| 18 |
+
- Review Gate 14, on 1,000 documents (1,714 windows, 614,466 tokens): torch FP32 against ONNX Runtime FP32, max
|
| 19 |
+
absolute logit difference 3.4e-4 (within 1e-3), every token's argmax identical, every person range identical.
|
| 20 |
+
- NERGAL uses only the PERSON, PERSON_F and PERSON_L tags, masked as `[PERSON]`.
|
| 21 |
+
|
| 22 |
+
## Files
|
| 23 |
+
|
| 24 |
+
| File | sha256 |
|
| 25 |
+
|---|---|
|
| 26 |
+
| `config.json` | `3cef51cd7d184478adbdec9f68730db279386fe145cb32473a0622edea923578` |
|
| 27 |
+
| `model.safetensors` | `2fa84ec6abd0c1b12ba0ba1548e89c9fca36fc58f03e66074db423b0e98ec8e6` |
|
| 28 |
+
| `tokenizer.json` | `3a690c2d605076ad3901d946d4c0145fbfb19fef2f01370c7388430aa9f31edf` |
|
| 29 |
+
| `NOTICE.md` | this file |
|
names/config.json
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_cross_attention": false,
|
| 3 |
+
"architectures": [
|
| 4 |
+
"BertForTokenClassification"
|
| 5 |
+
],
|
| 6 |
+
"attention_probs_dropout_prob": 0.1,
|
| 7 |
+
"bos_token_id": null,
|
| 8 |
+
"classifier_dropout": 0.1,
|
| 9 |
+
"dtype": "float32",
|
| 10 |
+
"eos_token_id": null,
|
| 11 |
+
"hidden_act": "gelu",
|
| 12 |
+
"hidden_dropout_prob": 0.1,
|
| 13 |
+
"hidden_size": 768,
|
| 14 |
+
"id2label": {
|
| 15 |
+
"0": "O",
|
| 16 |
+
"1": "B-PERSON",
|
| 17 |
+
"2": "I-PERSON",
|
| 18 |
+
"3": "B-PERSON_F",
|
| 19 |
+
"4": "I-PERSON_F",
|
| 20 |
+
"5": "B-PERSON_L",
|
| 21 |
+
"6": "I-PERSON_L",
|
| 22 |
+
"7": "B-ORG",
|
| 23 |
+
"8": "I-ORG",
|
| 24 |
+
"9": "B-STREET",
|
| 25 |
+
"10": "I-STREET",
|
| 26 |
+
"11": "B-CITY",
|
| 27 |
+
"12": "I-CITY"
|
| 28 |
+
},
|
| 29 |
+
"initializer_range": 0.02,
|
| 30 |
+
"intermediate_size": 3072,
|
| 31 |
+
"is_decoder": false,
|
| 32 |
+
"label2id": {
|
| 33 |
+
"B-CITY": 11,
|
| 34 |
+
"B-ORG": 7,
|
| 35 |
+
"B-PERSON": 1,
|
| 36 |
+
"B-PERSON_F": 3,
|
| 37 |
+
"B-PERSON_L": 5,
|
| 38 |
+
"B-STREET": 9,
|
| 39 |
+
"I-CITY": 12,
|
| 40 |
+
"I-ORG": 8,
|
| 41 |
+
"I-PERSON": 2,
|
| 42 |
+
"I-PERSON_F": 4,
|
| 43 |
+
"I-PERSON_L": 6,
|
| 44 |
+
"I-STREET": 10,
|
| 45 |
+
"O": 0
|
| 46 |
+
},
|
| 47 |
+
"layer_norm_eps": 1e-12,
|
| 48 |
+
"max_position_embeddings": 514,
|
| 49 |
+
"model_type": "bert",
|
| 50 |
+
"num_attention_heads": 12,
|
| 51 |
+
"num_hidden_layers": 12,
|
| 52 |
+
"pad_token_id": 1,
|
| 53 |
+
"position_embedding_type": "absolute",
|
| 54 |
+
"tie_word_embeddings": true,
|
| 55 |
+
"tokenizer_class": "HerbertTokenizerFast",
|
| 56 |
+
"transformers_version": "5.12.1",
|
| 57 |
+
"type_vocab_size": 2,
|
| 58 |
+
"use_cache": false,
|
| 59 |
+
"vocab_size": 50000
|
| 60 |
+
}
|
names/model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2fa84ec6abd0c1b12ba0ba1548e89c9fca36fc58f03e66074db423b0e98ec8e6
|
| 3 |
+
size 495472716
|
names/tokenizer.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3a690c2d605076ad3901d946d4c0145fbfb19fef2f01370c7388430aa9f31edf
|
| 3 |
+
size 3688881
|
nergal.py
CHANGED
|
@@ -258,12 +258,13 @@ def scrub_spans(text, rule_spans, model_spans, *, threshold=THRESHOLD, module=sc
|
|
| 258 |
'model_extra_spans': extra}
|
| 259 |
|
| 260 |
|
| 261 |
-
def _resolve(source, *, local_files_only):
|
| 262 |
path = Path(source)
|
| 263 |
if path.is_dir():
|
| 264 |
return path
|
| 265 |
from huggingface_hub import snapshot_download
|
| 266 |
-
return Path(snapshot_download(source, local_files_only=local_files_only
|
|
|
|
| 267 |
|
| 268 |
|
| 269 |
def _load_rules_module(asset):
|
|
@@ -279,8 +280,74 @@ def _load_rules_module(asset):
|
|
| 279 |
return scrub_pii
|
| 280 |
|
| 281 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 282 |
class Nergal:
|
| 283 |
-
def __init__(self, asset, device='cpu', dtype='float32'):
|
| 284 |
import torch
|
| 285 |
from transformers import AutoModelForTokenClassification, AutoTokenizer
|
| 286 |
if dtype not in DTYPES:
|
|
@@ -295,6 +362,8 @@ class Nergal:
|
|
| 295 |
card = json.loads((asset / 'hybrid.json').read_text())
|
| 296 |
if card['gap_ids'] != GAP_IDS or card['threshold'] != THRESHOLD:
|
| 297 |
raise ValueError('hybrid.json does not match this NERGAL snapshot')
|
|
|
|
|
|
|
| 298 |
tokenizer = AutoTokenizer.from_pretrained(
|
| 299 |
str(asset), local_files_only=True, use_fast=True, fix_mistral_regex=False,
|
| 300 |
)
|
|
@@ -304,13 +373,15 @@ class Nergal:
|
|
| 304 |
self.encoding = Encoding(tokenizer)
|
| 305 |
self.threshold = THRESHOLD
|
| 306 |
self.model.to(device, dtype=getattr(torch, dtype)).eval()
|
|
|
|
| 307 |
|
| 308 |
@classmethod
|
| 309 |
-
def from_pretrained(cls, source=HUB_ID, *, device=None, dtype='float32', local_files_only=False):
|
| 310 |
import torch
|
| 311 |
if device is None:
|
| 312 |
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
|
| 313 |
-
return cls(_resolve(source, local_files_only=local_files_only), device=device, dtype=dtype
|
|
|
|
| 314 |
|
| 315 |
def predict(self, text):
|
| 316 |
return self.predict_many([text])[0]
|
|
@@ -336,14 +407,9 @@ class Nergal:
|
|
| 336 |
for window in chunks:
|
| 337 |
encoded, first = encoding.encode([u.model for u in units[window['start']:window['end']]])
|
| 338 |
items.append((len(encoded['input_ids'][0]), d, window, encoded, first))
|
| 339 |
-
items.sort(key=lambda item: item[0])
|
| 340 |
with torch.inference_mode():
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
j = i + 1 # sorted ascending, so items[j] sets the padded width of items[i:j + 1]
|
| 344 |
-
while j < len(items) and j - i < max_batch and (j - i + 1) * items[j][0] <= batch_tokens:
|
| 345 |
-
j += 1
|
| 346 |
-
part = items[i:j]
|
| 347 |
batch = encoding.tokenizer.pad([{k: v[0] for k, v in e.items()} for _, _, _, e, _ in part],
|
| 348 |
padding=True, return_tensors='pt')
|
| 349 |
if batch['input_ids'].shape[1] > 512:
|
|
@@ -353,7 +419,6 @@ class Nergal:
|
|
| 353 |
a, b = window['start'], window['end']
|
| 354 |
docs[d][1][a:b] += logits[row, first]
|
| 355 |
docs[d][2][a:b] += 1
|
| 356 |
-
i = j
|
| 357 |
result = []
|
| 358 |
for units, sums, counts in docs:
|
| 359 |
if (counts == 0).any():
|
|
@@ -369,8 +434,10 @@ class Nergal:
|
|
| 369 |
|
| 370 |
def scrub_many(self, texts):
|
| 371 |
texts = list(texts)
|
| 372 |
-
|
| 373 |
-
|
|
|
|
|
|
|
| 374 |
|
| 375 |
|
| 376 |
def main(argv=None):
|
|
@@ -381,9 +448,10 @@ def main(argv=None):
|
|
| 381 |
parser.add_argument('--device', default=None)
|
| 382 |
parser.add_argument('--dtype', default='float32', choices=DTYPES)
|
| 383 |
parser.add_argument('--local', action='store_true')
|
|
|
|
| 384 |
args = parser.parse_args(argv)
|
| 385 |
nergal = Nergal.from_pretrained(args.repo, device=args.device, dtype=args.dtype,
|
| 386 |
-
local_files_only=args.local)
|
| 387 |
text = sys.stdin.read()
|
| 388 |
masked, counts = nergal.scrub(text)
|
| 389 |
sys.stdout.write(masked)
|
|
|
|
| 258 |
'model_extra_spans': extra}
|
| 259 |
|
| 260 |
|
| 261 |
+
def _resolve(source, *, local_files_only, names=False):
|
| 262 |
path = Path(source)
|
| 263 |
if path.is_dir():
|
| 264 |
return path
|
| 265 |
from huggingface_hub import snapshot_download
|
| 266 |
+
return Path(snapshot_download(source, local_files_only=local_files_only,
|
| 267 |
+
ignore_patterns=None if names else ['names/*'])) # names/ is ≈490 MB
|
| 268 |
|
| 269 |
|
| 270 |
def _load_rules_module(asset):
|
|
|
|
| 280 |
return scrub_pii
|
| 281 |
|
| 282 |
|
| 283 |
+
_FEEDS = (('input_ids', 'ids'), ('attention_mask', 'attention_mask'), ('token_type_ids', 'type_ids'))
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def pack(lengths, batch_tokens, max_batch):
|
| 287 |
+
"""Indices sorted by length, cut into batches of at most max_batch rows and batch_tokens padded tokens."""
|
| 288 |
+
order = sorted(range(len(lengths)), key=lengths.__getitem__)
|
| 289 |
+
out, i = [], 0
|
| 290 |
+
while i < len(order):
|
| 291 |
+
j = i + 1 # ascending, so order[j] sets the padded width of order[i:j + 1]
|
| 292 |
+
while j < len(order) and j - i < max_batch and (j - i + 1) * lengths[order[j]] <= batch_tokens:
|
| 293 |
+
j += 1
|
| 294 |
+
out.append(order[i:j])
|
| 295 |
+
i = j
|
| 296 |
+
return out
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
class Names:
|
| 300 |
+
"""FastPDN-PII person names (names/, CC-BY-4.0, see names/NOTICE.md): the FP32 ONNX converted to safetensors, run
|
| 301 |
+
in torch on NERGAL's device; argmax per token, windows packed like predict_many."""
|
| 302 |
+
|
| 303 |
+
def __init__(self, asset, card, device='cpu'):
|
| 304 |
+
import torch
|
| 305 |
+
from safetensors.torch import load_file
|
| 306 |
+
from tokenizers import Tokenizer
|
| 307 |
+
from transformers import BertConfig, BertForTokenClassification
|
| 308 |
+
root = Path(asset) / 'names'
|
| 309 |
+
for name, digest in card['sha256'].items():
|
| 310 |
+
if sha(root / name) != digest:
|
| 311 |
+
raise ValueError(f'Unexpected names/{name} sha256')
|
| 312 |
+
config = BertConfig.from_pretrained(str(root))
|
| 313 |
+
labels = config.id2label
|
| 314 |
+
self.person_ids = {i for i, label in labels.items() if label[2:] in PERSON_LABELS}
|
| 315 |
+
if sorted(labels[i] for i in self.person_ids) != sorted(f'{p}-{l}' for p in 'BI' for l in PERSON_LABELS):
|
| 316 |
+
raise ValueError('names/config.json does not label B/I person tags')
|
| 317 |
+
self.tokenizer = Tokenizer.from_file(str(root / 'tokenizer.json'))
|
| 318 |
+
self.tokenizer.enable_truncation(max_length=card['max_length'], stride=card['stride'])
|
| 319 |
+
self.tokenizer.no_padding()
|
| 320 |
+
self.pad = {'input_ids': config.pad_token_id, 'attention_mask': 0, 'token_type_ids': 0}
|
| 321 |
+
self.model = BertForTokenClassification(config)
|
| 322 |
+
self.model.load_state_dict(load_file(root / 'model.safetensors'), strict=True)
|
| 323 |
+
self.model.to(device, dtype=getattr(torch, card['dtype'])).eval()
|
| 324 |
+
self.device, self._torch = device, torch
|
| 325 |
+
|
| 326 |
+
def spans(self, text):
|
| 327 |
+
return self.spans_many([text])[0]
|
| 328 |
+
|
| 329 |
+
def spans_many(self, texts, *, batch_tokens=32768, max_batch=128):
|
| 330 |
+
torch, texts = self._torch, list(texts)
|
| 331 |
+
items = [(d, w) for d, text in enumerate(texts)
|
| 332 |
+
for enc in [self.tokenizer.encode(text)] for w in [enc, *enc.overflowing]]
|
| 333 |
+
ranges = [[] for _ in texts]
|
| 334 |
+
with torch.inference_mode():
|
| 335 |
+
for part in pack([len(w.ids) for _, w in items], batch_tokens, max_batch):
|
| 336 |
+
rows = [items[i][1] for i in part]
|
| 337 |
+
width = max(len(w.ids) for w in rows)
|
| 338 |
+
feed = {name: torch.tensor([getattr(w, attr) + [self.pad[name]] * (width - len(w.ids)) for w in rows],
|
| 339 |
+
device=self.device) for name, attr in _FEEDS}
|
| 340 |
+
logits = self.model(**feed).logits.float().cpu()
|
| 341 |
+
for row, i in enumerate(part):
|
| 342 |
+
d, w = items[i]
|
| 343 |
+
tags = logits[row, :len(w.ids)].argmax(-1).tolist()
|
| 344 |
+
ranges[d] += [(a, b) for tag, special, (a, b) in zip(tags, w.special_tokens_mask, w.offsets, strict=True)
|
| 345 |
+
if tag in self.person_ids and not special and a < b]
|
| 346 |
+
return [person_spans(text, r) for text, r in zip(texts, ranges, strict=True)]
|
| 347 |
+
|
| 348 |
+
|
| 349 |
class Nergal:
|
| 350 |
+
def __init__(self, asset, device='cpu', dtype='float32', names=False):
|
| 351 |
import torch
|
| 352 |
from transformers import AutoModelForTokenClassification, AutoTokenizer
|
| 353 |
if dtype not in DTYPES:
|
|
|
|
| 362 |
card = json.loads((asset / 'hybrid.json').read_text())
|
| 363 |
if card['gap_ids'] != GAP_IDS or card['threshold'] != THRESHOLD:
|
| 364 |
raise ValueError('hybrid.json does not match this NERGAL snapshot')
|
| 365 |
+
if names and 'names' not in card:
|
| 366 |
+
raise ValueError('This NERGAL snapshot has no names model')
|
| 367 |
tokenizer = AutoTokenizer.from_pretrained(
|
| 368 |
str(asset), local_files_only=True, use_fast=True, fix_mistral_regex=False,
|
| 369 |
)
|
|
|
|
| 373 |
self.encoding = Encoding(tokenizer)
|
| 374 |
self.threshold = THRESHOLD
|
| 375 |
self.model.to(device, dtype=getattr(torch, dtype)).eval()
|
| 376 |
+
self.names = Names(asset, card['names'], device) if names else None # dtype from the card, not NERGAL's
|
| 377 |
|
| 378 |
@classmethod
|
| 379 |
+
def from_pretrained(cls, source=HUB_ID, *, device=None, dtype='float32', local_files_only=False, names=False):
|
| 380 |
import torch
|
| 381 |
if device is None:
|
| 382 |
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
|
| 383 |
+
return cls(_resolve(source, local_files_only=local_files_only, names=names), device=device, dtype=dtype,
|
| 384 |
+
names=names)
|
| 385 |
|
| 386 |
def predict(self, text):
|
| 387 |
return self.predict_many([text])[0]
|
|
|
|
| 407 |
for window in chunks:
|
| 408 |
encoded, first = encoding.encode([u.model for u in units[window['start']:window['end']]])
|
| 409 |
items.append((len(encoded['input_ids'][0]), d, window, encoded, first))
|
|
|
|
| 410 |
with torch.inference_mode():
|
| 411 |
+
for part in pack([n for n, *_ in items], batch_tokens, max_batch):
|
| 412 |
+
part = [items[i] for i in part]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 413 |
batch = encoding.tokenizer.pad([{k: v[0] for k, v in e.items()} for _, _, _, e, _ in part],
|
| 414 |
padding=True, return_tensors='pt')
|
| 415 |
if batch['input_ids'].shape[1] > 512:
|
|
|
|
| 419 |
a, b = window['start'], window['end']
|
| 420 |
docs[d][1][a:b] += logits[row, first]
|
| 421 |
docs[d][2][a:b] += 1
|
|
|
|
| 422 |
result = []
|
| 423 |
for units, sums, counts in docs:
|
| 424 |
if (counts == 0).any():
|
|
|
|
| 434 |
|
| 435 |
def scrub_many(self, texts):
|
| 436 |
texts = list(texts)
|
| 437 |
+
name_spans = self.names.spans_many(texts) if self.names else [()] * len(texts)
|
| 438 |
+
return [scrub_spans(text, self.rule_spans(text), model, threshold=self.threshold, module=self._scrub,
|
| 439 |
+
name_spans=spans)
|
| 440 |
+
for text, model, spans in zip(texts, self.predict_many(texts), name_spans, strict=True)]
|
| 441 |
|
| 442 |
|
| 443 |
def main(argv=None):
|
|
|
|
| 448 |
parser.add_argument('--device', default=None)
|
| 449 |
parser.add_argument('--dtype', default='float32', choices=DTYPES)
|
| 450 |
parser.add_argument('--local', action='store_true')
|
| 451 |
+
parser.add_argument('--names', action='store_true')
|
| 452 |
args = parser.parse_args(argv)
|
| 453 |
nergal = Nergal.from_pretrained(args.repo, device=args.device, dtype=args.dtype,
|
| 454 |
+
local_files_only=args.local, names=args.names)
|
| 455 |
text = sys.stdin.read()
|
| 456 |
masked, counts = nergal.scrub(text)
|
| 457 |
sys.stdout.write(masked)
|
test_nergal.py
CHANGED
|
@@ -1,6 +1,8 @@
|
|
| 1 |
"""Synthetic NERGAL tests. Invented strings only; no corpus text or real identifiers."""
|
| 2 |
import hashlib
|
| 3 |
import json
|
|
|
|
|
|
|
| 4 |
import unittest
|
| 5 |
from pathlib import Path
|
| 6 |
|
|
@@ -172,6 +174,68 @@ class NergalTests(unittest.TestCase):
|
|
| 172 |
self.assertEqual(scrub_spans(text, [], [span(text, '112')])[0], text)
|
| 173 |
self.assertEqual(model_keep(text, [span(text, '112', score=0.9)], threshold=0.95), [])
|
| 174 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
|
| 176 |
if __name__ == '__main__':
|
| 177 |
unittest.main()
|
|
|
|
| 1 |
"""Synthetic NERGAL tests. Invented strings only; no corpus text or real identifiers."""
|
| 2 |
import hashlib
|
| 3 |
import json
|
| 4 |
+
import shutil
|
| 5 |
+
import tempfile
|
| 6 |
import unittest
|
| 7 |
from pathlib import Path
|
| 8 |
|
|
|
|
| 174 |
self.assertEqual(scrub_spans(text, [], [span(text, '112')])[0], text)
|
| 175 |
self.assertEqual(model_keep(text, [span(text, '112', score=0.9)], threshold=0.95), [])
|
| 176 |
|
| 177 |
+
def _names(self):
|
| 178 |
+
from nergal import Names
|
| 179 |
+
return Names(HERE, json.loads((HERE / 'hybrid.json').read_text())['names'])
|
| 180 |
+
|
| 181 |
+
def test_names_mask_an_invented_person_and_nothing_else(self):
|
| 182 |
+
names = self._names()
|
| 183 |
+
text = 'Wniosek złożyła Anna Nowakowska z Radomia.'
|
| 184 |
+
self.assertIn('Anna Nowakowska', [text[s['start']:s['end']] for s in names.spans(text)])
|
| 185 |
+
self.assertEqual(names.spans('Zdanie bez nazwisk o pogodzie.'), []) # special tokens are never a person
|
| 186 |
+
self.assertEqual(names.spans(''), [])
|
| 187 |
+
text = 'Ala ma kota.' # a first name alone is a person (names policy)
|
| 188 |
+
self.assertEqual([text[s['start']:s['end']] for s in names.spans(text)], ['Ala'])
|
| 189 |
+
|
| 190 |
+
def test_names_find_a_person_past_the_first_window_and_are_idempotent(self):
|
| 191 |
+
from nergal import apply_union
|
| 192 |
+
names = self._names()
|
| 193 |
+
text = 'Zdanie bez nazwisk o pogodzie. ' * 200 + 'Wniosek złożyła Anna Nowakowska.'
|
| 194 |
+
spans = names.spans(text)
|
| 195 |
+
self.assertEqual([text[s['start']:s['end']] for s in spans], ['Anna Nowakowska'])
|
| 196 |
+
masked, _, _ = apply_union(text, spans)
|
| 197 |
+
self.assertEqual(names.spans(masked), [])
|
| 198 |
+
|
| 199 |
+
def test_names_batched_equal_one_at_a_time(self):
|
| 200 |
+
names = self._names()
|
| 201 |
+
texts = ['Wniosek złożyła Anna Nowakowska z Radomia.', '',
|
| 202 |
+
'Zdanie bez nazwisk o pogodzie. ' * 200 + 'Podpisał Tomasz Wrzos.', 'Ala ma kota.']
|
| 203 |
+
self.assertEqual(names.spans_many(texts, max_batch=2), [names.spans(t) for t in texts])
|
| 204 |
+
|
| 205 |
+
def test_names_are_opt_in_and_verified(self):
|
| 206 |
+
from nergal import Names
|
| 207 |
+
card = json.loads((HERE / 'hybrid.json').read_text())['names']
|
| 208 |
+
with self.assertRaises(ValueError):
|
| 209 |
+
Names(HERE, {**card, 'sha256': {**card['sha256'], 'tokenizer.json': '0' * 64}})
|
| 210 |
+
|
| 211 |
+
def test_a_snapshot_without_names_refuses_names(self):
|
| 212 |
+
from nergal import Nergal
|
| 213 |
+
card = json.loads((HERE / 'hybrid.json').read_text())
|
| 214 |
+
del card['names']
|
| 215 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 216 |
+
shutil.copy(HERE / 'scrub_pii.py', tmp)
|
| 217 |
+
(Path(tmp) / 'hybrid.json').write_text(json.dumps(card))
|
| 218 |
+
with self.assertRaisesRegex(ValueError, 'no names model'):
|
| 219 |
+
Nergal(tmp, names=True) # raised before the tokenizer or model loads
|
| 220 |
+
|
| 221 |
+
def test_hub_download_skips_names_unless_asked(self):
|
| 222 |
+
from unittest import mock
|
| 223 |
+
import huggingface_hub
|
| 224 |
+
from nergal import _resolve
|
| 225 |
+
with mock.patch.object(huggingface_hub, 'snapshot_download', return_value=str(HERE)) as download:
|
| 226 |
+
_resolve('SlayerLab/NERGAL', local_files_only=True)
|
| 227 |
+
_resolve('SlayerLab/NERGAL', local_files_only=True, names=True)
|
| 228 |
+
self.assertEqual([c.kwargs['ignore_patterns'] for c in download.call_args_list], [['names/*'], None])
|
| 229 |
+
|
| 230 |
+
def test_pack_keeps_every_index_once_within_limits(self):
|
| 231 |
+
from nergal import pack
|
| 232 |
+
lengths = [5, 1, 9, 3, 3, 7]
|
| 233 |
+
parts = pack(lengths, batch_tokens=12, max_batch=2)
|
| 234 |
+
self.assertEqual(sorted(i for p in parts for i in p), list(range(6)))
|
| 235 |
+
for p in parts:
|
| 236 |
+
self.assertLessEqual(len(p), 2)
|
| 237 |
+
self.assertLessEqual(len(p) * max(lengths[i] for i in p), 12)
|
| 238 |
+
|
| 239 |
|
| 240 |
if __name__ == '__main__':
|
| 241 |
unittest.main()
|