ppuzio commited on
Commit
78cc85a
·
1 Parent(s): 3f67c66

1.1.0: batch API (predict_many, scrub_many), opt-in float16 (#2)

Browse files

- Prepare 1.1.0: batch API (predict_many, scrub_many), opt-in float16 (fdc79fca5b4800a95c0eddeb2c18f9fdd1dd59e3)
- 1.1.0 card: throughput in TL;DR (7b7f961957267e4439c13c67c51b634fd7fbc76b)

Files changed (5) hide show
  1. CHANGELOG.md +21 -0
  2. README.md +11 -7
  3. hybrid.json +1 -1
  4. nergal.py +68 -32
  5. test_nergal.py +21 -1
CHANGELOG.md CHANGED
@@ -8,6 +8,27 @@ Semver for this island:
8
 
9
  Accuracy is 841-dev, union at 0.95, 354 gold spans. A version that changes those numbers must update `hybrid.json` `eval` and the tables below.
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  ## 1.0.3
12
 
13
  Same weights, threshold, and API. Rules SHA `f32d5c54…`.
 
8
 
9
  Accuracy is 841-dev, union at 0.95, 354 gold spans. A version that changes those numbers must update `hybrid.json` `eval` and the tables below.
10
 
11
+ ## 1.1.0
12
+
13
+ Same weights, rules, threshold and default outputs; `hybrid.json` `eval` is unchanged. New batch API and opt-in fp16.
14
+
15
+ - **`Nergal.predict_many(texts)` / `scrub_many(texts)`:** windows from up to 64 texts are sorted by token length and packed into batches of at most 32,768 padded tokens and 128 rows. `predict` / `scrub` are now the one-text case of these.
16
+ - **`dtype='float16'`** on `Nergal(...)` / `from_pretrained(...)` (CLI `--dtype`): casts the float32 weights at load time. Needs CUDA or MPS. The default stays `float32`, and `model.safetensors` is unchanged.
17
+ - **Faster window sizing:** `Encoding.count` adds up cached unit pieces instead of re-tokenizing inside the window search. It yields the same windows, because `encode()` still rejects any unit whose pieces change with context.
18
+ - **Default device:** `from_pretrained` now tries CUDA, then MPS, then CPU. 1.0.x used CPU even on CUDA machines.
19
+
20
+ Throughput on one RTX 4090 (13.88M chars of FineWeb-2, kchar/s): 1.0.3-style per-document batches 11.0 (23.0 with 3 processes); `predict_many` float32 21.3 (28.1 with 2); `predict_many` float16 39.4 (79.6 with 3). The float16 path is limited by CPU-side tokenization, so run 2–3 processes per GPU.
21
+
22
+ Equivalence: on the 1,685 labelled dev rows, float32 `predict_many` gives 0 span changes at 0.95 against the cached model spans of the published weights (841-dev max score change 2.6e-5). Float16 adds 2 spans on gold (1 on 841-dev, already covered by the rules) and removes none; 841-dev union numbers are identical. On 6,182 FineWeb-2 documents (1,236 with MPS and 4,946 with CUDA float32 references), CUDA float16 gave 0 span changes (max score change 0.012).
23
+
24
+ | Version | Whole /354 | Residual | Rules FP | Union FP | Char P | Char R | What changed |
25
+ |---|---:|---:|---:|---:|---:|---:|---|
26
+ | 1.0.0 | 323 | 25 | 133 | 133 | 97.76% | 95.95% | First Hub snapshot |
27
+ | 1.0.1 | 323 | 25 | 98 | 123 | 97.93% | 95.95% | Prefix-only glued-email trim |
28
+ | 1.0.2 | 324 | 24 | 98 | 123 | 97.93% | 96.12% | Labelled country-area phone fix |
29
+ | 1.0.3 | 324 | 24 | 98 | 123 | 97.93% | 96.12% | Label-note, e-Delivery and registry rules; placeholder and card fixes |
30
+ | 1.1.0 | 324 | 24 | 98 | 123 | 97.93% | 96.12% | Batch API (`predict_many`, `scrub_many`), opt-in float16 |
31
+
32
  ## 1.0.3
33
 
34
  Same weights, threshold, and API. Rules SHA `f32d5c54…`.
README.md CHANGED
@@ -13,7 +13,7 @@ tags:
13
  - hybrid
14
  ---
15
 
16
- # NERGAL 1.0.3
17
 
18
  **Named Entity Recognition with Grounded Additive Labels**
19
 
@@ -23,9 +23,10 @@ SlayerLab hybrid PII cleaner for Polish. Not a chat model. Not a drop-in `pipeli
23
 
24
  Python rules do the identifiers they can prove. A transformer NER head adds phone and other PII spans the regex misses. The cleaner **unions** the two on the original text, then replaces hits with `[Telefon]` or `[PII]`.
25
 
26
- - **Version:** `1.0.3` (`hybrid.json`, `CHANGELOG.md`)
27
  - **Ground:** `scrub_pii` regex (SHA256 `f32d5c54…`)
28
  - **Additive labels:** XLM-RoBERTa-large token classifier, BIO tags `phone` / `pii`, threshold 0.95
 
29
  - **This snapshot:** seed `202609160`, **epoch 5** of a seven-epoch schedule
30
 
31
  ## What NERGAL detects — and what it does not
@@ -61,9 +62,9 @@ NERGAL is not designed to remove:
61
 
62
  These are intended exclusions; false positives can still mask some of this content.
63
 
64
- ### Known gaps in 1.0.3
65
 
66
- Unlabelled phones and identifiers, unusual formatting and damaged text can escape detection. **VINs and obfuscated emails** (such as `name (at) domain.pl`) are approved annotation targets, but that approval alone does not establish reliable support in the released 1.0.3 model. Do not rely on it to remove them consistently.
67
 
68
  ## Versions
69
 
@@ -74,7 +75,8 @@ Unlabelled phones and identifiers, unusual formatting and damaged text can escap
74
  | 1.0.0 | 323 | 25 | 133 | 133 | 97.76% | 95.95% | First Hub snapshot |
75
  | 1.0.1 | 323 | 25 | 98 | 123 | 97.93% | 95.95% | Prefix-only glued-email trim |
76
  | 1.0.2 | 324 | 24 | 98 | 123 | 97.93% | 96.12% | Labelled country-area phone fix |
77
- | **1.0.3** | **324** | **24** | **98** | **123** | **97.93%** | **96.12%** | Label-note, e-Delivery and registry rules; placeholder and card fixes |
 
78
 
79
  ## 841-dev
80
 
@@ -116,7 +118,7 @@ Same 841-dev split, threshold **0.95**. **Naked** is the transformer alone. **
116
  | Historical GLiNER email12 | naked | 249 | 70 | 10 | 99.81% | 85.39% |
117
  | Historical GLiNER email12 | ∪ regex | 290 | 50 | 108 | 98.13% | 93.76% |
118
  | XLM-R epoch 5 | naked | 298 | 42 | 57 | 98.96% | 89.38% |
119
- | **NERGAL 1.0.3** | **∪ regex** | 324 | 24 | 123 | 97.93% | 96.12% |
120
 
121
  Zero-shot [GLiNER 2.5](https://huggingface.co/fastino/gliner2.5-multi-v1) is not competitive here, especially on non-phone PII (7/185 whole vs 160 naked / 179 union). Fine-tuned historical GLiNER is the precise naked baseline (10 false characters) and still trails XLM-R on coverage. NERGAL is XLM-R epoch 5 plus the regex: 145/169 phone, 179/185 other PII. Exact-span precision 86.34%, recall 89.27%, F1 87.78%.
122
 
@@ -151,6 +153,8 @@ nergal = Nergal.from_pretrained(root, local_files_only=True)
151
  masked, counts = nergal.scrub(text)
152
  ```
153
 
154
- `hybrid.json` records version `1.0.3`, threshold 0.95, gap ids `250002` / `250003`, the 841-dev `eval` block, and two weight hashes: `model_safetensors_sha256` for the published file and `source_checkpoint_sha256` for the training checkpoint it was packed from. `test_nergal.py` is synthetic (no corpus text). From this snapshot: `python -m unittest test_nergal`.
 
 
155
 
156
  Base weights: [`FacebookAI/xlm-roberta-large`](https://huggingface.co/FacebookAI/xlm-roberta-large) revision `c23d21b0620b635a76227c604d44e43a9f0ee389` (MIT).
 
13
  - hybrid
14
  ---
15
 
16
+ # NERGAL 1.1.0
17
 
18
  **Named Entity Recognition with Grounded Additive Labels**
19
 
 
23
 
24
  Python rules do the identifiers they can prove. A transformer NER head adds phone and other PII spans the regex misses. The cleaner **unions** the two on the original text, then replaces hits with `[Telefon]` or `[PII]`.
25
 
26
+ - **Version:** `1.1.0` (`hybrid.json`, `CHANGELOG.md`)
27
  - **Ground:** `scrub_pii` regex (SHA256 `f32d5c54…`)
28
  - **Additive labels:** XLM-RoBERTa-large token classifier, BIO tags `phone` / `pii`, threshold 0.95
29
+ - **Throughput:** about 80k chars/s on one RTX 4090 with `scrub_many` + `dtype="float16"` and 3 processes (1.0.3: 23k)
30
  - **This snapshot:** seed `202609160`, **epoch 5** of a seven-epoch schedule
31
 
32
  ## What NERGAL detects — and what it does not
 
62
 
63
  These are intended exclusions; false positives can still mask some of this content.
64
 
65
+ ### Known gaps in 1.1.0
66
 
67
+ Unlabelled phones and identifiers, unusual formatting and damaged text can escape detection. **VINs and obfuscated emails** (such as `name (at) domain.pl`) are approved annotation targets, but that approval alone does not establish reliable support in the released 1.1.0 model. Do not rely on it to remove them consistently.
68
 
69
  ## Versions
70
 
 
75
  | 1.0.0 | 323 | 25 | 133 | 133 | 97.76% | 95.95% | First Hub snapshot |
76
  | 1.0.1 | 323 | 25 | 98 | 123 | 97.93% | 95.95% | Prefix-only glued-email trim |
77
  | 1.0.2 | 324 | 24 | 98 | 123 | 97.93% | 96.12% | Labelled country-area phone fix |
78
+ | 1.0.3 | 324 | 24 | 98 | 123 | 97.93% | 96.12% | Label-note, e-Delivery and registry rules; placeholder and card fixes |
79
+ | **1.1.0** | **324** | **24** | **98** | **123** | **97.93%** | **96.12%** | Batch API (`predict_many`, `scrub_many`), opt-in float16 |
80
 
81
  ## 841-dev
82
 
 
118
  | Historical GLiNER email12 | naked | 249 | 70 | 10 | 99.81% | 85.39% |
119
  | Historical GLiNER email12 | ∪ regex | 290 | 50 | 108 | 98.13% | 93.76% |
120
  | XLM-R epoch 5 | naked | 298 | 42 | 57 | 98.96% | 89.38% |
121
+ | **NERGAL 1.1.0** | **∪ regex** | 324 | 24 | 123 | 97.93% | 96.12% |
122
 
123
  Zero-shot [GLiNER 2.5](https://huggingface.co/fastino/gliner2.5-multi-v1) is not competitive here, especially on non-phone PII (7/185 whole vs 160 naked / 179 union). Fine-tuned historical GLiNER is the precise naked baseline (10 false characters) and still trails XLM-R on coverage. NERGAL is XLM-R epoch 5 plus the regex: 145/169 phone, 179/185 other PII. Exact-span precision 86.34%, recall 89.27%, F1 87.78%.
124
 
 
153
  masked, counts = nergal.scrub(text)
154
  ```
155
 
156
+ For many texts, `nergal.scrub_many(texts)` (or `predict_many` for the raw model spans) batches windows across texts: about 2× the throughput of calling `scrub` in a loop on a CUDA GPU. `from_pretrained(..., dtype="float16")` casts the weights at load time on CUDA or MPS: another 1.9× on an RTX 4090, and 841-dev union numbers are unchanged, but scores are not bit-identical to float32 (0.95 spans can differ in rare cases). For a corpus, run 2–3 processes per GPU, because float16 inference is limited by CPU-side tokenization. Measurements are in `CHANGELOG.md`.
157
+
158
+ `hybrid.json` records version `1.1.0`, threshold 0.95, gap ids `250002` / `250003`, the 841-dev `eval` block, and two weight hashes: `model_safetensors_sha256` for the published file and `source_checkpoint_sha256` for the training checkpoint it was packed from. `test_nergal.py` is synthetic (no corpus text). From this snapshot: `python -m unittest test_nergal`.
159
 
160
  Base weights: [`FacebookAI/xlm-roberta-large`](https://huggingface.co/FacebookAI/xlm-roberta-large) revision `c23d21b0620b635a76227c604d44e43a9f0ee389` (MIT).
hybrid.json CHANGED
@@ -1,7 +1,7 @@
1
  {
2
  "full_name": "Named Entity Recognition with Grounded Additive Labels",
3
  "hub_id": "SlayerLab/NERGAL",
4
- "version": "1.0.3",
5
  "mode": "rules_union",
6
  "epoch": 5,
7
  "seed": 202609160,
 
1
  {
2
  "full_name": "Named Entity Recognition with Grounded Additive Labels",
3
  "hub_id": "SlayerLab/NERGAL",
4
+ "version": "1.1.0",
5
  "mode": "rules_union",
6
  "epoch": 5,
7
  "seed": 202609160,
nergal.py CHANGED
@@ -17,13 +17,14 @@ import scrub_pii
17
  from scrub_pii import PHONE_TAG, PII_TAG
18
 
19
  HUB_ID = 'SlayerLab/NERGAL'
20
- VERSION = '1.0.3'
21
  GAPS = ['[PII_SPACE]', '[PII_BREAK]']
22
  GAP_IDS = [250002, 250003]
23
  BIO_LABELS = ['O', 'B-phone', 'I-phone', 'B-pii', 'I-pii']
24
  LABELS = ['phone', 'pii']
25
  THRESHOLD = 0.95
26
  RULES_SHA = 'f32d5c5452fc47178e109d4bc248a0d8234ea6e59e8cf79407f4eb8451581d67'
 
27
 
28
 
29
  def sha(path):
@@ -157,8 +158,9 @@ class Encoding:
157
  return encoded, [first[j] for j in range(len(words))]
158
 
159
  def count(self, units):
160
- encoded, _ = self.encode([u.model for u in units])
161
- return len(encoded['input_ids'][0])
 
162
 
163
  def prepare(self, text):
164
  units = unitize(text, self.pieces, self.tokenizer.unk_token)
@@ -245,9 +247,14 @@ def _load_rules_module(asset):
245
 
246
 
247
  class Nergal:
248
- def __init__(self, asset, device='cpu'):
249
  import torch
250
  from transformers import AutoModelForTokenClassification, AutoTokenizer
 
 
 
 
 
251
  self.device = device
252
  self._torch = torch
253
  asset = Path(asset)
@@ -263,47 +270,74 @@ class Nergal:
263
  self.model = AutoModelForTokenClassification.from_pretrained(str(asset), local_files_only=True)
264
  self.encoding = Encoding(tokenizer)
265
  self.threshold = THRESHOLD
266
- self.model.to(device).eval()
267
 
268
  @classmethod
269
- def from_pretrained(cls, source=HUB_ID, *, device=None, local_files_only=False):
270
  import torch
271
  if device is None:
272
- device = 'mps' if torch.backends.mps.is_available() else 'cpu'
273
- return cls(_resolve(source, local_files_only=local_files_only), device=device)
274
 
275
  def predict(self, text):
276
- torch = self._torch
277
- units, chunks = self.encoding.prepare(text)
278
- if not units:
279
- return []
280
- sums, counts = torch.zeros(len(units), 5), torch.zeros(len(units), 1)
281
- with torch.inference_mode():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282
  for window in chunks:
283
- a, b = window['start'], window['end']
284
- words = [u.model for u in units[a:b]]
285
- encoded, first = self.encoding.encode(words)
286
- batch = self.encoding.tokenizer.pad(
287
- [{k: v[0] for k, v in encoded.items()}], padding=True, return_tensors='pt',
288
- )
289
- batch = {k: v.to(self.device) if torch.is_tensor(v) else v for k, v in batch.items()}
 
 
 
 
 
290
  if batch['input_ids'].shape[1] > 512:
291
  raise ValueError('Batch exceeds encoder limit')
292
- logits = self.model(**batch).logits
293
- sums[a:b] += logits[0, first].float().cpu()
294
- counts[a:b] += 1
295
- if (counts == 0).any():
296
- raise ValueError('Missing inference units')
297
- return decode_bio(units, (sums / counts).tolist())
 
 
 
 
 
 
298
 
299
  def rule_spans(self, text):
300
  return spans_from(self._scrub, text)
301
 
302
  def scrub(self, text):
303
- if not text:
304
- return text, {'phone': 0, 'pii': 0, 'rules_placeholder_chars': 0,
305
- 'union_placeholder_chars': 0, 'model_extra_spans': 0}
306
- return scrub_spans(text, self.rule_spans(text), self.predict(text), threshold=self.threshold)
 
 
307
 
308
 
309
  def main(argv=None):
@@ -312,9 +346,11 @@ def main(argv=None):
312
  parser = argparse.ArgumentParser(description='NERGAL hybrid PII cleaner')
313
  parser.add_argument('--repo', default=HUB_ID)
314
  parser.add_argument('--device', default=None)
 
315
  parser.add_argument('--local', action='store_true')
316
  args = parser.parse_args(argv)
317
- nergal = Nergal.from_pretrained(args.repo, device=args.device, local_files_only=args.local)
 
318
  text = sys.stdin.read()
319
  masked, counts = nergal.scrub(text)
320
  sys.stdout.write(masked)
 
17
  from scrub_pii import PHONE_TAG, PII_TAG
18
 
19
  HUB_ID = 'SlayerLab/NERGAL'
20
+ VERSION = '1.1.0'
21
  GAPS = ['[PII_SPACE]', '[PII_BREAK]']
22
  GAP_IDS = [250002, 250003]
23
  BIO_LABELS = ['O', 'B-phone', 'I-phone', 'B-pii', 'I-pii']
24
  LABELS = ['phone', 'pii']
25
  THRESHOLD = 0.95
26
  RULES_SHA = 'f32d5c5452fc47178e109d4bc248a0d8234ea6e59e8cf79407f4eb8451581d67'
27
+ DTYPES = ('float32', 'float16')
28
 
29
 
30
  def sha(path):
 
158
  return encoded, [first[j] for j in range(len(words))]
159
 
160
  def count(self, units):
161
+ """Special tokens + cached unit pieces. Exact because encode() rejects any unit whose pieces change with
162
+ context; no re-tokenization inside the windows() binary search."""
163
+ return self.tokenizer.num_special_tokens_to_add() + sum(len(self.pieces(u.model)) for u in units)
164
 
165
  def prepare(self, text):
166
  units = unitize(text, self.pieces, self.tokenizer.unk_token)
 
247
 
248
 
249
  class Nergal:
250
+ def __init__(self, asset, device='cpu', dtype='float32'):
251
  import torch
252
  from transformers import AutoModelForTokenClassification, AutoTokenizer
253
+ if dtype not in DTYPES:
254
+ raise ValueError(f'dtype must be one of {DTYPES}')
255
+ if dtype == 'float16' and torch.device(device).type == 'cpu':
256
+ raise ValueError('float16 needs a cuda or mps device')
257
+ self.dtype = dtype
258
  self.device = device
259
  self._torch = torch
260
  asset = Path(asset)
 
270
  self.model = AutoModelForTokenClassification.from_pretrained(str(asset), local_files_only=True)
271
  self.encoding = Encoding(tokenizer)
272
  self.threshold = THRESHOLD
273
+ self.model.to(device, dtype=getattr(torch, dtype)).eval()
274
 
275
  @classmethod
276
+ def from_pretrained(cls, source=HUB_ID, *, device=None, dtype='float32', local_files_only=False):
277
  import torch
278
  if device is None:
279
+ device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
280
+ return cls(_resolve(source, local_files_only=local_files_only), device=device, dtype=dtype)
281
 
282
  def predict(self, text):
283
+ return self.predict_many([text])[0]
284
+
285
+ def predict_many(self, texts, *, batch_tokens=32768, max_batch=128, group=64):
286
+ """Model spans for each text. Windows of up to `group` texts are sorted by token length and packed into
287
+ batches of at most `max_batch` rows and `batch_tokens` padded tokens; per text, units, windows, averaging
288
+ and decode are the same as one window at a time."""
289
+ if min(batch_tokens, max_batch, group) < 1:
290
+ raise ValueError('batch_tokens, max_batch and group must be positive')
291
+ texts = list(texts)
292
+ result = []
293
+ for i in range(0, len(texts), group):
294
+ result += self._predict_group(texts[i:i + group], batch_tokens, max_batch)
295
+ return result
296
+
297
+ def _predict_group(self, texts, batch_tokens, max_batch):
298
+ torch, encoding = self._torch, self.encoding
299
+ docs, items = [], []
300
+ for d, text in enumerate(texts):
301
+ units, chunks = encoding.prepare(text)
302
+ docs.append((units, torch.zeros(len(units), 5), torch.zeros(len(units), 1)))
303
  for window in chunks:
304
+ encoded, first = encoding.encode([u.model for u in units[window['start']:window['end']]])
305
+ items.append((len(encoded['input_ids'][0]), d, window, encoded, first))
306
+ items.sort(key=lambda item: item[0])
307
+ with torch.inference_mode():
308
+ i = 0
309
+ while i < len(items):
310
+ j = i + 1 # sorted ascending, so items[j] sets the padded width of items[i:j + 1]
311
+ while j < len(items) and j - i < max_batch and (j - i + 1) * items[j][0] <= batch_tokens:
312
+ j += 1
313
+ part = items[i:j]
314
+ batch = encoding.tokenizer.pad([{k: v[0] for k, v in e.items()} for _, _, _, e, _ in part],
315
+ padding=True, return_tensors='pt')
316
  if batch['input_ids'].shape[1] > 512:
317
  raise ValueError('Batch exceeds encoder limit')
318
+ logits = self.model(**{k: v.to(self.device) for k, v in batch.items()}).logits.float().cpu()
319
+ for row, (_, d, window, _, first) in enumerate(part):
320
+ a, b = window['start'], window['end']
321
+ docs[d][1][a:b] += logits[row, first]
322
+ docs[d][2][a:b] += 1
323
+ i = j
324
+ result = []
325
+ for units, sums, counts in docs:
326
+ if (counts == 0).any():
327
+ raise ValueError('Missing inference units')
328
+ result.append(decode_bio(units, (sums / counts).tolist()) if units else [])
329
+ return result
330
 
331
  def rule_spans(self, text):
332
  return spans_from(self._scrub, text)
333
 
334
  def scrub(self, text):
335
+ return self.scrub_many([text])[0]
336
+
337
+ def scrub_many(self, texts):
338
+ texts = list(texts)
339
+ return [scrub_spans(text, self.rule_spans(text), model, threshold=self.threshold)
340
+ for text, model in zip(texts, self.predict_many(texts), strict=True)]
341
 
342
 
343
  def main(argv=None):
 
346
  parser = argparse.ArgumentParser(description='NERGAL hybrid PII cleaner')
347
  parser.add_argument('--repo', default=HUB_ID)
348
  parser.add_argument('--device', default=None)
349
+ parser.add_argument('--dtype', default='float32', choices=DTYPES)
350
  parser.add_argument('--local', action='store_true')
351
  args = parser.parse_args(argv)
352
+ nergal = Nergal.from_pretrained(args.repo, device=args.device, dtype=args.dtype,
353
+ local_files_only=args.local)
354
  text = sys.stdin.read()
355
  masked, counts = nergal.scrub(text)
356
  sys.stdout.write(masked)
test_nergal.py CHANGED
@@ -13,7 +13,7 @@ class NergalTests(unittest.TestCase):
13
  from nergal import GAP_IDS, GAPS, HUB_ID, RULES_SHA as PINNED, THRESHOLD, VERSION
14
  card = json.loads((HERE / 'hybrid.json').read_text())
15
  self.assertEqual(HUB_ID, 'SlayerLab/NERGAL')
16
- self.assertEqual(VERSION, '1.0.3')
17
  self.assertEqual(card['version'], VERSION)
18
  self.assertEqual(card['eval']['union_fp'], 123)
19
  self.assertEqual(card['eval']['rules_fp'], 98)
@@ -35,6 +35,26 @@ class NergalTests(unittest.TestCase):
35
  self.assertEqual(len(first), len(words))
36
  self.assertEqual([encoded.word_ids(0)[i] for i in first], [0, 1, 2])
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  def test_existing_placeholders_do_not_switch_the_rules_off(self):
39
  from nergal import rules
40
  text = 'Kontakt [Telefon], NIP 1234567802.' # invented, checksum-valid
 
13
  from nergal import GAP_IDS, GAPS, HUB_ID, RULES_SHA as PINNED, THRESHOLD, VERSION
14
  card = json.loads((HERE / 'hybrid.json').read_text())
15
  self.assertEqual(HUB_ID, 'SlayerLab/NERGAL')
16
+ self.assertEqual(VERSION, '1.1.0')
17
  self.assertEqual(card['version'], VERSION)
18
  self.assertEqual(card['eval']['union_fp'], 123)
19
  self.assertEqual(card['eval']['rules_fp'], 98)
 
35
  self.assertEqual(len(first), len(words))
36
  self.assertEqual([encoded.word_ids(0)[i] for i in first], [0, 1, 2])
37
 
38
+ def test_window_token_count_matches_the_encoded_window(self):
39
+ from transformers import AutoTokenizer
40
+ from nergal import Encoding
41
+ tokenizer = AutoTokenizer.from_pretrained(str(HERE), local_files_only=True, fix_mistral_regex=False)
42
+ encoding = Encoding(tokenizer)
43
+ text = ' '.join(f'Zdanie {i}: tel. 22 123 45 67,\nNIP 1234567802.' for i in range(120))
44
+ units, chunks = encoding.prepare(text)
45
+ self.assertGreater(len(chunks), 1)
46
+ for w in chunks:
47
+ encoded, _ = encoding.encode([u.model for u in units[w['start']:w['end']]])
48
+ self.assertEqual(w['tokens'], len(encoded['input_ids'][0]))
49
+ self.assertLessEqual(w['tokens'], 512)
50
+
51
+ def test_float16_is_opt_in_and_needs_an_accelerator(self):
52
+ from nergal import Nergal
53
+ with self.assertRaises(ValueError):
54
+ Nergal(HERE, device='cpu', dtype='float16')
55
+ with self.assertRaises(ValueError):
56
+ Nergal(HERE, dtype='bfloat16')
57
+
58
  def test_existing_placeholders_do_not_switch_the_rules_off(self):
59
  from nergal import rules
60
  text = 'Kontakt [Telefon], NIP 1234567802.' # invented, checksum-valid