!pip install --upgrade torchao
!pip install -q bitsandbytes accelerate
import torch
from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
base_model_id = "Qwen/Qwen2.5-7B-Instruct"
adapter_id = "durganani60/qwen2.5-7b-pii-financial"
quantization_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_compute_dtype=torch.bfloat16,
bnb_4bit_quant_type="nf4",
bnb_4bit_use_double_quant=True
)
print("Loading base model in 4-bit...")
tokenizer = AutoTokenizer.from_pretrained(base_model_id)
base_model = AutoModelForCausalLM.from_pretrained(
base_model_id,
quantization_config=quantization_config,
device_map="auto"
)
print("Loading fine-tuned PII adapter...")
model = PeftModel.from_pretrained(base_model, adapter_id)
system_prompt = (
"You are a PII redaction engine for financial documents. Find every span "
"of personally identifiable information in the document: names, companies, "
"dates, street addresses, account or routing numbers, emails, phone "
"numbers, and any other identifier tied to a person or organization. "
'Respond with a single JSON object with two keys: "redacted_text", the '
"full document with each PII span replaced by its type in uppercase "
'square brackets such as [NAME] or [EMAIL], and "entities", a list of '
'{"type": ..., "value": ...} objects, one per span in order of '
"appearance. Respond with only the JSON object."
)
user_input = "John Doe transferred $5,000 from account 123456789 on March 14, 2024."
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_input},
]
text = tokenizer.apply_chat_template(
messages, tokenize=False, add_generation_prompt=True
)
inputs = tokenizer(text, return_tensors="pt").to("cuda")
print("Generating prediction...")
outputs = model.generate(
**inputs, max_new_tokens=512, temperature=0.0, do_sample=False
)
response = tokenizer.decode(
outputs[0][inputs["input_ids"].shape[1] :], skip_special_tokens=True
)
print("\n--- Model Output ---")
print(response)
{
"redacted_text": "[NAME] transferred $5,000 from account [ACCOUNT_NUMBER] on [DATE].",
"entities":
[
{
"type": "name", "value": "John Doe"
},
{
"type": "account_number", "value": "123456789"
},
{
"type": "date", "value": "March 14, 2024"
}
]
}