jefftherover commited on
Commit
2354b7e
Β·
verified Β·
1 Parent(s): 7d93fba

Upload train_ner_pii.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. train_ner_pii.py +262 -0
train_ner_pii.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Starts from the v6 fine-tuned backbone (jefftherover/modernbert-pii-ner)
16
+ and trains a new 23-label classification head using the label mapping below.
17
+
18
+ Run with: uv run train_ner_pii.py
19
+ """
20
+
21
+ import json
22
+ import numpy as np
23
+ import trackio
24
+ from datasets import load_dataset
25
+ from transformers import (
26
+ AutoTokenizer,
27
+ AutoModelForTokenClassification,
28
+ TrainingArguments,
29
+ Trainer,
30
+ DataCollatorForTokenClassification,
31
+ EarlyStoppingCallback,
32
+ )
33
+ import evaluate
34
+
35
+ # ── Label mapping: ai4privacy 56 types β†’ 11 policy categories ────────────────
36
+ # Labels absent from this dict β†’ treated as O (not redacted)
37
+ LABEL_MAP = {
38
+ # PER β€” person names and titles
39
+ "FIRSTNAME": "PER",
40
+ "MIDDLENAME": "PER",
41
+ "LASTNAME": "PER",
42
+ "PREFIX": "PER", # Mr., Dr., Ms.
43
+ # ORG β€” organisation names
44
+ "COMPANYNAME": "ORG",
45
+ # EMAIL
46
+ "EMAIL": "EMAIL",
47
+ # PHONE
48
+ "PHONENUMBER": "PHONE",
49
+ # ADDRESS β€” postal / physical address components
50
+ "BUILDINGNUMBER": "ADDRESS",
51
+ "STREET": "ADDRESS",
52
+ "SECONDARYADDRESS": "ADDRESS", # apt / suite
53
+ "CITY": "ADDRESS",
54
+ "COUNTY": "ADDRESS",
55
+ "STATE": "ADDRESS",
56
+ "ZIPCODE": "ADDRESS",
57
+ # GOV_ID β€” government-issued identity numbers
58
+ "SSN": "GOV_ID",
59
+ # FINANCIAL_ID β€” payment cards, bank & crypto account identifiers
60
+ "CREDITCARDNUMBER": "FINANCIAL_ID",
61
+ "CREDITCARDCVV": "FINANCIAL_ID",
62
+ "IBAN": "FINANCIAL_ID",
63
+ "BIC": "FINANCIAL_ID",
64
+ "BITCOINADDRESS": "FINANCIAL_ID",
65
+ "ETHEREUMADDRESS": "FINANCIAL_ID",
66
+ "LITECOINADDRESS": "FINANCIAL_ID",
67
+ "MASKEDNUMBER": "FINANCIAL_ID",
68
+ # ACCOUNT_ID β€” bank / service account identifiers
69
+ "ACCOUNTNAME": "ACCOUNT_ID",
70
+ "ACCOUNTNUMBER": "ACCOUNT_ID",
71
+ "USERNAME": "ACCOUNT_ID",
72
+ # DEVICE_ID β€” device, vehicle, and network identifiers
73
+ "IP": "DEVICE_ID",
74
+ "IPV4": "DEVICE_ID",
75
+ "IPV6": "DEVICE_ID",
76
+ "MAC": "DEVICE_ID",
77
+ "PHONEIMEI": "DEVICE_ID",
78
+ "USERAGENT": "DEVICE_ID",
79
+ "VEHICLEVIN": "DEVICE_ID",
80
+ "VEHICLEVRM": "DEVICE_ID",
81
+ # DATE_OF_BIRTH β€” birth dates only (generic DATE β†’ O)
82
+ "DOB": "DATE_OF_BIRTH",
83
+ # CREDENTIALS β€” authentication secrets
84
+ "PASSWORD": "CREDENTIALS",
85
+ "PIN": "CREDENTIALS",
86
+ # Everything else (AGE, DATE, GENDER, JOBAREA, etc.) β†’ O
87
+ }
88
+
89
+ TARGET_LABELS = [
90
+ "PER", "ORG", "EMAIL", "PHONE", "ADDRESS",
91
+ "GOV_ID", "FINANCIAL_ID", "ACCOUNT_ID", "DEVICE_ID",
92
+ "DATE_OF_BIRTH", "CREDENTIALS",
93
+ ]
94
+
95
+ label_list = (
96
+ ["O"]
97
+ + sorted(f"B-{l}" for l in TARGET_LABELS)
98
+ + sorted(f"I-{l}" for l in TARGET_LABELS)
99
+ )
100
+ id2label = {i: l for i, l in enumerate(label_list)}
101
+ label2id = {l: i for i, l in id2label.items()}
102
+
103
+ # ── Config ────────────────────────────────────────────────────────────────────
104
+ MODEL_NAME = "jefftherover/modernbert-pii-ner" # v6 backbone, new head
105
+ DATASET_NAME = "ai4privacy/pii-masking-200k"
106
+ HUB_MODEL_ID = "jefftherover/modernbert-pii-mapped"
107
+ OUTPUT_DIR = "modernbert-pii-mapped"
108
+ MAX_LENGTH = 512
109
+
110
+ print(f"Labels ({len(label_list)}): {label_list}")
111
+
112
+ # ── Dataset ───────────────────────────────────────────────────────────────────
113
+ print("Loading dataset...")
114
+ full = load_dataset(DATASET_NAME, split="train")
115
+ en = full.filter(lambda x: x["language"] == "en")
116
+ print(f"English rows: {len(en)}")
117
+
118
+ splits = en.train_test_split(test_size=0.1, seed=42)
119
+ train_ds = splits["train"]
120
+ eval_ds = splits["test"]
121
+ print(f"Train: {len(train_ds)} Eval: {len(eval_ds)}")
122
+
123
+ # ── Tokenizer ─────────────────────────────────────────────────────────────────
124
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
125
+
126
+ # ── Tokenisation + label alignment ────────────────────────────────────────────
127
+ # Identical to v6 logic, with LABEL_MAP applied inside make_char_labels.
128
+
129
+ def make_char_labels(text, raw):
130
+ spans = json.loads(raw) if isinstance(raw, str) else raw
131
+ cl = ["O"] * len(text)
132
+ for span in spans:
133
+ s, e, src_lbl = int(span[0]), int(span[1]), span[2]
134
+ tgt_lbl = LABEL_MAP.get(src_lbl)
135
+ if tgt_lbl is None:
136
+ continue
137
+ for i in range(s, min(e, len(text))):
138
+ cl[i] = f"B-{tgt_lbl}" if i == s else f"I-{tgt_lbl}"
139
+ return cl
140
+
141
+ def tokenize_and_align(examples):
142
+ enc = tokenizer(
143
+ examples["source_text"],
144
+ truncation=True,
145
+ max_length=MAX_LENGTH,
146
+ return_offsets_mapping=True,
147
+ )
148
+ all_labels = []
149
+ for idx in range(len(examples["source_text"])):
150
+ text = examples["source_text"][idx]
151
+ cl = make_char_labels(text, examples["span_labels"][idx])
152
+ offsets = enc["offset_mapping"][idx]
153
+ labels, prev_end = [], None
154
+ for tok_s, tok_e in offsets:
155
+ if tok_s == tok_e:
156
+ labels.append(-100)
157
+ prev_end = None
158
+ else:
159
+ # Space-offset fix: ModernBERT absorbs leading space into token offset
160
+ real_s = tok_s
161
+ while real_s < tok_e and text[real_s] == " ":
162
+ real_s += 1
163
+ if prev_end is None or real_s > tok_s:
164
+ # Word-start token
165
+ lbl = cl[real_s] if real_s < len(cl) else "O"
166
+ labels.append(label2id.get(lbl, label2id["O"]))
167
+ else:
168
+ # Subword continuation: label entity spans as I-, ignore O
169
+ lbl = cl[real_s] if real_s < len(cl) else "O"
170
+ if lbl != "O":
171
+ labels.append(label2id.get(f"I-{lbl[2:]}", label2id["O"]))
172
+ else:
173
+ labels.append(-100)
174
+ prev_end = tok_e
175
+ all_labels.append(labels)
176
+ enc.pop("offset_mapping")
177
+ enc["labels"] = all_labels
178
+ return enc
179
+
180
+ print("Tokenising datasets...")
181
+ cols = train_ds.column_names
182
+ train_tok = train_ds.map(tokenize_and_align, batched=True, remove_columns=cols)
183
+ eval_tok = eval_ds.map(tokenize_and_align, batched=True, remove_columns=cols)
184
+
185
+ # ── Metrics ───────────────────────────────────────────────────────────────────
186
+ seqeval = evaluate.load("seqeval")
187
+
188
+ def compute_metrics(p):
189
+ logits, labels = p
190
+ preds = np.argmax(logits, axis=2)
191
+ true_preds = [[id2label[pp] for pp, ll in zip(pr, la) if ll != -100]
192
+ for pr, la in zip(preds, labels)]
193
+ true_labels = [[id2label[ll] for pp, ll in zip(pr, la) if ll != -100]
194
+ for pr, la in zip(preds, labels)]
195
+ res = seqeval.compute(predictions=true_preds, references=true_labels)
196
+ return {
197
+ "precision": res["overall_precision"],
198
+ "recall": res["overall_recall"],
199
+ "f1": res["overall_f1"],
200
+ "accuracy": res["overall_accuracy"],
201
+ }
202
+
203
+ # ── Model: v6 backbone + new 23-label head ────────────────────────────────────
204
+ print("Loading model (v6 backbone, new head)...")
205
+ model = AutoModelForTokenClassification.from_pretrained(
206
+ MODEL_NAME,
207
+ num_labels=len(label_list),
208
+ id2label=id2label,
209
+ label2id=label2id,
210
+ ignore_mismatched_sizes=True, # replaces the old 113-label head
211
+ )
212
+
213
+ # ── Trackio ───────────────────────────────────────────────────────────────────
214
+ trackio.init(project="modernbert-pii-mapped", name="modernbert-pii-mapped-v1")
215
+
216
+ # ── Training args ─────────────────────────────────────────────────────────────
217
+ # Lower LR than v6 (5e-5) to protect the pre-trained backbone while the new
218
+ # classifier head converges.
219
+ args = TrainingArguments(
220
+ output_dir=OUTPUT_DIR,
221
+ num_train_epochs=5,
222
+ per_device_train_batch_size=16,
223
+ per_device_eval_batch_size=32,
224
+ gradient_accumulation_steps=2, # effective batch = 32
225
+ learning_rate=3e-5,
226
+ weight_decay=0.01,
227
+ warmup_ratio=0.1,
228
+ lr_scheduler_type="cosine_with_restarts",
229
+ eval_strategy="steps",
230
+ eval_steps=500,
231
+ save_strategy="steps",
232
+ save_steps=500,
233
+ save_total_limit=3,
234
+ load_best_model_at_end=True,
235
+ metric_for_best_model="f1",
236
+ greater_is_better=True,
237
+ push_to_hub=True,
238
+ hub_model_id=HUB_MODEL_ID,
239
+ hub_strategy="every_save",
240
+ report_to="trackio",
241
+ run_name="modernbert-pii-mapped-v1",
242
+ fp16=True,
243
+ logging_steps=100,
244
+ dataloader_num_workers=2,
245
+ )
246
+
247
+ # ── Train ─────────────────────────────────────────────────────────────────────
248
+ trainer = Trainer(
249
+ model=model,
250
+ args=args,
251
+ train_dataset=train_tok,
252
+ eval_dataset=eval_tok,
253
+ data_collator=DataCollatorForTokenClassification(tokenizer),
254
+ compute_metrics=compute_metrics,
255
+ callbacks=[EarlyStoppingCallback(early_stopping_patience=3)],
256
+ )
257
+
258
+ print("Starting training...")
259
+ trainer.train()
260
+ trainer.push_to_hub()
261
+ trackio.finish()
262
+ print(f"Done! Model pushed to: https://huggingface.co/{HUB_MODEL_ID}")