File size: 7,366 Bytes
6601375
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1ac1fe
6601375
 
 
 
 
 
 
 
 
7964618
6601375
 
 
 
 
7964618
6601375
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eceddee
 
6601375
 
 
 
 
b29c2e0
 
 
 
 
eceddee
 
 
7d93fba
 
b29c2e0
7d93fba
b29c2e0
 
 
7d93fba
 
 
 
 
 
 
 
 
 
6601375
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d93fba
6601375
7964618
7d93fba
 
 
 
 
 
6601375
 
b29c2e0
6601375
 
f1ac1fe
7964618
6601375
7964618
 
6601375
7964618
6601375
7964618
6601375
 
 
 
 
 
 
 
7d93fba
6601375
7964618
6601375
 
 
 
 
 
 
 
 
 
 
f1ac1fe
6601375
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# /// 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-<type> 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-<type>,
#     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}")