File size: 11,136 Bytes
2354b7e
 
 
 
 
 
 
 
 
 
 
 
 
 
d7c0dbf
 
 
 
 
 
2354b7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7c0dbf
 
 
 
 
 
 
 
 
 
2354b7e
d7c0dbf
2354b7e
d7c0dbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2354b7e
 
d7c0dbf
 
 
 
2354b7e
 
 
 
d7c0dbf
 
2354b7e
 
 
 
 
d7c0dbf
125edf5
 
 
2354b7e
 
 
 
 
 
125edf5
 
2354b7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7c0dbf
2354b7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7c0dbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2354b7e
d7c0dbf
 
2354b7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7c0dbf
 
2354b7e
 
 
 
 
 
 
 
125edf5
2354b7e
 
 
 
 
 
 
 
d7c0dbf
2354b7e
 
 
 
 
 
 
 
 
 
 
 
 
d7c0dbf
2354b7e
 
125edf5
2354b7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# /// 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",
# ]
# ///
"""
ModernBERT PII NER β€” remapped to 11 company policy labels.

Trains from answerdotai/ModernBERT-base with a new 23-label classification
head.  Fixes the entity-scan alignment bug: instead of reading char_labels
only at real_s (the first non-space position), we now scan the entire token
span [real_s, tok_e) for the first entity character.  This ensures entities
that start after punctuation (e.g. "(Home" or ":John") are correctly labeled
rather than silently dropped.

Run with:  uv run train_ner_pii.py
"""

import json
import numpy as np
import trackio
from datasets import load_dataset
from transformers import (
    AutoTokenizer,
    AutoModelForTokenClassification,
    TrainingArguments,
    Trainer,
    DataCollatorForTokenClassification,
    EarlyStoppingCallback,
)
import evaluate

# ── Training label map: 56 source types β†’ 17 training categories ─────────────
# At inference, LABEL_MAP_INFER collapses these to 11 policy categories.
LABEL_MAP_TRAIN = {
    # PER β€” names only; PREFIX removed (standalone Mr./Dr. caused boundary FPs)
    "FIRSTNAME":           "PER",
    "MIDDLENAME":          "PER",
    "LASTNAME":            "PER",
    "PREFIX":              "O",
    # ORG
    "COMPANYNAME":         "ORG",
    # EMAIL
    "EMAIL":               "EMAIL",
    # PHONE
    "PHONENUMBER":         "PHONE",
    # ADDRESS
    "BUILDINGNUMBER":      "ADDRESS",
    "STREET":              "ADDRESS",
    "SECONDARYADDRESS":    "ADDRESS",
    "CITY":                "ADDRESS",
    "COUNTY":              "ADDRESS",
    "STATE":               "ADDRESS",
    "ZIPCODE":             "ADDRESS",
    # GOV_ID
    "SSN":                 "GOV_ID",
    # FINANCIAL_ID
    "CREDITCARDNUMBER":    "FINANCIAL_ID",
    "CREDITCARDCVV":       "FINANCIAL_ID",
    "IBAN":                "FINANCIAL_ID",
    "BIC":                 "FINANCIAL_ID",
    "BITCOINADDRESS":      "FINANCIAL_ID",
    "ETHEREUMADDRESS":     "FINANCIAL_ID",
    "LITECOINADDRESS":     "FINANCIAL_ID",
    "MASKEDNUMBER":        "FINANCIAL_ID",
    # ACCOUNT_ID β€” ACCOUNTNAME removed (too ambiguous)
    "ACCOUNTNAME":         "O",
    "ACCOUNTNUMBER":       "ACCOUNT_ID",
    "USERNAME":            "ACCOUNT_ID",
    # DEVICE_ID
    "IP":                  "DEVICE_ID",
    "IPV4":                "DEVICE_ID",
    "IPV6":                "DEVICE_ID",
    "MAC":                 "DEVICE_ID",
    "PHONEIMEI":           "DEVICE_ID",
    "USERAGENT":           "DEVICE_ID",
    "VEHICLEVIN":          "DEVICE_ID",
    "VEHICLEVRM":          "DEVICE_ID",
    # DATE_OF_BIRTH
    "DOB":                 "DATE_OF_BIRTH",
    # Training-only categories (model learns them; suppressed at inference)
    "AMOUNT":              "AMOUNT",
    "DATE":                "DATE",
    "NEARBYGPSCOORDINATE": "NEARBYGPSCOORDINATE",
    "PASSWORD":            "PASSWORD",
    "PIN":                 "PIN",
    "TIME":                "TIME",
    "URL":                 "URL",
    # Explicitly O
    "AGE":                 "O",
    "CURRENCY":            "O",
    "CURRENCYCODE":        "O",
    "CURRENCYNAME":        "O",
    "CURRENCYSYMBOL":      "O",
    "EYECOLOR":            "O",
    "GENDER":              "O",
    "SEX":                 "O",
    "HEIGHT":              "O",
    "JOBAREA":             "O",
    "JOBTITLE":            "O",
    "JOBTYPE":             "O",
    "ORDINALDIRECTION":    "O",
}

