# /// script # dependencies = [ # "transformers>=4.48.0", # "datasets>=2.20.0", # "evaluate>=0.4.0", # "seqeval>=1.2.2", # "trackio", # "numpy<2.0", # "accelerate>=0.34.0", # ] # /// import json import numpy as np import trackio from datasets import load_dataset from transformers import ( AutoTokenizer, AutoModelForTokenClassification, TrainingArguments, Trainer, DataCollatorForTokenClassification, EarlyStoppingCallback, ) import evaluate MODEL_NAME = "answerdotai/ModernBERT-base" DATASET_NAME = "ai4privacy/pii-masking-200k" HUB_MODEL_ID = "jefftherover/modernbert-pii-ner" OUTPUT_DIR = "modernbert-pii-ner" MAX_LENGTH = 512 # ── 1. Load full English dataset ───────────────────────────────────────────── print("Loading dataset...") full = load_dataset(DATASET_NAME, split="train") en = full.filter(lambda x: x["language"] == "en") print(f"English rows: {len(en)}") splits = en.train_test_split(test_size=0.1, seed=42) train_ds = splits["train"] eval_ds = splits["test"] print(f"Train: {len(train_ds)} Eval: {len(eval_ds)}") # 2. Dynamic label vocabulary from data print("Building label vocabulary...") all_bio = set() for ds in (train_ds, eval_ds): for ex in ds: all_bio.update(ex["mbert_bio_labels"]) label_list = ( ["O"] + sorted(l for l in all_bio if l.startswith("B-")) + sorted(l for l in all_bio if l.startswith("I-")) ) id2label = {i: l for i, l in enumerate(label_list)} label2id = {l: i for i, l in id2label.items()} print(f"Total labels: {len(label_list)}") # 3. Tokenizer tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME) # 4. Tokenisation + label alignment def make_char_labels(text, raw): spans = json.loads(raw) if isinstance(raw, str) else raw cl = ["O"] * len(text) for span in spans: s, e, lbl = int(span[0]), int(span[1]), span[2] if lbl == "O": continue for i in range(s, min(e, len(text))): cl[i] = f"B-{lbl}" if i == s else f"I-{lbl}" return cl def tokenize_and_align(examples): enc = tokenizer( examples["source_text"], truncation=True, max_length=MAX_LENGTH, return_offsets_mapping=True, ) all_labels = [] for idx in range(len(examples["source_text"])): text = examples["source_text"][idx] cl = make_char_labels(text, examples["span_labels"][idx]) offsets = enc["offset_mapping"][idx] labels, prev_end = [], None for tok_s, tok_e in offsets: if tok_s == tok_e: labels.append(-100); prev_end = None else: # ModernBERT (RoBERTa-style) tokenizer absorbs the preceding # space into the next token's offset (e.g. " Grey" has ts at # the space, not at 'G'). Strip leading spaces to find the # true first character of the word. real_s = tok_s while real_s < tok_e and text[real_s] == ' ': real_s += 1 # Word-boundary rule: new word if first token (prev_end None) # OR token had a leading space stripped (real_s > tok_s). if prev_end is None or real_s > tok_s: # Word-start: assign label from char array (B-, I-, or O). lbl = cl[real_s] if real_s < len(cl) else "O" labels.append(label2id.get(lbl, label2id["O"])) else: # Subword continuation (no leading space, within the same # word as the previous token). v6: if this subword falls # inside an entity span give it I- so the model # learns to sustain entity spans across subword boundaries. # Non-entity subword continuations keep -100 (ignored). lbl = cl[real_s] if real_s < len(cl) else "O" if lbl != "O": labels.append(label2id.get(f"I-{lbl[2:]}", label2id["O"])) else: labels.append(-100) prev_end = tok_e all_labels.append(labels) enc.pop("offset_mapping") enc["labels"] = all_labels return enc print("Tokenising datasets...") cols = train_ds.column_names train_tok = train_ds.map(tokenize_and_align, batched=True, remove_columns=cols) eval_tok = eval_ds.map(tokenize_and_align, batched=True, remove_columns=cols) # 5. Metrics seqeval = evaluate.load("seqeval") def compute_metrics(p): logits, labels = p preds = np.argmax(logits, axis=2) true_preds = [[id2label[pp] for pp, ll in zip(pr, la) if ll != -100] for pr, la in zip(preds, labels)] true_labels = [[id2label[ll] for pp, ll in zip(pr, la) if ll != -100] for pr, la in zip(preds, labels)] res = seqeval.compute(predictions=true_preds, references=true_labels) return { "precision": res["overall_precision"], "recall": res["overall_recall"], "f1": res["overall_f1"], "accuracy": res["overall_accuracy"], } # 6. Model print("Loading model...") model = AutoModelForTokenClassification.from_pretrained( MODEL_NAME, num_labels=len(label_list), id2label=id2label, label2id=label2id, ignore_mismatched_sizes=True, ) # 7. Trackio trackio.init(project="modernbert-pii-ner", name="modernbert-pii-ner-43k-v6") # ── 8. Training args ───────────────────────────────────────────────────────── # v6: subword continuation labeling fixed. # Previously only the first subword of each word was labeled; within-word # continuations got -100. Now entity subword continuations receive I-, # so the model learns to sustain entity spans across subword boundaries. # This directly targets the BOUNDARY fragmentation errors seen in v5 results # (e.g. "Hadley_Larson" → Had/ley/_/Larson each emitting B- instead of one span). args = TrainingArguments( output_dir=OUTPUT_DIR, num_train_epochs=5, per_device_train_batch_size=16, per_device_eval_batch_size=32, gradient_accumulation_steps=2, # effective batch = 32 learning_rate=5e-5, weight_decay=0.01, warmup_ratio=0.2, lr_scheduler_type="cosine_with_restarts", eval_strategy="steps", eval_steps=500, save_strategy="steps", save_steps=500, save_total_limit=3, load_best_model_at_end=True, metric_for_best_model="f1", greater_is_better=True, push_to_hub=True, hub_model_id=HUB_MODEL_ID, hub_strategy="every_save", report_to="trackio", run_name="modernbert-pii-ner-43k-v6", fp16=True, logging_steps=100, dataloader_num_workers=2, ) # 9. Train trainer = Trainer( model=model, args=args, train_dataset=train_tok, eval_dataset=eval_tok, data_collator=DataCollatorForTokenClassification(tokenizer), compute_metrics=compute_metrics, callbacks=[EarlyStoppingCallback(early_stopping_patience=3)], ) print("Starting training...") trainer.train() trainer.push_to_hub() print(f"Done! Model pushed to: {HUB_MODEL_ID}")