| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| 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 |
|
|
| |
| 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)}") |
|
|
| |
| 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)}") |
|
|
| |
| tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME) |
|
|
| |
| 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: |
| |
| |
| |
| |
| real_s = tok_s |
| while real_s < tok_e and text[real_s] == ' ': |
| real_s += 1 |
| |
| |
| if prev_end is None or real_s > tok_s: |
| |
| lbl = cl[real_s] if real_s < len(cl) else "O" |
| labels.append(label2id.get(lbl, label2id["O"])) |
| else: |
| |
| |
| |
| |
| |
| 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) |
|
|
| |
| 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"], |
| } |
|
|
| |
| print("Loading model...") |
| model = AutoModelForTokenClassification.from_pretrained( |
| MODEL_NAME, |
| num_labels=len(label_list), |
| id2label=id2label, |
| label2id=label2id, |
| ignore_mismatched_sizes=True, |
| ) |
|
|
| |
| trackio.init(project="modernbert-pii-ner", name="modernbert-pii-ner-43k-v6") |
|
|
| |
| |
| |
| |
| |
| |
| |
| 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, |
| 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, |
| ) |
|
|
| |
| 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}") |
|
|