TRAIN_LABELS = [
    "ACCOUNT_ID", "ADDRESS", "AMOUNT", "DATE", "DATE_OF_BIRTH",
    "DEVICE_ID", "EMAIL", "FINANCIAL_ID", "GOV_ID", "NEARBYGPSCOORDINATE",
    "ORG", "PASSWORD", "PER", "PHONE", "PIN", "TIME", "URL",
]

label_list = (
    ["O"]
    + sorted(f"B-{l}" for l in TRAIN_LABELS)
    + sorted(f"I-{l}" for l in TRAIN_LABELS)
)
id2label = {i: l for i, l in enumerate(label_list)}
label2id = {l: i for i, l in id2label.items()}

# ── Config ────────────────────────────────────────────────────────────────────
MODEL_NAME   = "answerdotai/ModernBERT-base"        # train from base
DATASET_NAME = "jefftherover/pii-masking-200k-DOBfixed"
HUB_MODEL_ID = "jefftherover/modernbert-pii-mapped-v4"
OUTPUT_DIR   = "modernbert-pii-mapped-v4"
MAX_LENGTH   = 512

print(f"Labels ({len(label_list)}): {label_list}")

# ── Dataset ───────────────────────────────────────────────────────────────────
print("Loading dataset...")
en = load_dataset(DATASET_NAME, split="train")
print(f"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)}")

# ── Tokenizer ─────────────────────────────────────────────────────────────────
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)

# ── Tokenisation + label alignment ────────────────────────────────────────────
# Identical to v6 logic, with LABEL_MAP applied inside make_char_labels.

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, src_lbl = int(span[0]), int(span[1]), span[2]
        tgt_lbl = LABEL_MAP_TRAIN.get(src_lbl)
        if tgt_lbl is None:
            continue
        for i in range(s, min(e, len(text))):
            cl[i] = f"B-{tgt_lbl}" if i == s else f"I-{tgt_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
                continue
            # Space-offset fix: ModernBERT absorbs leading space into token offset
            real_s = tok_s
            while real_s < tok_e and text[real_s] == " ":
                real_s += 1
            is_word_start = prev_end is None or real_s > tok_s
            # Scan the full token span for the first entity character.
            # Fixes the case where an entity begins after punctuation with no
            # preceding space (e.g. "(Home Loan Account") β€” previously real_s
            # landed on "(" (O) and the entity was silently dropped.
            lbl = "O"
            for c in range(real_s, min(tok_e, len(cl))):
                if cl[c] != "O":
                    lbl = cl[c]
                    break
            if lbl == "O":
                labels.append(label2id["O"] if is_word_start else -100)
            else:
                labels.append(label2id.get(lbl, label2id["O"]))
            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)

# ── 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"],
    }

# ── Model ─────────────────────────────────────────────────────────────────────
print(f"Loading model (ModernBERT-base + new {len(label_list)}-label head)...")
model = AutoModelForTokenClassification.from_pretrained(
    MODEL_NAME,
    num_labels=len(label_list),
    id2label=id2label,
    label2id=label2id,
)

# ── Trackio ───────────────────────────────────────────────────────────────────
trackio.init(project="modernbert-pii-mapped", name="modernbert-pii-mapped-v4")

# ── Training args ─────────────────────────────────────────────────────────────
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.1,
    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_private_repo=False,
    hub_strategy="every_save",
    report_to="trackio",
    run_name="modernbert-pii-mapped-v4",
    fp16=True,
    logging_steps=100,
    dataloader_num_workers=2,
)

# ── 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: https://huggingface.co/{HUB_MODEL_ID}")