jefftherover commited on
Commit
0eb9532
Β·
verified Β·
1 Parent(s): 125edf5

v5: full fine-tune with CUSTOMER_NAME + PROJECT_NAME labels, 49k dataset

Browse files
Files changed (1) hide show
  1. train_ner_pii_newlabel.py +300 -0
train_ner_pii_newlabel.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # dependencies = [
3
+ # "transformers>=4.48.0",
4
+ # "datasets>=2.20.0",
5
+ # "evaluate>=0.4.0",
6
+ # "seqeval>=1.2.2",
7
+ # "trackio",
8
+ # "numpy<2.0",
9
+ # "accelerate>=0.34.0",
10
+ # ]
11
+ # ///
12
+ """
13
+ ModernBERT PII NER β€” remapped to 11 company policy labels.
14
+
15
+ Trains from answerdotai/ModernBERT-base with a new 23-label classification
16
+ head. Fixes the entity-scan alignment bug: instead of reading char_labels
17
+ only at real_s (the first non-space position), we now scan the entire token
18
+ span [real_s, tok_e) for the first entity character. This ensures entities
19
+ that start after punctuation (e.g. "(Home" or ":John") are correctly labeled
20
+ rather than silently dropped.
21
+
22
+ Run with: uv run train_ner_pii.py
23
+ """
24
+
25
+ import json
26
+ import numpy as np
27
+ import trackio
28
+ from datasets import load_dataset
29
+ from transformers import (
30
+ AutoTokenizer,
31
+ AutoModelForTokenClassification,
32
+ TrainingArguments,
33
+ Trainer,
34
+ DataCollatorForTokenClassification,
35
+ EarlyStoppingCallback,
36
+ )
37
+ import evaluate
38
+
39
+ # ── Training label map: 56 source types β†’ 17 training categories ─────────────
40
+ # At inference, LABEL_MAP_INFER collapses these to 11 policy categories.
41
+ LABEL_MAP_TRAIN = {
42
+ # PER β€” names only; PREFIX removed (standalone Mr./Dr. caused boundary FPs)
43
+ "FIRSTNAME": "PER",
44
+ "MIDDLENAME": "PER",
45
+ "LASTNAME": "PER",
46
+ "PREFIX": "O",
47
+ # ORG
48
+ "COMPANYNAME": "ORG",
49
+ # New labels
50
+ "CUSTOMER_NAME": "CUSTOMER_NAME",
51
+ "PROJECT_NAME": "PROJECT_NAME",
52
+ # EMAIL
53
+ "EMAIL": "EMAIL",
54
+ # PHONE
55
+ "PHONENUMBER": "PHONE",
56
+ # ADDRESS
57
+ "BUILDINGNUMBER": "ADDRESS",
58
+ "STREET": "ADDRESS",
59
+ "SECONDARYADDRESS": "ADDRESS",
60
+ "CITY": "ADDRESS",
61
+ "COUNTY": "ADDRESS",
62
+ "STATE": "ADDRESS",
63
+ "ZIPCODE": "ADDRESS",
64
+ # GOV_ID
65
+ "SSN": "GOV_ID",
66
+ # FINANCIAL_ID
67
+ "CREDITCARDNUMBER": "FINANCIAL_ID",
68
+ "CREDITCARDCVV": "FINANCIAL_ID",
69
+ "IBAN": "FINANCIAL_ID",
70
+ "BIC": "FINANCIAL_ID",
71
+ "BITCOINADDRESS": "FINANCIAL_ID",
72
+ "ETHEREUMADDRESS": "FINANCIAL_ID",
73
+ "LITECOINADDRESS": "FINANCIAL_ID",
74
+ "MASKEDNUMBER": "FINANCIAL_ID",
75
+ # ACCOUNT_ID β€” ACCOUNTNAME removed (too ambiguous)
76
+ "ACCOUNTNAME": "O",
77
+ "ACCOUNTNUMBER": "ACCOUNT_ID",
78
+ "USERNAME": "ACCOUNT_ID",
79
+ # DEVICE_ID
80
+ "IP": "DEVICE_ID",
81
+ "IPV4": "DEVICE_ID",
82
+ "IPV6": "DEVICE_ID",
83
+ "MAC": "DEVICE_ID",
84
+ "PHONEIMEI": "DEVICE_ID",
85
+ "USERAGENT": "DEVICE_ID",
86
+ "VEHICLEVIN": "DEVICE_ID",
87
+ "VEHICLEVRM": "DEVICE_ID",
88
+ # DATE_OF_BIRTH
89
+ "DOB": "DATE_OF_BIRTH",
90
+ # Training-only categories (model learns them; suppressed at inference)
91
+ "AMOUNT": "AMOUNT",
92
+ "DATE": "DATE",
93
+ "NEARBYGPSCOORDINATE": "NEARBYGPSCOORDINATE",
94
+ "PASSWORD": "PASSWORD",
95
+ "PIN": "PIN",
96
+ "TIME": "TIME",
97
+ "URL": "URL",
98
+ # Explicitly O
99
+ "AGE": "O",
100
+ "CURRENCY": "O",
101
+ "CURRENCYCODE": "O",
102
+ "CURRENCYNAME": "O",
103
+ "CURRENCYSYMBOL": "O",
104
+ "EYECOLOR": "O",
105
+ "GENDER": "O",
106
+ "SEX": "O",
107
+ "HEIGHT": "O",
108
+ "JOBAREA": "O",
109
+ "JOBTITLE": "O",
110
+ "JOBTYPE": "O",
111
+ "ORDINALDIRECTION": "O",
112
+ }
113
+
114
+ TRAIN_LABELS = [
115
+ "ACCOUNT_ID", "ADDRESS", "AMOUNT", "CUSTOMER_NAME", "DATE", "DATE_OF_BIRTH",
116
+ "DEVICE_ID", "EMAIL", "FINANCIAL_ID", "GOV_ID", "NEARBYGPSCOORDINATE",
117
+ "ORG", "PASSWORD", "PER", "PHONE", "PIN", "PROJECT_NAME", "TIME", "URL",
118
+ ]
119
+
120
+ label_list = (
121
+ ["O"]
122
+ + sorted(f"B-{l}" for l in TRAIN_LABELS)
123
+ + sorted(f"I-{l}" for l in TRAIN_LABELS)
124
+ )
125
+ id2label = {i: l for i, l in enumerate(label_list)}
126
+ label2id = {l: i for i, l in id2label.items()}
127
+
128
+ # ── Config ────────────────────────────────────────────────────────────────────
129
+ MODEL_NAME = "answerdotai/ModernBERT-base" # train from base
130
+ DATASET_NAME = "jefftherover/pii-masking-200k-newlabel"
131
+ HUB_MODEL_ID = "jefftherover/modernbert-pii-mapped-v5"
132
+ OUTPUT_DIR = "modernbert-pii-mapped-v5"
133
+ MAX_LENGTH = 512
134
+
135
+ print(f"Labels ({len(label_list)}): {label_list}")
136
+
137
+ # ── Dataset ───────────────────────────────────────────────────────────────────
138
+ print("Loading dataset...")
139
+ en = load_dataset(DATASET_NAME, split="train")
140
+ print(f"Rows: {len(en)}")
141
+
142
+ splits = en.train_test_split(test_size=0.1, seed=42)
143
+ train_ds = splits["train"]
144
+ eval_ds = splits["test"]
145
+ print(f"Train: {len(train_ds)} Eval: {len(eval_ds)}")
146
+
147
+ # ── Tokenizer ─────────────────────────────────────────────────────────────────
148
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
149
+
150
+ # ── Tokenisation + label alignment ────────────────────────────────────────────
151
+ # Identical to v6 logic, with LABEL_MAP applied inside make_char_labels.
152
+
153
+ def make_char_labels(text, raw):
154
+ spans = json.loads(raw) if isinstance(raw, str) else raw
155
+ cl = ["O"] * len(text)
156
+ for span in spans:
157
+ s, e, src_lbl = int(span[0]), int(span[1]), span[2]
158
+ tgt_lbl = LABEL_MAP_TRAIN.get(src_lbl)
159
+ if tgt_lbl is None:
160
+ continue
161
+ for i in range(s, min(e, len(text))):
162
+ cl[i] = f"B-{tgt_lbl}" if i == s else f"I-{tgt_lbl}"
163
+ return cl
164
+
165
+ def tokenize_and_align(examples):
166
+ enc = tokenizer(
167
+ examples["source_text"],
168
+ truncation=True,
169
+ max_length=MAX_LENGTH,
170
+ return_offsets_mapping=True,
171
+ )
172
+ all_labels = []
173
+ for idx in range(len(examples["source_text"])):
174
+ text = examples["source_text"][idx]
175
+ cl = make_char_labels(text, examples["span_labels"][idx])
176
+ offsets = enc["offset_mapping"][idx]
177
+ labels, prev_end = [], None
178
+ for tok_s, tok_e in offsets:
179
+ if tok_s == tok_e:
180
+ labels.append(-100)
181
+ prev_end = None
182
+ continue
183
+ # Space-offset fix: ModernBERT absorbs leading space into token offset
184
+ real_s = tok_s
185
+ while real_s < tok_e and text[real_s] == " ":
186
+ real_s += 1
187
+ is_word_start = prev_end is None or real_s > tok_s
188
+ # Scan the full token span for the first entity character.
189
+ # Fixes the case where an entity begins after punctuation with no
190
+ # preceding space (e.g. "(Home Loan Account") β€” previously real_s
191
+ # landed on "(" (O) and the entity was silently dropped.
192
+ lbl = "O"
193
+ for c in range(real_s, min(tok_e, len(cl))):
194
+ if cl[c] != "O":
195
+ lbl = cl[c]
196
+ break
197
+ if lbl == "O":
198
+ labels.append(label2id["O"] if is_word_start else -100)
199
+ else:
200
+ labels.append(label2id.get(lbl, label2id["O"]))
201
+ prev_end = tok_e
202
+ all_labels.append(labels)
203
+ enc.pop("offset_mapping")
204
+ enc["labels"] = all_labels
205
+ return enc
206
+
207
+ print("Tokenising datasets...")
208
+ cols = train_ds.column_names
209
+ train_tok = train_ds.map(tokenize_and_align, batched=True, remove_columns=cols)
210
+ eval_tok = eval_ds.map(tokenize_and_align, batched=True, remove_columns=cols)
211
+
212
+ # ── Metrics ───────────────────────────────────────────────────────────────────
213
+ seqeval = evaluate.load("seqeval")
214
+
215
+ def compute_metrics(p):
216
+ logits, labels = p
217
+ preds = np.argmax(logits, axis=2)
218
+ true_preds = [[id2label[pp] for pp, ll in zip(pr, la) if ll != -100]
219
+ for pr, la in zip(preds, labels)]
220
+ true_labels = [[id2label[ll] for pp, ll in zip(pr, la) if ll != -100]
221
+ for pr, la in zip(preds, labels)]
222
+ res = seqeval.compute(predictions=true_preds, references=true_labels)
223
+ return {
224
+ "precision": res["overall_precision"],
225
+ "recall": res["overall_recall"],
226
+ "f1": res["overall_f1"],
227
+ "accuracy": res["overall_accuracy"],
228
+ }
229
+
230
+ # ── Model ─────────────────────────────────────────────────────────────────────
231
+ # v5: full fine-tune β€” body + head trained end-to-end on the 49k PII dataset.
232
+ # This produces a PII-adapted body that becomes the frozen base for v6+.
233
+ #
234
+ # v6+ LoRA plan (re-enable this block, change MODEL_NAME to the v5 hub id):
235
+ # from peft import LoraConfig, get_peft_model, TaskType # add peft to deps too
236
+ # lora_config = LoraConfig(
237
+ # task_type=TaskType.TOKEN_CLS,
238
+ # r=16, lora_alpha=32, lora_dropout=0.1,
239
+ # target_modules=["Wqkv", "out_proj", "Wi", "Wo"],
240
+ # modules_to_save=["classifier"],
241
+ # bias="none",
242
+ # )
243
+ # model = get_peft_model(model, lora_config)
244
+ # model.print_trainable_parameters()
245
+ print(f"Loading model (ModernBERT-base + new {len(label_list)}-label head)...")
246
+ model = AutoModelForTokenClassification.from_pretrained(
247
+ MODEL_NAME,
248
+ num_labels=len(label_list),
249
+ id2label=id2label,
250
+ label2id=label2id,
251
+ )
252
+
253
+ # ── Trackio ───────────────────────────────────────────────────────────────────
254
+ trackio.init(project="modernbert-pii-mapped", name="modernbert-pii-mapped-v5")
255
+
256
+ # ── Training args ─────────────────────────────────────────────────────────────
257
+ args = TrainingArguments(
258
+ output_dir=OUTPUT_DIR,
259
+ num_train_epochs=5,
260
+ per_device_train_batch_size=16,
261
+ per_device_eval_batch_size=32,
262
+ gradient_accumulation_steps=2, # effective batch = 32
263
+ learning_rate=5e-5,
264
+ weight_decay=0.01,
265
+ warmup_ratio=0.1,
266
+ lr_scheduler_type="cosine_with_restarts",
267
+ eval_strategy="steps",
268
+ eval_steps=500,
269
+ save_strategy="steps",
270
+ save_steps=500,
271
+ save_total_limit=3,
272
+ load_best_model_at_end=True,
273
+ metric_for_best_model="f1",
274
+ greater_is_better=True,
275
+ push_to_hub=True,
276
+ hub_model_id=HUB_MODEL_ID,
277
+ hub_private_repo=False,
278
+ hub_strategy="every_save",
279
+ report_to="trackio",
280
+ run_name="modernbert-pii-mapped-v5",
281
+ fp16=True,
282
+ logging_steps=100,
283
+ dataloader_num_workers=2,
284
+ )
285
+
286
+ # ── Train ─────────────────────────────────────────────────────────────────────
287
+ trainer = Trainer(
288
+ model=model,
289
+ args=args,
290
+ train_dataset=train_tok,
291
+ eval_dataset=eval_tok,
292
+ data_collator=DataCollatorForTokenClassification(tokenizer),
293
+ compute_metrics=compute_metrics,
294
+ callbacks=[EarlyStoppingCallback(early_stopping_patience=3)],
295
+ )
296
+
297
+ print("Starting training...")
298
+ trainer.train()
299
+ trainer.push_to_hub()
300
+ print(f"Done! Model pushed to: https://huggingface.co/{HUB_MODEL_ID}")