-
Notifications
You must be signed in to change notification settings - Fork 1
/
loggers.py
213 lines (181 loc) · 8.76 KB
/
loggers.py
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import os
import wandb
import pytz
from datetime import datetime
import pandas as pd
class WandBLogger:
"""WandB logger."""
def __init__(self, args, system_prompt):
save_path = "wandb/"+ os.path.basename(args.init_defense_prompt_path) +"/"+ args.target_model + "/" + args.scenario + "/"
if not os.path.exists(save_path):
os.makedirs(save_path)
self.logger = wandb.init(
dir = save_path ,
project = "jailbreak-llms",
config = {
"defense_model" : args.defense_model,
"target_model" : args.target_model,
"judge_model": args.judge_model,
"keep_last_n": args.keep_last_n,
"system_prompt": system_prompt,
"scenario": args.scenario,
"n_iter": args.n_iterations,
"n_streams": args.n_streams,
}
)
print(self.logger.dir)
# self.is_jailbroken = False
self.best_defense_prompt_list = []
self.best_defense_improv_list = []
self.init_score_list = []
self.score_list = []
self.defense_success_num = 0
self.table = pd.DataFrame()
self.total_sample_number = 0
def log(self, iteration: int, defense_prompt: str,defense_improv: str, qs_list : list, image_path_list: list,
new_response_list: list, new_judge_scores_list: list, init_judge_scores_list: list,):
defense_prompt_list = [defense_prompt] *len(new_response_list)
defense_improv_list = [defense_improv] *len(new_response_list)
sameple_id_list = [i+1 for i in range(len(new_response_list))]
df = pd.DataFrame(sameple_id_list)
df["defense_prompt_list"] = defense_prompt_list
df["defense_improv_list"] = defense_improv_list
df["targetvlm_response"] = new_response_list
df["final_judge_scores"] = new_judge_scores_list
df['init_judge_scores'] = init_judge_scores_list
df["iter"] = iteration
df['query'] = qs_list
df['image'] = image_path_list
df["conv_num"] = [i+1 for i in range(len(new_response_list))]
self.total_sample_number += 1
self.table = pd.concat([self.table, df])
self.score_list+= new_judge_scores_list
self.init_score_list += init_judge_scores_list
cur_defense_success_num = 0
for score in new_judge_scores_list:
if score == 1:
cur_defense_success_num += 1
else:
pass
self.defense_success_num += cur_defense_success_num
self.best_defense_prompt_list.append(defense_prompt)
self.best_defense_improv_list.append(defense_improv)
self.logger.log({
"iteration": str(iteration),
"defense_success_num": self.defense_success_num,
"best_defense_prompt": defense_prompt,
"best_defense_improv": defense_improv})
self.print_summary_stats(iteration)
def finish(self):
self.print_final_summary_stats()
self.logger.finish()
def print_summary_stats(self, iter):
df = self.table
mean_score_for_iter = df[df['iter'] == iter]["final_judge_scores"].mean()
max_score_for_iter = df[df['iter'] == iter]["final_judge_scores"].max()
min_score_for_iter = df[df['iter'] == iter]["final_judge_scores"].min()
print(f"{'='*14} SUMMARY STATISTICS {'='*14}")
print(f"Mean/Max/Min Score for iteration: {mean_score_for_iter:.1f}, {max_score_for_iter}, {min_score_for_iter}")
print(f"Number of defense success: {self.defense_success_num}/{self.total_sample_number}")
def print_final_summary_stats(self):
print(f"{'='*8} FINAL SUMMARY STATISTICS {'='*8}")
df = self.table
if "final_judge_scores" in self.table.columns:
max_score = df["final_judge_scores"].max()
min_score = df["final_judge_scores"].min()
mean_score = df["final_judge_scores"].mean()
print(f"Max Score: {max_score}")
print(f"Min Score: {min_score}")
print(f"Mean Score: {mean_score}")
print(f"FINAL_DEFENSE_PROMPT:\n\n{self.best_defense_prompt_list}\n\n")
print(f"INIT_SCORE:\n\n{self.init_score_list }\n\n")
print(f"FINAL_SCORE:\n\n{self.score_list }\n\n")
self.table.to_csv(self.logger.dir+"/final_table.csv", index=False)
class FigStepWandBLogger:
"""WandB logger."""
def __init__(self, args, system_prompt):
save_path = "figstep_wandb/"+ os.path.basename(args.init_defense_prompt_path) +"/"+ args.target_model + "/" + args.scenario + "/"
if not os.path.exists(save_path):
os.makedirs(save_path)
self.logger = wandb.init(
dir = save_path ,
project = "jailbreak-llms",
config = {
"defense_model" : args.defense_model,
"target_model" : args.target_model,
"judge_model": args.judge_model,
"keep_last_n": args.keep_last_n,
"system_prompt": system_prompt,
"scenario": args.scenario,
"n_iter": args.n_iterations,
"n_streams": args.n_streams,
}
)
print(self.logger.dir)
# self.is_jailbroken = False
self.best_defense_prompt_list = []
self.best_defense_improv_list = []
self.init_score_list = []
self.score_list = []
self.defense_success_num = 0
self.table = pd.DataFrame()
self.total_sample_number = 0
def log(self, iteration: int, defense_prompt: str,defense_improv: str, qs_list : list, image_path_list: list,
new_response_list: list, new_judge_scores_list: list, init_judge_scores_list: list,):
defense_prompt_list = [defense_prompt] *len(new_response_list)
defense_improv_list = [defense_improv] *len(new_response_list)
sameple_id_list = [i+1 for i in range(len(new_response_list))]
df = pd.DataFrame(sameple_id_list)
df["defense_prompt_list"] = defense_prompt_list
df["defense_improv_list"] = defense_improv_list
df["targetvlm_response"] = new_response_list
df["final_judge_scores"] = new_judge_scores_list
df['init_judge_scores'] = init_judge_scores_list
df["iter"] = iteration
df['query'] = qs_list
df['image'] = image_path_list
df["conv_num"] = [i+1 for i in range(len(new_response_list))]
self.total_sample_number += 1
self.table = pd.concat([self.table, df])
self.score_list+= new_judge_scores_list
self.init_score_list += init_judge_scores_list
cur_defense_success_num = 0
for score in new_judge_scores_list:
if score == 1:
cur_defense_success_num += 1
else:
pass
self.defense_success_num += cur_defense_success_num
self.best_defense_prompt_list.append(defense_prompt)
self.best_defense_improv_list.append(defense_improv)
self.logger.log({
"iteration": str(iteration),
"defense_success_num": self.defense_success_num,
"best_defense_prompt": defense_prompt,
"best_defense_improv": defense_improv})
self.print_summary_stats(iteration)
def finish(self):
self.print_final_summary_stats()
self.logger.finish()
def print_summary_stats(self, iter):
df = self.table
mean_score_for_iter = df[df['iter'] == iter]["final_judge_scores"].mean()
max_score_for_iter = df[df['iter'] == iter]["final_judge_scores"].max()
min_score_for_iter = df[df['iter'] == iter]["final_judge_scores"].min()
print(f"{'='*14} SUMMARY STATISTICS {'='*14}")
print(f"Mean/Max/Min Score for iteration: {mean_score_for_iter:.1f}, {max_score_for_iter}, {min_score_for_iter}")
print(f"Number of defense success: {self.defense_success_num}/{self.total_sample_number}")
def print_final_summary_stats(self):
print(f"{'='*8} FINAL SUMMARY STATISTICS {'='*8}")
df = self.table
if "final_judge_scores" in self.table.columns:
max_score = df["final_judge_scores"].max()
min_score = df["final_judge_scores"].min()
mean_score = df["final_judge_scores"].mean()
print(f"Max Score: {max_score}")
print(f"Min Score: {min_score}")
print(f"Mean Score: {mean_score}")
print(f"FINAL_DEFENSE_PROMPT:\n\n{self.best_defense_prompt_list}\n\n")
print(f"INIT_SCORE:\n\n{self.init_score_list }\n\n")
print(f"FINAL_SCORE:\n\n{self.score_list }\n\n")
self.table.to_csv(self.logger.dir+"/final_table.csv", index=False)