Spaces:
Runtime error
Runtime error
File size: 4,302 Bytes
23fbd2c ec3124e 23fbd2c ec3124e 23fbd2c fbc4d55 23fbd2c 3588849 23fbd2c 8861c10 23fbd2c 58a4585 23fbd2c 8861c10 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | import torch
import torch.nn as nn
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import gradio as gr
# Define categories (needed for harm category names)
categories = [
'Cybercrime', 'Economic Crime', 'Privacy Violation', 'Mental Manipulation',
'White-Collar Crime', 'Violence', 'Psychological Harm', 'Physical Harm',
'Insulting Behavior', 'Drugs', 'Endangering National Security',
'Disrupting Public Order', 'Human Trafficking', 'Discriminatory Behavior',
'Copyright Issues', 'Endangering Public Health', 'Sexual Content',
'Environmental Damage', 'Animal Abuse'
]
model_name = 'distilbert-base-uncased'
class MultiTaskModel(nn.Module):
def __init__(self, model_name, num_harm_categories=19):
super().__init__()
self.distilbert = AutoModelForSequenceClassification.from_pretrained(
model_name, num_labels=1
)
hidden_size = self.distilbert.config.hidden_size
self.distilbert.classifier = nn.Identity()
self.safety_head = nn.Linear(hidden_size, 1)
self.harm_head = nn.Linear(hidden_size, num_harm_categories)
def forward(self, input_ids, attention_mask, labels=None):
outputs = self.distilbert.distilbert(input_ids=input_ids, attention_mask=attention_mask)
hidden_state = outputs.last_hidden_state[:, 0]
hidden_state = self.distilbert.pre_classifier(hidden_state)
hidden_state = nn.ReLU()(hidden_state)
hidden_state = self.distilbert.dropout(hidden_state)
safety_logits = torch.sigmoid(self.safety_head(hidden_state))
harm_logits = self.harm_head(hidden_state)
combined_logits = torch.cat([safety_logits, harm_logits], dim=1)
return {"logits": combined_logits}
def predict_safety(prompt, response):
# Combine prompt and response
text = f"{prompt} [SEP] {response}"
# Tokenize
inputs = tokenizer(
text,
return_tensors="pt",
truncation=True,
padding=True,
max_length=256
)
# Get prediction
with torch.no_grad():
outputs = model(**inputs)
predictions = outputs['logits'][0]
# Extract safety score
safety_score = predictions[0].item()
safety_label = "Safe" if safety_score > 0.5 else "Unsafe"
# Extract harm categories
harm_scores = torch.sigmoid(predictions[1:])
# Get top harm categories (confidence > 30%)
harm_results = []
for i, score in enumerate(harm_scores):
if score > 0.3:
harm_results.append(f"{categories[i]}: {score:.1%}")
harm_text = ", ".join(harm_results) if harm_results else "No significant harm categories"
return f"{safety_label} (confidence: {safety_score:.1%})", harm_text
# Load the model
model = MultiTaskModel(model_name)
# Load state dict and remove 'module.' prefixes
state_dict = torch.load('safety_classifier_model.pth', map_location='cpu')
# Remove 'module.' prefix from keys (caused by DataParallel training)
new_state_dict = {}
for key, value in state_dict.items():
if key.startswith('module.'):
new_key = key[7:] # Remove 'module.' prefix
else:
new_key = key
new_state_dict[new_key] = value
model.load_state_dict(new_state_dict)
model.eval()
tokenizer = AutoTokenizer.from_pretrained('./tokenizer')
# Create Gradio interface
iface = gr.Interface(
fn=predict_safety,
inputs=[
gr.Textbox(label="Prompt", placeholder="What did the user ask?"),
gr.Textbox(label="Response", placeholder="How did the LLM respond?")
],
outputs=[
gr.Textbox(label="Safety Assessment"),
gr.Textbox(label="Harm Categories")
],
title="LLM Safety Classifier",
description="I fine-tuned a base model (DistilBERT) to predict whether an LLM response is safe or unsafe, and the category of harm. I achieved 92% accuracy on the validation set. To try it, enter a prompt and response below.\n\nFor more detail on the training process, see my [Jupyter notebook on Kaggle](https://www.kaggle.com/code/markkeavney/llm-safety-classifier).\n\nMark Keavney, 8/16/2025"
)
# Launch the interface
iface.launch(share=True) |