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)