import torch import numpy as np import pandas as pd import matplotlib.pyplot as plt from transformers import (AutoModelForCausalLM, AutoTokenizer, MarianMTModel, MarianTokenizer, BertTokenizer, BertModel) from sklearn.pipeline import make_pipeline from sklearn.linear_model import LogisticRegression from sklearn.feature_extraction.text import TfidfVectorizer from lime.lime_text import LimeTextExplainer from scipy.stats import ks_2samp from rouge_score import rouge_scorer import warnings warnings.filterwarnings("ignore") class LLMEvaluator: def __init__(self, model_name='gpt2'): self.model_name = model_name self.model = AutoModelForCausalLM.from_pretrained(model_name) self.tokenizer = AutoTokenizer.from_pretrained(model_name) # For explainability self.explainer = LimeTextExplainer(class_names=['Negative', 'Positive']) self.vectorizer = TfidfVectorizer() self.classifier = LogisticRegression() self.pipeline = make_pipeline(self.vectorizer, self.classifier) # Placeholder for training data for explainability self.texts = [] self.labels = [] # For drift detection self.performance_data = pd.DataFrame() ### Robustness Evaluation ### def generate_adversarial_example(self, text, epsilon=0.01): inputs = self.tokenizer(text, return_tensors='pt') inputs_embeds = self.model.transformer.wte(inputs['input_ids']) inputs_embeds.requires_grad = True outputs = self.model(inputs_embeds=inputs_embeds, labels=inputs['input_ids']) loss = outputs.loss loss.backward() # Apply perturbation perturbation = epsilon * inputs_embeds.grad.sign() adversarial_embeds = inputs_embeds + perturbation # Generate adversarial output adversarial_outputs = self.model.generate(inputs_embeds=adversarial_embeds) adversarial_text = self.tokenizer.decode(adversarial_outputs[0], skip_special_tokens=True) return adversarial_text def calculate_ece(self, probabilities, true_labels, n_bins=10): bin_boundaries = np.linspace(0, 1, n_bins + 1) ece = 0.0 for i in range(n_bins): bin_lower = bin_boundaries[i] bin_upper = bin_boundaries[i + 1] bin_indices = np.where((probabilities > bin_lower) & (probabilities <= bin_upper))[0] if len(bin_indices) > 0: bin_accuracy = np.mean(true_labels[bin_indices]) bin_confidence = np.mean(probabilities[bin_indices]) ece += len(bin_indices) * np.abs(bin_confidence - bin_accuracy) ece /= len(probabilities) return ece ### Quality Assessment ### def compute_rouge_score(self, reference_text, generated_text): scorer = rouge_scorer.RougeScorer(['rouge1', 'rougeL'], use_stemmer=True) scores = scorer.score(reference_text, generated_text) return scores ### Fairness Evaluation ### def counterfactual_test(self, template_text, sensitive_word, counter_word): original_input = template_text.replace('[SENSITIVE]', sensitive_word) counter_input = template_text.replace('[SENSITIVE]', counter_word) inputs_original = self.tokenizer.encode(original_input, return_tensors='pt') inputs_counter = self.tokenizer.encode(counter_input, return_tensors='pt') output_original = self.model.generate(inputs_original) output_counter = self.model.generate(inputs_counter) text_original = self.tokenizer.decode(output_original[0], skip_special_tokens=True) text_counter = self.tokenizer.decode(output_counter[0], skip_special_tokens=True) return text_original, text_counter def calculate_eod(self, data, protected_attribute, true_label, prediction): group_a = data[data[protected_attribute] == 0] group_b = data[data[protected_attribute] == 1] tpr_a = group_a[group_a[true_label] == 1][prediction].mean() tpr_b = group_b[group_b[true_label] == 1][prediction].mean() eod = tpr_a - tpr_b return eod ### Explainability ### def train_explainability_model(self, texts, labels): self.texts = texts self.labels = labels self.pipeline.fit(texts, labels) def explain_prediction(self, text): exp = self.explainer.explain_instance(text, self.pipeline.predict_proba, num_features=6) return exp def visualize_attention(self, text): bert_tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') bert_model = BertModel.from_pretrained('bert-base-uncased', output_attentions=True) inputs = bert_tokenizer(text, return_tensors='pt') outputs = bert_model(**inputs) attentions = outputs.attentions # A tuple of tensors # Visualize attention for a specific layer and head layer = 0 head = 0 attention = attentions[layer][0, head].detach().numpy() plt.matshow(attention) plt.title(f'Attention weights - Layer {layer}, Head {head}') plt.show() ### Drift Detection ### def monitor_performance(self, dates, precision_values, recall_values): self.performance_data = pd.DataFrame({ 'date': dates, 'precision': precision_values, 'recall': recall_values }) plt.plot(self.performance_data['date'], self.performance_data['precision'], label='Precision') plt.plot(self.performance_data['date'], self.performance_data['recall'], label='Recall') plt.xlabel('Date') plt.ylabel('Metric Value') plt.title('Model Performance Over Time') plt.legend() plt.show() def ks_test_for_drift(self, training_data, new_data): statistic, p_value = ks_2samp(training_data, new_data) print("KS Statistic:", statistic) print("p-value:", p_value) if p_value < 0.05: print("Significant drift detected.") else: print("No significant drift detected.") # Example usage if __name__ == "__main__": evaluator = LLMEvaluator() ### Robustness Evaluation ### print("=== Robustness Evaluation ===") original_text = "Can you help me reset my password?" adversarial_text = evaluator.generate_adversarial_example(original_text) print("Original Text:", original_text) print("Adversarial Text:", adversarial_text) probabilities = np.array([0.9, 0.7, 0.2, 0.4, 0.85, 0.6]) true_labels = np.array([1, 1, 0, 0, 1, 0]) ece = evaluator.calculate_ece(probabilities, true_labels) print("Expected Calibration Error (ECE):", ece) ### Quality Assessment ### print("\n=== Quality Assessment ===") reference_summary = "The cat sat on the mat." generated_summary = "A cat was sitting on the mat." rouge_scores = evaluator.compute_rouge_score(reference_summary, generated_summary) print("ROUGE Scores:", rouge_scores) ### Fairness Evaluation ### print("\n=== Fairness Evaluation ===") template_text = "The [SENSITIVE] person applied for the job." sensitive_word = 'male' counter_word = 'female' output_original, output_counter = evaluator.counterfactual_test(template_text, sensitive_word, counter_word) print("Original Output:", output_original) print("Counterfactual Output:", output_counter) # Sample data for EOD calculation data = pd.DataFrame({ 'true_label': [1, 1, 0, 0, 1, 1], 'prediction': [1, 0, 0, 1, 1, 1], 'protected_attribute': [0, 1, 0, 1, 0, 1] # 0: Group A, 1: Group B }) eod = evaluator.calculate_eod(data, 'protected_attribute', 'true_label', 'prediction') print("Equal Opportunity Difference (EOD):", eod) ### Explainability ### print("\n=== Explainability ===") # Training data for the explainability model texts = ["I love this product", "This is the worst service ever"] labels = [1, 0] evaluator.train_explainability_model(texts, labels) # Explain a prediction text_to_explain = "I hate the quality of this item" explanation = evaluator.explain_prediction(text_to_explain) explanation.show_in_notebook() # Visualize attention weights evaluator.visualize_attention("The quick brown fox jumps over the lazy dog") ### Drift Detection ### print("\n=== Drift Detection ===") # Monitoring performance over time dates = pd.date_range(start='2023-01-01', periods=6, freq='M') precision_values = [0.95, 0.94, 0.90, 0.88, 0.85, 0.80] recall_values = [0.92, 0.91, 0.89, 0.85, 0.80, 0.75] evaluator.monitor_performance(dates, precision_values, recall_values) # KS Test for drift detection training_data = np.random.normal(0, 1, 1000) new_data = np.random.normal(0.5, 1, 1000) evaluator.ks_test_for_drift(training_data, new_data)