Token Classification
Transformers
ONNX
Safetensors
Transformers.js
modernbert
pii
pii-detection
secret-detection
dlp
ai-agents
security
guardrails
presidio
llm-guard
litellm
nemo-guardrails
open-webui
data-loss-prevention
Instructions to use Tamarillo/pii-secrets-guard-small with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Tamarillo/pii-secrets-guard-small with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("token-classification", model="Tamarillo/pii-secrets-guard-small")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForTokenClassification tokenizer = AutoTokenizer.from_pretrained("Tamarillo/pii-secrets-guard-small") model = AutoModelForTokenClassification.from_pretrained("Tamarillo/pii-secrets-guard-small", device_map="auto") - Transformers.js
How to use Tamarillo/pii-secrets-guard-small with Transformers.js:
// npm i @huggingface/transformers import { pipeline } from '@huggingface/transformers'; // Allocate pipeline const pipe = await pipeline('token-classification', 'Tamarillo/pii-secrets-guard-small'); - Notebooks
- Google Colab
- Kaggle
Download scripts/train.py from Tamarillo/pii-secrets-guard-small: direct link, hf CLI and curl.
- Browser
- Download file 12.6 kB
-
https://huggingface.co/Tamarillo/pii-secrets-guard-small/resolve/main/scripts/train.py
- Command line
-
hf download hf://Tamarillo/pii-secrets-guard-small/scripts/train.py
-
curl -L -o train.py https://huggingface.co/Tamarillo/pii-secrets-guard-small/resolve/main/scripts/train.py
12.6 kB
| """Reproducible training script for Tamarillo pii-secrets-guard (ModernBertForTokenClassification). | |
| Selects the best checkpoint strictly by validation metrics (entity F1 with hard-negative FPR check) | |
| and writes clean safetensors release weights to --output-dir without leftover optimizer states. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import gc | |
| import json | |
| import os | |
| import shutil | |
| from pathlib import Path | |
| from typing import Any | |
| import numpy as np | |
| import torch | |
| from datasets import Dataset, concatenate_datasets, load_from_disk | |
| from seqeval.metrics import f1_score, precision_score, recall_score | |
| from transformers import ( | |
| AutoConfig, | |
| AutoModelForTokenClassification, | |
| AutoTokenizer, | |
| DataCollatorForTokenClassification, | |
| Trainer, | |
| TrainingArguments, | |
| ) | |
| from taxonomy import BIO_LABELS, ID2LABEL, LABEL2ID | |
| def load_jsonl(path: Path) -> list[dict[str, Any]]: | |
| rows = [] | |
| with path.open("r", encoding="utf-8") as f: | |
| for line in f: | |
| line = line.strip() | |
| if line: | |
| rows.append(json.loads(line)) | |
| return rows | |
| def align_char_spans_to_bio( | |
| text: str, | |
| spans: list[dict[str, Any]], | |
| offsets: list[tuple[int, int]], | |
| special_mask: list[int], | |
| ) -> list[int]: | |
| """ | |
| Exact character-offset to subword BIO tag alignment. | |
| First subword overlapping a span gets B-<LABEL>; subsequent subwords overlapping | |
| the same span get I-<LABEL>; special tokens get -100. | |
| """ | |
| labels = [-100 if sp == 1 else 0 for sp in special_mask] | |
| if not spans: | |
| return labels | |
| sorted_spans = sorted(spans, key=lambda s: s["start"]) | |
| s_idx = 0 | |
| n_spans = len(sorted_spans) | |
| started_spans: set[int] = set() | |
| for tok_i, ((t_start, t_end), is_spec) in enumerate(zip(offsets, special_mask)): | |
| if is_spec == 1 or t_start == t_end: | |
| labels[tok_i] = -100 | |
| continue | |
| # Advance span pointer past spans ending before this token | |
| while s_idx < n_spans and sorted_spans[s_idx]["end"] <= t_start: | |
| s_idx += 1 | |
| if s_idx >= n_spans: | |
| break | |
| sp = sorted_spans[s_idx] | |
| # Check overlap | |
| if t_start < sp["end"] and t_end > sp["start"]: | |
| ent = sp["label"] | |
| if s_idx not in started_spans: | |
| labels[tok_i] = LABEL2ID[f"B-{ent}"] | |
| started_spans.add(s_idx) | |
| else: | |
| labels[tok_i] = LABEL2ID[f"I-{ent}"] | |
| return labels | |
| def tokenize_dataset( | |
| rows: list[dict[str, Any]], | |
| tokenizer: Any, | |
| max_length: int, | |
| stride: int = 128, | |
| chunk_size: int = 4000, | |
| cache_dir: Path | None = None, | |
| ) -> Dataset: | |
| """Chunked, low-RAM tokenization with overflow windowing backed by disk Arrow shards.""" | |
| shards: list[Dataset] = [] | |
| for start_i in range(0, len(rows), chunk_size): | |
| chunk = rows[start_i : start_i + chunk_size] | |
| texts = [r["text"] for r in chunk] | |
| spans_list = [r.get("spans", []) for r in chunk] | |
| is_hard_neg = [1 if r.get("category") == "hard_negative" else 0 for r in chunk] | |
| enc = tokenizer( | |
| texts, | |
| truncation=True, | |
| max_length=max_length, | |
| stride=stride, | |
| return_overflowing_tokens=True, | |
| return_offsets_mapping=True, | |
| return_special_tokens_mask=True, | |
| ) | |
| sample_map = enc.pop("overflow_to_sample_mapping") | |
| offsets_all = enc.pop("offset_mapping") | |
| spec_all = enc.pop("special_tokens_mask") | |
| all_labels: list[list[int]] = [] | |
| all_hardneg_flags: list[int] = [] | |
| for i, orig_idx in enumerate(sample_map): | |
| lbls = align_char_spans_to_bio( | |
| texts[orig_idx], | |
| spans_list[orig_idx], | |
| offsets_all[i], | |
| spec_all[i], | |
| ) | |
| all_labels.append(lbls) | |
| all_hardneg_flags.append(is_hard_neg[orig_idx]) | |
| enc["labels"] = all_labels | |
| enc["is_hard_neg"] = all_hardneg_flags | |
| ds_shard = Dataset.from_dict(enc) | |
| if cache_dir is not None: | |
| shard_path = cache_dir / f"shard_{start_i}" | |
| ds_shard.save_to_disk(str(shard_path)) | |
| shards.append(load_from_disk(str(shard_path))) | |
| else: | |
| shards.append(ds_shard) | |
| del enc, offsets_all, spec_all, sample_map, texts, spans_list, all_labels, all_hardneg_flags | |
| gc.collect() | |
| return concatenate_datasets(shards) if len(shards) > 1 else shards[0] | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--base-model", type=str, required=True) | |
| parser.add_argument("--data-dir", type=str, required=True) | |
| parser.add_argument("--output-dir", type=str, required=True) | |
| parser.add_argument("--work-dir", type=str, default="/tmp/train_work") | |
| parser.add_argument("--max-length", type=int, default=2048) | |
| parser.add_argument("--epochs", type=float, default=3.0) | |
| parser.add_argument("--lr", type=float, default=3e-5) | |
| parser.add_argument("--batch-size", type=int, default=16) | |
| parser.add_argument("--grad-accum", type=int, default=2) | |
| parser.add_argument("--eval-batch-size", type=int, default=32) | |
| parser.add_argument("--weight-decay", type=float, default=0.01) | |
| parser.add_argument("--warmup-ratio", type=float, default=0.06) | |
| parser.add_argument("--seed", type=int, default=42) | |
| parser.add_argument("--grad-checkpointing", action="store_true") | |
| args = parser.parse_args() | |
| os.environ.setdefault("HF_HOME", "/tmp/hf") | |
| os.environ["TOKENIZERS_PARALLELISM"] = "true" | |
| data_dir = Path(args.data_dir) | |
| out_dir = Path(args.output_dir) | |
| work_dir = Path(args.work_dir) | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| work_dir.mkdir(parents=True, exist_ok=True) | |
| print(f"[train] Loading tokenizer & model from {args.base_model}") | |
| tokenizer = AutoTokenizer.from_pretrained(args.base_model, use_fast=True) | |
| config = AutoConfig.from_pretrained( | |
| args.base_model, | |
| num_labels=len(BIO_LABELS), | |
| id2label=ID2LABEL, | |
| label2id=LABEL2ID, | |
| ) | |
| # Remove any reference_compile setting that causes macOS/ONNX warnings | |
| if hasattr(config, "reference_compile"): | |
| config.reference_compile = False | |
| model = AutoModelForTokenClassification.from_pretrained( | |
| args.base_model, | |
| config=config, | |
| ignore_mismatched_sizes=True, | |
| ) | |
| if args.grad_checkpointing: | |
| model.gradient_checkpointing_enable() | |
| print("[train] Loading and tokenizing datasets ...") | |
| train_raw = load_jsonl(data_dir / "train.jsonl") | |
| val_raw = load_jsonl(data_dir / "val.jsonl") | |
| tr_cache = work_dir / "tok_train" | |
| va_cache = work_dir / "tok_val" | |
| train_ds = tokenize_dataset(train_raw, tokenizer, max_length=args.max_length, cache_dir=tr_cache) | |
| del train_raw | |
| gc.collect() | |
| val_ds = tokenize_dataset(val_raw, tokenizer, max_length=args.max_length, cache_dir=va_cache) | |
| del val_raw | |
| gc.collect() | |
| val_hard_neg_flags = list(val_ds["is_hard_neg"]) | |
| train_ds = train_ds.remove_columns(["is_hard_neg"]) | |
| val_ds = val_ds.remove_columns(["is_hard_neg"]) | |
| print(f"[train] Tokenized windows: train={len(train_ds):,} val={len(val_ds):,}") | |
| def compute_metrics(eval_pred: Any) -> dict[str, float]: | |
| logits, labels = eval_pred | |
| preds = np.argmax(logits, axis=-1) | |
| true_seqs: list[list[str]] = [] | |
| pred_seqs: list[list[str]] = [] | |
| hn_total_tokens = 0 | |
| hn_fp_tokens = 0 | |
| hn_docs = 0 | |
| hn_fp_docs = 0 | |
| for i, (pred_row, label_row) in enumerate(zip(preds, labels)): | |
| t_seq, p_seq = [], [] | |
| doc_fp = False | |
| is_hn = i < len(val_hard_neg_flags) and val_hard_neg_flags[i] == 1 | |
| for p_id, l_id in zip(pred_row, label_row): | |
| if l_id == -100: | |
| continue | |
| t_lbl = ID2LABEL[int(l_id)] | |
| p_lbl = ID2LABEL[int(p_id)] | |
| t_seq.append(t_lbl) | |
| p_seq.append(p_lbl) | |
| if is_hn: | |
| hn_total_tokens += 1 | |
| if p_lbl != "O": | |
| hn_fp_tokens += 1 | |
| doc_fp = True | |
| true_seqs.append(t_seq) | |
| pred_seqs.append(p_seq) | |
| if is_hn: | |
| hn_docs += 1 | |
| if doc_fp: | |
| hn_fp_docs += 1 | |
| micro_f1 = float(f1_score(true_seqs, pred_seqs, mode="strict", average="micro")) | |
| macro_f1 = float(f1_score(true_seqs, pred_seqs, mode="strict", average="macro")) | |
| prec = float(precision_score(true_seqs, pred_seqs, mode="strict", average="micro")) | |
| rec = float(recall_score(true_seqs, pred_seqs, mode="strict", average="micro")) | |
| hn_fpr_1k = (1000.0 * hn_fp_tokens / max(1, hn_total_tokens)) if hn_total_tokens else 0.0 | |
| hn_doc_fpr = (hn_fp_docs / max(1, hn_docs)) if hn_docs else 0.0 | |
| # Composite selection score: rewards high micro+macro F1 while penalizing hard-negative false alarms | |
| selection_score = 0.65 * micro_f1 + 0.35 * macro_f1 - 0.05 * hn_doc_fpr | |
| return { | |
| "micro_f1": round(micro_f1, 5), | |
| "macro_f1": round(macro_f1, 5), | |
| "precision": round(prec, 5), | |
| "recall": round(rec, 5), | |
| "hardneg_fpr_per_1k_tok": round(hn_fpr_1k, 4), | |
| "hardneg_doc_fpr": round(hn_doc_fpr, 5), | |
| "selection_score": round(selection_score, 5), | |
| } | |
| use_bf16 = torch.cuda.is_available() and torch.cuda.is_bf16_supported() | |
| eff_bs = max(1, args.batch_size * args.grad_accum) | |
| steps_per_epoch = max(1, len(train_ds) // eff_bs) | |
| eval_steps = max(25, min(1500, steps_per_epoch // 2)) | |
| print(f"[train] eff_bs={eff_bs}, steps_per_epoch={steps_per_epoch}, eval_steps={eval_steps}") | |
| import inspect | |
| ta_params = inspect.signature(TrainingArguments.__init__).parameters | |
| eval_kw = "eval_strategy" if "eval_strategy" in ta_params else "evaluation_strategy" | |
| ta_kwargs = dict( | |
| output_dir=str(work_dir), | |
| num_train_epochs=args.epochs, | |
| learning_rate=args.lr, | |
| per_device_train_batch_size=args.batch_size, | |
| per_device_eval_batch_size=args.eval_batch_size, | |
| gradient_accumulation_steps=args.grad_accum, | |
| weight_decay=args.weight_decay, | |
| warmup_ratio=args.warmup_ratio, | |
| lr_scheduler_type="cosine", | |
| bf16=use_bf16, | |
| fp16=(torch.cuda.is_available() and not use_bf16), | |
| eval_steps=eval_steps, | |
| save_strategy="steps", | |
| save_steps=eval_steps, | |
| save_total_limit=2, | |
| load_best_model_at_end=True, | |
| metric_for_best_model="selection_score", | |
| greater_is_better=True, | |
| logging_steps=max(10, eval_steps // 4), | |
| report_to="none", | |
| seed=args.seed, | |
| dataloader_num_workers=4, | |
| save_safetensors=True, | |
| group_by_length=True, | |
| ) | |
| ta_kwargs[eval_kw] = "steps" | |
| training_args = TrainingArguments(**ta_kwargs) | |
| collator = DataCollatorForTokenClassification(tokenizer=tokenizer, pad_to_multiple_of=8) | |
| tr_params = inspect.signature(Trainer.__init__).parameters | |
| tok_kw = "processing_class" if "processing_class" in tr_params else "tokenizer" | |
| tr_kwargs = dict( | |
| model=model, | |
| args=training_args, | |
| train_dataset=train_ds, | |
| eval_dataset=val_ds, | |
| data_collator=collator, | |
| compute_metrics=compute_metrics, | |
| ) | |
| tr_kwargs[tok_kw] = tokenizer | |
| trainer = Trainer(**tr_kwargs) | |
| train_result = trainer.train() | |
| val_metrics = trainer.evaluate() | |
| print("[train] Best validation metrics:", json.dumps(val_metrics, indent=2)) | |
| # Save clean final release weights (safetensors only, no optimizer states) | |
| trainer.save_model(str(out_dir)) | |
| tokenizer.save_pretrained(str(out_dir)) | |
| meta = { | |
| "base_model": args.base_model, | |
| "max_length": args.max_length, | |
| "epochs": args.epochs, | |
| "lr": args.lr, | |
| "train_windows": len(train_ds), | |
| "val_windows": len(val_ds), | |
| "train_runtime_sec": round(train_result.metrics.get("train_runtime", 0.0), 1), | |
| "best_val_metrics": val_metrics, | |
| } | |
| (out_dir / "training_summary.json").write_text(json.dumps(meta, indent=2), encoding="utf-8") | |
| # Clean up intermediate optimizer checkpoints to conserve disk | |
| shutil.rmtree(work_dir, ignore_errors=True) | |
| print(f"[train] Clean release weights saved to {out_dir}") | |
| if __name__ == "__main__": | |
| main() | |