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
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
import json, random, argparse
|
| 3 |
+
import numpy as np, torch
|
| 4 |
+
from datasets import load_dataset, Dataset
|
| 5 |
+
from transformers import AutoTokenizer, AutoModelForTokenClassification, TrainingArguments, Trainer, DataCollatorForTokenClassification
|
| 6 |
+
import evaluate
|
| 7 |
+
|
| 8 |
+
CATEGORIES = ["account_number","private_address","private_date","private_email","private_person","private_phone","private_url","secret","fax_number","credit_card_last4","company_contact_block"]
|
| 9 |
+
LABELS = ["O"]
|
| 10 |
+
for cat in CATEGORIES:
|
| 11 |
+
for p in ("B","I","E","S"): LABELS.append(f"{p}-{cat}")
|
| 12 |
+
label2id = {l:i for i,l in enumerate(LABELS)}
|
| 13 |
+
id2label = {i:l for l,i in label2id.items()}
|
| 14 |
+
NUM_LABELS = len(LABELS)
|
| 15 |
+
seqeval = evaluate.load("seqeval")
|
| 16 |
+
|
| 17 |
+
def compute_metrics(p):
|
| 18 |
+
predictions, labels = p
|
| 19 |
+
predictions = np.argmax(predictions, axis=2)
|
| 20 |
+
true_preds = [[id2label[pred] for pred,lab in zip(pred_row,lab_row) if lab!=-100] for pred_row,lab_row in zip(predictions,labels)]
|
| 21 |
+
true_labs = [[id2label[lab] for pred,lab in zip(pred_row,lab_row) if lab!=-100] for pred_row,lab_row in zip(predictions,labels)]
|
| 22 |
+
results = seqeval.compute(predictions=true_preds, references=true_labs)
|
| 23 |
+
return {"precision":results["overall_precision"],"recall":results["overall_recall"],"f1":results["overall_f1"],"accuracy":results["overall_accuracy"]}
|
| 24 |
+
|
| 25 |
+
from faker import Faker
|
| 26 |
+
fake = Faker()
|
| 27 |
+
|
| 28 |
+
def generate_synthetic_examples(n=5000, seed=42):
|
| 29 |
+
random.seed(seed); fake.seed_instance(seed)
|
| 30 |
+
examples = []
|
| 31 |
+
def add(text, spans): examples.append({"text":text,"spans":spans})
|
| 32 |
+
for _ in range(n):
|
| 33 |
+
r = random.random()
|
| 34 |
+
if r < 0.25:
|
| 35 |
+
fax = fake.numerify(text="(###) ###-####")
|
| 36 |
+
tmpl = random.choice([f"Please fax documents to {fax}.",f"Fax: {fax}\nAttn: Legal",f"Secure fax line: {fax}",f"You can reach us at phone (555) 123-4567 or fax {fax}.",f"Facsimile: {fax}"])
|
| 37 |
+
s = tmpl.find(fax); add(tmpl, [(s,s+len(fax),"fax_number")])
|
| 38 |
+
elif r < 0.5:
|
| 39 |
+
last4 = fake.numerify(text="####")
|
| 40 |
+
tmpl = random.choice([f"Card ending in {last4} charged.",f"Visa ****-****-****-{last4}",f"Last 4 digits: {last4}",f"Card on file ...{last4}",f"XXXX-XXXX-XXXX-{last4}"])
|
| 41 |
+
s = tmpl.find(last4); add(tmpl, [(s,s+len(last4),"credit_card_last4")])
|
| 42 |
+
elif r < 0.75:
|
| 43 |
+
company = fake.company(); addr = fake.street_address() + ", " + fake.city() + ", " + fake.state_abbr() + " " + fake.zipcode()
|
| 44 |
+
phone = fake.numerify(text="(###) ###-####"); email = fake.company_email()
|
| 45 |
+
tmpl = random.choice([f"{company}\n{addr}\nPhone: {phone}\nEmail: {email}",f"Contact:\n{company}\n{addr}\nTel: {phone}\n{email}",f"{company} HQ\n{addr}\nMain: {phone}\nInquiries: {email}"])
|
| 46 |
+
s = tmpl.find(company); e = tmpl.find(email)+len(email); add(tmpl, [(s,e,"company_contact_block")])
|
| 47 |
+
else:
|
| 48 |
+
person = fake.name(); email = fake.email(); fax = fake.numerify(text="(###) ###-####")
|
| 49 |
+
phone = fake.numerify(text="(###) ###-####"); last4 = fake.numerify(text="####")
|
| 50 |
+
company = fake.company(); addr = fake.street_address() + ", " + fake.city() + ", " + fake.state_abbr() + " " + fake.zipcode()
|
| 51 |
+
tmpl = random.choice([f"From: {person} <{email}>\nTo: Legal\nFax: {fax}\nPhone: {phone}\nCard: {last4}\n{company}\n{addr}",f"Client: {person}\nEmail: {email}\nFax: {fax}\nTel: {phone}\nPayment: ****{last4}\nEmployer: {company}\n{addr}"])
|
| 52 |
+
spans = []
|
| 53 |
+
for sub,lab in [(person,"private_person"),(email,"private_email"),(fax,"fax_number"),(phone,"private_phone"),(last4,"credit_card_last4"),(company,"company_contact_block"),(addr,"private_address")]:
|
| 54 |
+
idx = tmpl.find(sub)
|
| 55 |
+
if idx >= 0: spans.append((idx,idx+len(sub),lab))
|
| 56 |
+
add(tmpl, spans)
|
| 57 |
+
return examples
|
| 58 |
+
|
| 59 |
+
NEMOTRON_MAP = {"first_name":"private_person","last_name":"private_person","full_name":"private_person","name":"private_person","email":"private_email","phone_number":"private_phone","street_address":"private_address","address":"private_address","date_of_birth":"private_date","date":"private_date","credit_card_number":"account_number","ssn":"account_number","company_name":"company_contact_block","url":"private_url","secret":"secret","api_key":"secret","password":"secret","token":"secret"}
|
| 60 |
+
|
| 61 |
+
def load_nemotron_split(split, max_examples=10000):
|
| 62 |
+
ds = load_dataset("nvidia/Nemotron-PII", split=split)
|
| 63 |
+
examples = []
|
| 64 |
+
for ex in ds:
|
| 65 |
+
if len(examples) >= max_examples: break
|
| 66 |
+
text = ex["text"]
|
| 67 |
+
spans_raw = ex["spans"]
|
| 68 |
+
if isinstance(spans_raw, str):
|
| 69 |
+
spans_raw = json.loads(spans_raw)
|
| 70 |
+
spans = []
|
| 71 |
+
for sp in spans_raw:
|
| 72 |
+
lab = NEMOTRON_MAP.get(sp["label"])
|
| 73 |
+
if lab: spans.append((sp["start"],sp["end"],lab))
|
| 74 |
+
if spans: examples.append({"text":text,"spans":spans})
|
| 75 |
+
return examples
|
| 76 |
+
|
| 77 |
+
def tokenize_and_align(examples, tokenizer):
|
| 78 |
+
tokenized = tokenizer([ex["text"] for ex in examples], truncation=True, max_length=512, return_offsets_mapping=True)
|
| 79 |
+
all_labels = []
|
| 80 |
+
for i,ex in enumerate(examples):
|
| 81 |
+
offsets = tokenized["offset_mapping"][i]; labels = ["O"]*len(offsets)
|
| 82 |
+
for start,end,lab in ex["spans"]:
|
| 83 |
+
covered = [j for j,(ts,te) in enumerate(offsets) if ts is not None and te is not None and ts < end and te > start]
|
| 84 |
+
if not covered: continue
|
| 85 |
+
if len(covered)==1: labels[covered[0]] = f"S-{lab}"
|
| 86 |
+
else:
|
| 87 |
+
labels[covered[0]] = f"B-{lab}"
|
| 88 |
+
for idx in covered[1:-1]: labels[idx] = f"I-{lab}"
|
| 89 |
+
labels[covered[-1]] = f"E-{lab}"
|
| 90 |
+
label_ids = []
|
| 91 |
+
for j,(ts,te) in enumerate(offsets):
|
| 92 |
+
if ts is None and te is None: label_ids.append(-100)
|
| 93 |
+
else: label_ids.append(label2id.get(labels[j],0))
|
| 94 |
+
all_labels.append(label_ids)
|
| 95 |
+
tokenized["labels"] = all_labels
|
| 96 |
+
tokenized.pop("offset_mapping")
|
| 97 |
+
return tokenized
|
| 98 |
+
|
| 99 |
+
def main():
|
| 100 |
+
parser = argparse.ArgumentParser()
|
| 101 |
+
parser.add_argument("--model", default="openai/privacy-filter")
|
| 102 |
+
parser.add_argument("--output_model", default="narcolepticchicken/privacy-filter-enhanced")
|
| 103 |
+
parser.add_argument("--epochs", type=int, default=3)
|
| 104 |
+
parser.add_argument("--batch_size", type=int, default=8)
|
| 105 |
+
parser.add_argument("--grad_accum", type=int, default=4)
|
| 106 |
+
parser.add_argument("--lr", type=float, default=2e-5)
|
| 107 |
+
parser.add_argument("--max_synthetic", type=int, default=5000)
|
| 108 |
+
parser.add_argument("--max_nemotron_train", type=int, default=15000)
|
| 109 |
+
parser.add_argument("--max_nemotron_eval", type=int, default=2000)
|
| 110 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 111 |
+
args = parser.parse_args()
|
| 112 |
+
random.seed(args.seed); np.random.seed(args.seed); torch.manual_seed(args.seed)
|
| 113 |
+
tokenizer = AutoTokenizer.from_pretrained(args.model, trust_remote_code=True)
|
| 114 |
+
model = AutoModelForTokenClassification.from_pretrained(args.model, num_labels=NUM_LABELS, id2label=id2label, label2id=label2id, trust_remote_code=True, ignore_mismatched_sizes=True)
|
| 115 |
+
print("Generating synthetic data...")
|
| 116 |
+
synth = generate_synthetic_examples(args.max_synthetic, args.seed)
|
| 117 |
+
print(f"Synthetic examples: {len(synth)}")
|
| 118 |
+
print("Loading Nemotron-PII...")
|
| 119 |
+
nemotron_train = load_nemotron_split("train", args.max_nemotron_train)
|
| 120 |
+
nemotron_eval = load_nemotron_split("test", args.max_nemotron_eval)
|
| 121 |
+
print(f"Nemotron train: {len(nemotron_train)}, eval: {len(nemotron_eval)}")
|
| 122 |
+
train_examples = synth + nemotron_train
|
| 123 |
+
eval_examples = nemotron_eval
|
| 124 |
+
print("Tokenizing...")
|
| 125 |
+
train_tok = tokenize_and_align(train_examples, tokenizer)
|
| 126 |
+
eval_tok = tokenize_and_align(eval_examples, tokenizer)
|
| 127 |
+
train_ds = Dataset.from_dict(train_tok)
|
| 128 |
+
eval_ds = Dataset.from_dict(eval_tok)
|
| 129 |
+
data_collator = DataCollatorForTokenClassification(tokenizer)
|
| 130 |
+
training_args = TrainingArguments(
|
| 131 |
+
output_dir="/app/privacy-filter-checkpoints",
|
| 132 |
+
learning_rate=args.lr,
|
| 133 |
+
per_device_train_batch_size=args.batch_size,
|
| 134 |
+
per_device_eval_batch_size=args.batch_size,
|
| 135 |
+
num_train_epochs=args.epochs,
|
| 136 |
+
weight_decay=0.01,
|
| 137 |
+
eval_strategy="epoch",
|
| 138 |
+
save_strategy="epoch",
|
| 139 |
+
load_best_model_at_end=True,
|
| 140 |
+
metric_for_best_model="f1",
|
| 141 |
+
greater_is_better=True,
|
| 142 |
+
logging_strategy="steps",
|
| 143 |
+
logging_steps=50,
|
| 144 |
+
logging_first_step=True,
|
| 145 |
+
disable_tqdm=True,
|
| 146 |
+
push_to_hub=True,
|
| 147 |
+
hub_model_id=args.output_model,
|
| 148 |
+
report_to="trackio",
|
| 149 |
+
run_name=f"privacy-filter-enhanced-lr{args.lr}-bs{args.batch_size}-ep{args.epochs}",
|
| 150 |
+
project="privacy-filter-enhanced",
|
| 151 |
+
seed=args.seed,
|
| 152 |
+
bf16=True,
|
| 153 |
+
gradient_accumulation_steps=args.grad_accum,
|
| 154 |
+
dataloader_num_workers=4,
|
| 155 |
+
)
|
| 156 |
+
trainer = Trainer(model=model, args=training_args, train_dataset=train_ds, eval_dataset=eval_ds, processing_class=tokenizer, data_collator=data_collator, compute_metrics=compute_metrics)
|
| 157 |
+
print("Starting training...")
|
| 158 |
+
trainer.train()
|
| 159 |
+
print("Pushing to hub...")
|
| 160 |
+
trainer.push_to_hub()
|
| 161 |
+
print("Done!")
|
| 162 |
+
|
| 163 |
+
if __name__ == "__main__":
|
| 164 |
+
main()
|