JanviMl commited on
Commit
77d857b
·
verified ·
1 Parent(s): d53d9a6

Upload rlhf_refinement.py

Browse files
Files changed (1) hide show
  1. rlhf_refinement.py +122 -0
rlhf_refinement.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer
4
+ import torch
5
+ import warnings
6
+ warnings.filterwarnings("ignore")
7
+
8
+ # Load the human evaluation dataset
9
+ df = pd.read_excel("final_comments_evaluations_latest.xlsx")
10
+
11
+ # Initialize the Granite 3.2-2B-Instruct model and tokenizer (from your existing setup)
12
+ model_name = "ibm-granite/granite-3.2-2b-instruct"
13
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
14
+ model = AutoModelForCausalLM.from_pretrained(model_name)
15
+ device = "cuda" if torch.cuda.is_available() else "cpu"
16
+ model.to(device)
17
+
18
+ # Define a simple reward model (mockup based on dataset metrics)
19
+ # In practice, this would be the trained reward model from Stage 3
20
+ def reward_model(paraphrase, original_scores):
21
+ # Mock reward calculation: adjust scores based on trends in the dataset
22
+ base_toxicity = original_scores["toxicity"]
23
+ base_empathy = original_scores["empathy"]
24
+ # Simulate improved paraphrasing: reduce toxicity, increase empathy
25
+ new_toxicity = max(0.1, base_toxicity - 0.2) # Reduce toxicity
26
+ new_empathy = min(0.9, base_empathy + 0.1) # Increase empathy
27
+ new_bias = original_scores["bias"]
28
+ new_hallucination = max(0.1, original_scores["hallucination"] - 0.1)
29
+ # Composite reward score (weights based on dataset analysis)
30
+ reward = 0.4 * new_empathy - 0.3 * new_toxicity - 0.2 * new_bias - 0.1 * new_hallucination
31
+ return reward, {"toxicity": new_toxicity, "empathy": new_empathy, "bias": new_bias, "hallucination": new_hallucination}
32
+
33
+ # Function to generate a paraphrase using your existing paraphrasing logic
34
+ def generate_paraphrase(comment, max_length=128):
35
+ prompt = (
36
+ "You are a content moderator tasked with rewriting toxic comments into neutral and constructive ones while maintaining the original meaning. "
37
+ "Follow these guidelines:\n"
38
+ "- Remove explicit hate speech, personal attacks, or offensive language.\n"
39
+ "- Keep the response neutral and professional.\n"
40
+ "- Ensure the rewritten comment retains the original intent but in a constructive tone.\n"
41
+ "- Match the length and brevity of the original toxic comment whenever possible. Keep the response short and to the point.\n\n"
42
+ "Examples:\n"
43
+ "Toxic: \"You're so dumb! You never understand anything!\"\n"
44
+ "Neutral: \"You might be misunderstanding this.\"\n"
45
+ "Toxic: \"This is the worst idea ever. Only an idiot would suggest this.\"\n"
46
+ "Neutral: \"I don’t think this idea works well.\"\n"
47
+ "Toxic: \"You’re useless.\"\n"
48
+ "Neutral: \"This isn’t helping much.\"\n"
49
+ "Toxic: \"Shut up.\"\n"
50
+ "Neutral: \"Let’s take a break from this.\"\n\n"
51
+ f"Now, rewrite this comment: \"{comment}\""
52
+ )
53
+ inputs = tokenizer(prompt, return_tensors="pt", max_length=max_length, truncation=True).to(device)
54
+ outputs = model.generate(
55
+ **inputs,
56
+ max_new_tokens=50,
57
+ num_beams=4,
58
+ early_stopping=True,
59
+ do_sample=False
60
+ )
61
+ paraphrase = tokenizer.decode(outputs[0], skip_special_tokens=True)
62
+ # Clean up the output by removing the prompt part
63
+ paraphrase = paraphrase.replace(prompt, "").strip()
64
+ if paraphrase.startswith("Neutral: "):
65
+ paraphrase = paraphrase[len("Neutral: "):].strip()
66
+ return paraphrase
67
+
68
+ # RLHF Loop
69
+ max_iterations = 5
70
+ reward_threshold = 0.2 # Target for acceptable paraphrases (based on dataset range -0.25 to 0.24)
71
+ results = []
72
+
73
+ for idx, row in df.iterrows():
74
+ original_comment = row["Comment"]
75
+ current_paraphrase = row["Paraphrase_Comment"]
76
+ current_reward = row["reward_score"]
77
+ current_scores = {
78
+ "toxicity": row["toxicity"],
79
+ "empathy": row["empathy"],
80
+ "bias": row["bias"],
81
+ "hallucination": row["hallucination"]
82
+ }
83
+
84
+ best_paraphrase = current_paraphrase
85
+ best_reward = current_reward
86
+ best_scores = current_scores.copy()
87
+
88
+ # Iteratively refine the paraphrase
89
+ for iteration in range(max_iterations):
90
+ # Generate a new paraphrase
91
+ new_paraphrase = generate_paraphrase(original_comment)
92
+ # Evaluate the new paraphrase with the reward model
93
+ new_reward, new_scores = reward_model(new_paraphrase, current_scores)
94
+
95
+ # If the new reward is better, update the best paraphrase
96
+ if new_reward > best_reward:
97
+ best_paraphrase = new_paraphrase
98
+ best_reward = new_reward
99
+ best_scores = new_scores
100
+
101
+ # Stop if the reward exceeds the threshold
102
+ if best_reward >= reward_threshold:
103
+ break
104
+
105
+ # Store the result
106
+ results.append({
107
+ "Comment": original_comment,
108
+ "Original_Paraphrase": current_paraphrase,
109
+ "Refined_Paraphrase": best_paraphrase,
110
+ "Original_Reward_Score": current_reward,
111
+ "Refined_Reward_Score": best_reward,
112
+ "Refined_Empathy": best_scores["empathy"],
113
+ "Refined_Toxicity": best_scores["toxicity"],
114
+ "Refined_Bias": best_scores["bias"],
115
+ "Refined_Hallucination": best_scores["hallucination"],
116
+ "Human_Evaluation_Reasoning": row["Human_Evaluation_Reasoning"]
117
+ })
118
+
119
+ # Save the results to a CSV file
120
+ results_df = pd.DataFrame(results)
121
+ results_df.to_csv("refined_paraphrases.csv", index=False)
122
+ print("Refinement complete. Results saved to refined_paraphrases.csv")