A context-aware PII anonymization model fine-tuned from Qwen2.5-0.5B-Instruct. Unlike traditional redaction tools that insert ugly [REDACTED] or <PERSON> placeholders, this model replaces personally identifiable information with realistic synthetic data while preserving the original grammar, formatting, tone, and semantic flow of the text.
This is Phase 1 of an enterprise grade PII anonymization pipeline. THIS CANNOT BE USED FOR ANY COMMERCIAL PURPOSE WITHOUT LICENSE APPROVAL FROM AI4PRIVACY. Phase 2 combines this model with Microsoft Presidio and GLiNER for production-grade, compliance-ready deployment.
Given any text containing personally identifiable information, the model outputs the same text with all PII replaced by realistic, contextually appropriate synthetic entities:
The model handles 55+ PII categories across corporate, medical, financial, conversational, and multilingual contexts.
Why Context-Aware Rewriting
Traditional PII tools fall into two camps, each with significant drawbacks:
Rule-based redaction (regex, Presidio alone) catches structured patterns well (SSNs, credit cards) but produces unreadable output filled with [PERSON] and [ADDRESS] tokens. This breaks downstream NLP tasks, makes documents unusable for analytics, and is immediately obvious to anyone reading the text.
Naive masking (simple find-and-replace) often breaks grammar, misses contextual PII like "my boss David" or "send it to the Baker Street office", and can't handle the same entity appearing in different syntactic roles.
This model combines both strengths: it understands context deeply enough to identify PII that rule-based systems miss, while generating natural-sounding replacements that maintain document utility. A medical record that says "Patient: Robert Williams, DOB: 1985-04-12" becomes "Patient: Michael Rodriguez, DOB: 1976-03-25" — still perfectly usable for analytics, training other models, or sharing with third parties.
Description: A synthetic, persona-grounded dataset for PII/PHI detection. Contains span-level annotations for 55+ PII/PHI categories across 50+ industries, generated with NVIDIA NeMo Data Designer using synthetic personas grounded in U.S. Census data. Includes both structured (forms, invoices) and unstructured (emails, free text) documents.
Categories covered: first_name, last_name, date_of_birth, street_address, email, phone_number, ssn, credit_card, company_name, vehicle_identifier, url, blood_type, employment_status, and 40+ more.
Size: 209,261 multilingual records (English, French, German, Italian)
License: AI4Privacy Free/Corporate License (see LICENSE.md)
Description: Built by AI4Privacy (Ai Suisse SA) using the p5y framework with human-in-the-loop validation. Features diverse real-world PII scenarios across multiple domains and languages. Contains span-level privacy masks with entity types and positions.
Categories covered: FIRSTNAME, LASTNAME, EMAIL, PHONE, STREETADDRESS, CITY, ZIPCODE, COUNTRY, JOBAREA, JOBTYPE, CREDITCARDNUMBER, IBAN, BITCOINADDRESS, VEHICLEVIN, USERAGENT, and 30+ more.
Data Engineering Pipeline
Neither dataset provides ready-made "input → synthetic output" pairs. A custom data engineering pipeline was built to transform both datasets into training-ready format.
The Challenge
Nvidia Nemotron-PII provides text (raw) + spans (PII positions with labels), but no synthetic replacements. The spans use Python-style single-quoted dictionaries (not JSON), requiring ast.literal_eval for parsing.
AI4Privacy provides source_text (raw) + target_text (with [LABEL] mask tokens, not synthetic data) + privacy_mask (PII values with positions and labels).
The Solution
Both datasets were processed through a label-aware synthetic data generation pipeline using Faker:
[Raw text + PII span annotations]
│
▼
[Parse spans (ast.literal_eval for Nvidia, JSON for AI4Privacy)]
│
▼
[Sort spans by position (descending) to preserve indices during replacement]
│
▼
[For each span: generate synthetic value via label→Faker mapping]
first_name → fake.first_name()
email → fake.email()
ssn → fake.ssn()
street_addr → fake.street_address()
phone → fake.phone_number()
... (55+ label types mapped)
│
▼
[Validate: non-empty, changed from original, structurally coherent]
│
▼
[Format as ChatML: system instruction + user input + assistant output]
Results: 99,994 valid pairs from Nvidia (6 skipped) + 209,231 from AI4Privacy (30 skipped) = 309,225 total training samples.
ChatML Format
Every training sample follows the Qwen ChatML template:
<|im_start|>system
You are an enterprise data privacy engine. Analyze the input text, identify all
Personally Identifiable Information (PII), and output the text with the PII seamlessly
replaced by realistic synthetic data. Maintain the exact original formatting, syntax,
and tone.<|im_end|>
<|im_start|>user
I, Jason, am applying for a financial services account. My date of birth is
1987-05-22. I live at 87 Avenida De La Estrella.<|im_end|>
<|im_start|>assistant
I, Jeffery, am applying for a financial services account. My date of birth is
1947-04-28. I live at 43321 Brittany Bypass.<|im_end|>
Model Architecture & Fine-Tuning
Base Model: Qwen2.5-0.5B-Instruct
Selected for its optimal balance of speed and linguistic capability at 500M parameters:
Architecture: Dense Causal LM with RoPE (Rotary Position Embedding), SwiGLU activation, and Grouped-Query Attention (GQA)
Context window: 2,048 tokens (sufficient for document-level PII rewriting)
License: Apache 2.0
QLoRA Configuration
The base model weights are frozen with 4-bit NormalFloat (NF4) quantization. Low-Rank Adaptation (LoRA) matrices are injected across all linear projections:
Passport xQyFZbWd belonging to Christopher Williams
9
Medical
Patient: Robert Williams, DOB: 1985-04-12, MRN: MED-2024-88451
Patient: Michael Rodriguez, DOB: 1976-03-25, MRN: MED-2024-88451
10
Employee
Name: Tanaka Yuki, SSN: 321-45-6789
Name: Williams James, SSN: 458-78-3375
11
Informal
Hey Lisa, it's Mike from the gym. Text me at 555-867-5309
Hey Michael, it's David from the gym. Text me at 412.938.3297x641
12
Hindi-English
Ramesh ji ka address hai 14, MG Road, Pune 411001
Lori ji ka address hai 92953 Michael Plaza Suite 825
Coherence check: All 12 samples passed — no empty outputs, no placeholder tokens, all outputs structurally coherent with the input.
Usage
Quick Start — Test It in 30 Seconds
python
1# pip install transformers torch accelerate23from transformers import AutoModelForCausalLM, AutoTokenizer
45MODEL_NAME ="AXONVERTEX-AI-RESEARCH/qwen2.5-0.5b-pii-anonymizer"67model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, device_map="auto")8tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)910defanonymize(text):11"""Anonymize PII in the given text and return the result."""12 messages =[13{"role":"system","content":(14"You are an enterprise data privacy engine. Analyze the input text, identify all "15"Personally Identifiable Information (PII), and output the text with the PII seamlessly "16"replaced by realistic synthetic data. Maintain the exact original formatting, syntax, "17"and tone."18)},19{"role":"user","content": text},20]21 inputs = tokenizer.apply_chat_template(22 messages, tokenize=True, add_generation_prompt=True, return_tensors="pt"23).to(model.device)2425 outputs = model.generate(26 inputs,27 max_new_tokens=512,28 temperature=0.3,29 top_p=0.9,30 do_sample=True,31)32return tokenizer.decode(outputs[0][inputs.shape[-1]:], skip_special_tokens=True)3334# Try it35result = anonymize("Hi, I'm John Doe. Email me at john.doe@acme.com or call +1-555-867-5309.")36print(result)
Run the Full Test Suite — See Results Across 12 PII Categories
Copy and run this script to test the model against names, emails, phones, addresses, national IDs, financial data, passports, medical records, employee records, informal text, and multilingual input:
python
1# pip install transformers torch accelerate23from transformers import AutoModelForCausalLM, AutoTokenizer
45MODEL_NAME ="AXONVERTEX-AI-RESEARCH/qwen2.5-0.5b-pii-anonymizer"6model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, device_map="auto")7tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)89SYSTEM_PROMPT =(10"You are an enterprise data privacy engine. Analyze the input text, identify all "11"Personally Identifiable Information (PII), and output the text with the PII seamlessly "12"replaced by realistic synthetic data. Maintain the exact original formatting, syntax, "13"and tone."14)1516TEST_CASES =[17("Names","Dear Mr. Arjun Mehta, your appointment with Dr. Priya Sharma is confirmed for July 15th."),18("Emails","For billing inquiries, contact sarah.johnson@globalfinance.com or accounts@globalfinance.com."),19("Phones","Call our Mumbai office at +91-22-4567-8901 or reach Raj directly on 9876543210."),20("Addresses","Ship the package to 42 Baker Street, London, NW1 6XE, United Kingdom."),21("National ID","Aadhaar verification complete for ID 2345-6789-0123 issued to Neha Gupta."),22("Financial","Payment processed on Visa ending 4829. Transaction ref: TXN-2024-09-17-0042."),23("Mixed PII","Hi, I'm David Chen (david.chen@techcorp.io, +1-415-555-0198). Please update my records."),24("Passport","Passport number L8472910 belonging to Maria Gonzalez expires on 2027-03-22."),25("Medical","Patient: Robert Williams, DOB: 1985-04-12, MRN: MED-2024-88451. Prescribed metformin 500mg."),26("Employee","Employee ID: EMP-30291, Name: Tanaka Yuki, Department: Engineering, SSN: 321-45-6789."),27("Informal","Hey Lisa, it's Mike from the gym. Text me at 555-867-5309 about Saturday's class!"),28("Hindi-English","Ramesh ji ka address hai 14, MG Road, Pune 411001. Unka number 9823456789 hai."),29]3031defanonymize(text):32 messages =[33{"role":"system","content": SYSTEM_PROMPT},34{"role":"user","content": text},35]36 inputs = tokenizer.apply_chat_template(37 messages, tokenize=True, add_generation_prompt=True, return_tensors="pt"38).to(model.device)39 outputs = model.generate(inputs, max_new_tokens=512, temperature=0.3, top_p=0.9, do_sample=True)40return tokenizer.decode(outputs[0][inputs.shape[-1]:], skip_special_tokens=True)4142print("="*80)43print("PII ANONYMIZER — FULL TEST SUITE")44print("="*80)4546for i,(category, text)inenumerate(TEST_CASES,1):47 result = anonymize(text)48print(f"\n── {i}. {category} ──")49print(f" INPUT: {text}")50print(f" OUTPUT: {result}")5152print("\n"+"="*80)53print("TEST COMPLETE")54print("="*80)
With Unsloth (2× Faster Inference, 60% Less Memory)
python
1# pip install "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"23from unsloth import FastLanguageModel
45model, tokenizer = FastLanguageModel.from_pretrained(6 model_name="AXONVERTEX-AI-RESEARCH/qwen2.5-0.5b-pii-anonymizer",7 max_seq_length=2048,8 dtype=None,# auto-detect9 load_in_4bit=True,# uses ~1.5GB VRAM10)11FastLanguageModel.for_inference(model)1213SYSTEM_PROMPT =(14"You are an enterprise data privacy engine. Analyze the input text, identify all "15"Personally Identifiable Information (PII), and output the text with the PII seamlessly "16"replaced by realistic synthetic data. Maintain the exact original formatting, syntax, "17"and tone."18)1920defanonymize(text):21 messages =[22{"role":"system","content": SYSTEM_PROMPT},23{"role":"user","content": text},24]25 inputs = tokenizer.apply_chat_template(26 messages, tokenize=True, add_generation_prompt=True, return_tensors="pt"27).to(model.device)28 outputs = model.generate(inputs, max_new_tokens=512, temperature=0.3, top_p=0.9, do_sample=True)29return tokenizer.decode(outputs[0][inputs.shape[-1]:], skip_special_tokens=True)3031print(anonymize("Call Dr. Sarah Chen at +44-20-7946-0958 or email s.chen@hospital.nhs.uk"))
Batch Processing — Anonymize Multiple Documents
python
1from transformers import AutoModelForCausalLM, AutoTokenizer
23MODEL_NAME ="AXONVERTEX-AI-RESEARCH/qwen2.5-0.5b-pii-anonymizer"4model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, device_map="auto")5tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)67SYSTEM_PROMPT =(8"You are an enterprise data privacy engine. Analyze the input text, identify all "9"Personally Identifiable Information (PII), and output the text with the PII seamlessly "10"replaced by realistic synthetic data. Maintain the exact original formatting, syntax, "11"and tone."12)1314defanonymize(text):15 messages =[16{"role":"system","content": SYSTEM_PROMPT},17{"role":"user","content": text},18]19 inputs = tokenizer.apply_chat_template(20 messages, tokenize=True, add_generation_prompt=True, return_tensors="pt"21).to(model.device)22 outputs = model.generate(inputs, max_new_tokens=512, temperature=0.3, top_p=0.9, do_sample=True)23return tokenizer.decode(outputs[0][inputs.shape[-1]:], skip_special_tokens=True)2425defanonymize_batch(texts):26"""Anonymize a list of texts and return results."""27 results =[]28for text in texts:29 results.append(anonymize(text))30return results
3132# Example: process a list of customer support tickets33tickets =[34"Customer Jane Smith (jane.smith@outlook.com) reported billing issue on account #4481-2290.",35"Technician Raj Patel visited 15 Elm Street, Apt 3B. Contact: +91-98765-43210.",36"Refund processed for order #ORD-2024-1847 to card ending 9012. Customer: Liu Wei.",37]3839anonymized = anonymize_batch(tickets)40for original, cleaned inzip(tickets, anonymized):41print(f"ORIGINAL: {original}")42print(f"CLEANED: {cleaned}")43print()
Process a File Line-by-Line
python
1from transformers import AutoModelForCausalLM, AutoTokenizer
23MODEL_NAME ="AXONVERTEX-AI-RESEARCH/qwen2.5-0.5b-pii-anonymizer"4model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, device_map="auto")5tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)67SYSTEM_PROMPT =(8"You are an enterprise data privacy engine. Analyze the input text, identify all "9"Personally Identifiable Information (PII), and output the text with the PII seamlessly "10"replaced by realistic synthetic data. Maintain the exact original formatting, syntax, "11"and tone."12)1314defanonymize(text):15 messages =[16{"role":"system","content": SYSTEM_PROMPT},17{"role":"user","content": text},18]19 inputs = tokenizer.apply_chat_template(20 messages, tokenize=True, add_generation_prompt=True, return_tensors="pt"21).to(model.device)22 outputs = model.generate(inputs, max_new_tokens=512, temperature=0.3, top_p=0.9, do_sample=True)23return tokenizer.decode(outputs[0][inputs.shape[-1]:], skip_special_tokens=True)2425input_file ="customer_data.txt"26output_file ="customer_data_anonymized.txt"2728withopen(input_file,"r")as f_in,open(output_file,"w")as f_out:29for line_num, line inenumerate(f_in,1):30 line = line.strip()31ifnot line:32 f_out.write("\n")33continue34 cleaned = anonymize(line)35 f_out.write(cleaned +"\n")36if line_num %10==0:37print(f"Processed {line_num} lines...")3839print(f"Done. Anonymized output saved to {output_file}")
Integration with Pandas DataFrames
python
1import pandas as pd
2from transformers import AutoModelForCausalLM, AutoTokenizer
3from tqdm import tqdm
45MODEL_NAME ="AXONVERTEX-AI-RESEARCH/qwen2.5-0.5b-pii-anonymizer"6model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, device_map="auto")7tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)89SYSTEM_PROMPT =(10"You are an enterprise data privacy engine. Analyze the input text, identify all "11"Personally Identifiable Information (PII), and output the text with the PII seamlessly "12"replaced by realistic synthetic data. Maintain the exact original formatting, syntax, "13"and tone."14)1516defanonymize(text):17ifnotisinstance(text,str)ornot text.strip():18return text
19 messages =[20{"role":"system","content": SYSTEM_PROMPT},21{"role":"user","content": text},22]23 inputs = tokenizer.apply_chat_template(24 messages, tokenize=True, add_generation_prompt=True, return_tensors="pt"25).to(model.device)26 outputs = model.generate(inputs, max_new_tokens=512, temperature=0.3, top_p=0.9, do_sample=True)27return tokenizer.decode(outputs[0][inputs.shape[-1]:], skip_special_tokens=True)2829# Load your data30df = pd.read_csv("customers.csv")3132# Anonymize specific columns33tqdm.pandas(desc="Anonymizing")34df["name_clean"]= df["full_name"].progress_apply(anonymize)35df["email_clean"]= df["email"].progress_apply(anonymize)36df["notes_clean"]= df["support_notes"].progress_apply(anonymize)3738# Save39df.to_csv("customers_anonymized.csv", index=False)40print(f"Anonymized {len(df)} rows.")
Recommended Generation Parameters
Parameter
Value
Why
temperature
0.3
Low randomness for consistent PII replacement
top_p
0.9
Nucleus sampling for natural-sounding output
max_new_tokens
512
Sufficient for most document chunks
do_sample
True
Required for temperature/top_p to take effect
Known Limitations
This is a Phase 1 model. Honest assessment of current limitations:
Occasional artifact tokens: Rare garbage tokens (e.g., "xQZo") can appear before synthetic names. Occurs in <5% of outputs.
Over-replacement: Sometimes replaces non-PII context (e.g., "Mumbai" → "Port Michaelborough", "Engineering" → "Engineer, technical sales"). The model can be too aggressive.
Format-unaware replacements: Aadhaar numbers replaced with non-numeric strings, postal codes with random characters. The model doesn't always respect the format constraints of specific ID types.
Missed PII: Card endings ("4829"), MRN numbers, and some phone numbers in Hindi-English text were not replaced.
English-primary: While the training data includes French, German, and Italian text, the model performs best on English. Multilingual coverage is inconsistent.
No deterministic guarantees: As a generative model, outputs can vary between runs. Not suitable as a sole compliance mechanism.
These limitations are precisely why Phase 2 adds Presidio as a pre/post-processing safety net.
Phase 2 Roadmap
Phase 2 wraps this model in a production-ready serving architecture:
[Raw Text Input]
│
▼
[Microsoft Presidio Analyzer] → Detect PII with high-precision rules
│
▼
[GLiNER NER Model] → Catch contextual PII that rules miss
│
▼
[This Fine-Tuned Model] → Generate natural synthetic replacements
│
▼
[Presidio Analyzer (2nd pass)] → Verify no PII leaked through
│
▼
[Clean Output via FastAPI]
Presidio handles the "don't miss anything" job (structured PII: SSNs, credit cards, IBANs)
GLiNER handles contextual entity recognition
This model handles the "make it read naturally" job
The second Presidio pass acts as a compliance safety net
License
This model is released under a composite license reflecting the licenses of all components used in training. See LICENSE.md for complete terms.
Component
License
Commercial Use
Qwen2.5-0.5B-Instruct (base model)
Apache 2.0
Yes
nvidia/Nemotron-PII (dataset)
CC-BY-4.0
Yes, with attribution
ai4privacy/pii-masking-200k (dataset)
AI4Privacy Free/Corporate License
Free for individuals and small businesses (≤3 employees). Larger organizations require a corporate license from licensing@ai4privacy.com
Unsloth (training framework)
Apache 2.0
Yes
Model weights (this repository)
Subject to the most restrictive upstream license
See LICENSE.md
Important: If you are a commercial entity with more than 3 employees, you must obtain a corporate license from AI4Privacy before using this model in production. Contact licensing@ai4privacy.com.
Citation
If you use this model in your research or products, please cite: