-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsafety_process.py
498 lines (450 loc) · 15.4 KB
/
safety_process.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
"""
======================================================================
SAFETY_PROCESS ---
Safety related experiments.
Author: Zi Liang <[email protected]>
Copyright © 2024, ZiLiang, all rights reserved.
Created: 27 June 2024
======================================================================
"""
# ------------------------ Code --------------------------------------
import os
if __name__ == "__main__":
# os.environ["CUDA_VISIBLE_DEVICES"] = "0,1,2,3"
# os.environ["CUDA_VISIBLE_DEVICES"] = "4,5,6,7"
# os.environ["CUDA_VISIBLE_DEVICES"] = "6,7"
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
# os.environ["CUDA_VISIBLE_DEVICES"] = "4,5"
os.environ["TORCH_USE_CUDA_DSA"] = "1"
import torch
from datasets import load_dataset
from openai import OpenAI as oa
import json
from collections import OrderedDict
import os
from math import exp
import random
import pickle
from tqdm import tqdm
from sklearn.metrics import precision_score, accuracy_score, recall_score, f1_score
from training_data_collecting_openai import chatWithOpenAI_APIs
from training_data_collecting_openai import chatWithOpenAI__LogLogits
from gen_pipeline_open import InferObj
from wmt_process import commonly_used_openai_post_process
# from wmt_process import eval_wmt as eval_sum
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel
import torch
from pprint import pprint
import numpy as np
def load_safety_datals(
tokenizer,
task_name="allenai/prosocial-dialog",
train_num=100,
# model_name="gpt-3.5-turbo-1106",
model_name="gpt-4o",
topk=5,
max_length=1024,
openai_tmp_save_pth="./STEALED_PKLS/wmt_data_saveto_",
tokenizer_name=None,
):
lm_tokenizer = tokenizer
pp = ""
V = lm_tokenizer.vocab_size
tasks_we_used = [
"PKU-Alignment/PKU-SafeRLHF",
"thu-coai/diasafety",
"allenai/prosocial-dialog",
"Anthropic/hh-rlhf",
]
assert task_name in tasks_we_used
dataset_name = task_name
inp_ls = []
if task_name == tasks_we_used[2]:
trainset_text = load_dataset(dataset_name, split=f"train[:{train_num}]")
for item in trainset_text:
inp = item["context"]
resp = item["response"]
inp_ls.append(inp)
elif task_name == tasks_we_used[0]:
trainset_text = load_dataset(
dataset_name,
# split=f"train[:{train_num}]",
split=f"train",
).shuffle(20240307)
for item in trainset_text:
inp = item["prompt"]
safe_label = item["is_response_1_safe"]
print(f"Safe Label: {safe_label}")
if safe_label == False:
inp_ls.append(inp)
if len(inp_ls) >= train_num:
break
elif task_name == tasks_we_used[1]:
trainset_text = load_dataset(
dataset_name,
# split=f"train[:{train_num}]",
split=f"train",
).shuffle(20240307)
for item in trainset_text:
inp = item["context"]
inp_ls.append(inp)
if len(inp_ls) >= train_num:
break
elif task_name == "Anthropic/hh-rlhf":
trainset_text = load_dataset(
dataset_name,
split="train",
).shuffle(20240307)
for item in trainset_text:
inp = item["chosen"]
if " Assistant: " not in inp:
continue
else:
inp = inp.split(" Assistant: ")[0]
inp_ls.append(inp)
if len(inp_ls) >= train_num:
break
assert inp_ls != []
p_idxls = []
prompts = [f"User: {x} Assistant: " for x in inp_ls]
for p in prompts:
p_idxls.append(lm_tokenizer(p, return_tensors="pt").input_ids[0])
openai_tmp_save_pth += f"safetask_{task_name}-trainNUM_{train_num}.pkl"
return commonly_used_openai_post_process(
openai_tmp_save_pth,
inp_ls,
pp,
model_name,
topk,
max_length,
p_idxls,
V,
lm_tokenizer,
)
def infer_safety(
modelname,
task_name,
res_pth,
test_set_take_num=100,
mnt=16,
base_model_name=None,
):
save_pth = res_pth
tasks_we_used = [
"PKU-Alignment/PKU-SafeRLHF",
"thu-coai/diasafety",
# "allenai/prosocial-dialog",
"Anthropic/hh-rlhf",
]
assert task_name in tasks_we_used
if task_name == tasks_we_used[0]:
dataset = (
load_dataset(task_name, split=f"test")
.shuffle(20240307)
.to_iterable_dataset()
)
# .take(test_set_take_num)
# sets = dataset
sets = []
for item in dataset:
if item["is_response_1_safe"] == False:
sets.append(item)
if len(sets) >= test_set_take_num:
break
elif task_name == tasks_we_used[1]:
dataset = (
load_dataset(task_name, split=f"test")
.shuffle(20240307)
.to_iterable_dataset()
)
# .take(test_set_take_num)
# sets = dataset
sets = []
for item in dataset:
if item["label"] == "Unsafe":
sets.append(item)
if len(sets) >= test_set_take_num:
break
elif task_name == "Anthropic/hh-rlhf":
dataset = (
load_dataset(task_name, split=f"test")
.shuffle(20240307)
.to_iterable_dataset()
)
# .take(test_set_take_num)
# sets = dataset
sets = []
for item in dataset:
inp = item["chosen"]
if "Assistant: " not in inp:
# print(inp)
continue
else:
inp = inp.split("Assistant: ")[0]
sets.append(inp)
if len(sets) >= test_set_take_num:
break
print("Length of test dataset:", len(sets))
if modelname == "gpt-3.5-turbo-1106":
from training_data_collecting_openai import chatWithOpenAI_APIs
res_ls = []
for d in tqdm(sets):
if task_name == tasks_we_used[0]:
d = d["prompt"]
elif task_name == tasks_we_used[1]:
inp = d["context"]
out = d["response"]
category = d["category"]
label = d["label"]
d = inp
res = chatWithOpenAI_APIs(modelname, "", query)
print(f"Generated Text: {res}")
res_ls.append((res, ""))
elif modelname is None:
print("USING Pretrained Model.")
# load model based on our idea
model = AutoModelForCausalLM.from_pretrained(
base_model_name,
device_map="auto",
trust_remote_code=True,
torch_dtype=torch.bfloat16,
)
tokenizer = AutoTokenizer.from_pretrained(base_model_name)
tokenizer.pad_token = tokenizer.eos_token
tokenizer.padding_side = "right"
res_ls = []
pp = ""
input_idxls = []
for d in tqdm(sets, total=test_set_take_num):
if task_name == tasks_we_used[0]:
d = d["prompt"]
elif task_name == tasks_we_used[1]:
inp = d["context"]
out = d["response"]
category = d["category"]
label = d["label"]
d = inp
final_inps = " User: " + d + " Assistant: "
inps_idx = tokenizer.encode(
final_inps, max_length=128, padding="longest", return_tensors="pt"
)
print(inps_idx)
inps_idx = inps_idx.to("cuda")
res = model.generate(
inps_idx,
max_new_tokens=mnt,
)
print(res)
res = tokenizer.decode(res[0])
if final_inps in res:
res = res.split(final_inps)[1]
else:
res = res
print(f"Text Generated:>>> {res}")
res_ls.append((res, ""))
elif base_model_name is None:
model = InferObj(
model_name=modelname,
device="auto",
max_length=2047,
open_16_mode=True,
)
gen_pipeline = model.text_gen
res_ls = []
pp = task_prompt_map[task_name]
for d in tqdm(sets, total=test_set_take_num):
if task_name == tasks_we_used[0]:
d = d["prompt"]
elif task_name == tasks_we_used[1]:
inp = d["context"]
out = d["response"]
category = d["category"]
label = d["label"]
d = inp
final_inps = " User: " + d + " Assistant: "
res = gen_pipeline(
final_inps,
do_sample=True,
max_new_tokens=mnt,
)[
0
]["generated_text"]
print("++++++++++++++++++DEBUG INFO+++++++++++++++++++++++")
print(f">>>Res with Inpus: {res}")
res = res.split(final_inps)[1]
print(f">>>Res without Inpus: {res}")
res_ls.append((res, ""))
# break
else:
print("USING PEFT: BASE MODEL + LORA")
# load model based on our idea
model = AutoModelForCausalLM.from_pretrained(
base_model_name,
device_map="auto",
# trust_remote_code=True,
torch_dtype=torch.bfloat16,
)
model = PeftModel.from_pretrained(model, modelname)
tokenizer = AutoTokenizer.from_pretrained(base_model_name)
tokenizer.pad_token = tokenizer.eos_token
tokenizer.padding_side = "right"
res_ls = []
pp = ""
input_idxls = []
for d in tqdm(sets, total=test_set_take_num):
if task_name == tasks_we_used[0]:
d = d["prompt"]
elif task_name == tasks_we_used[1]:
inp = d["context"]
out = d["response"]
category = d["category"]
label = d["label"]
d = inp
final_inps = " User: " + d + " Assistant: "
inps_idx = tokenizer.encode(
final_inps, max_length=128, padding="longest", return_tensors="pt"
)
print(inps_idx)
inps_idx = inps_idx.to("cuda")
res = model.generate(
inps_idx,
max_new_tokens=mnt,
)
print(res)
res = tokenizer.decode(res[0])
if final_inps in res:
res = res.split(final_inps)[1]
else:
res = res
print(f"Text Generated:>>> {res}")
res_ls.append((res, ""))
model = None
gen_pipeline = None
tokenizer = None
with open(save_pth, "w", encoding="utf8") as f:
json.dump(res_ls, f, ensure_ascii=False, indent=4)
return res_ls
def eval_varying_train_num():
print("LoAdInG Evaluation model...")
from safety.perspectiveAPI import PerspectiveAPI
eval_model = PerspectiveAPI()
taskls = [
"Anthropic/hh-rlhf",
# "PKU-Alignment/PKU-SafeRLHF",
# "thu-coai/diasafety",
]
mls = [
"vanilla",
"LoRD-VI",
# "pretrained",
# "gpt-3.5-turbo-1106",
# "kd",
]
train_times = [
"1",
# "2",
# "3",
# "4",
# "5",
]
train_nums = [
# "2",
# "4",
# "8",
# "16",
# "32",
"64",
# "128",
# "256",
# "512",
# "1024",
# "2048",
]
base_model_name1 = "meta-llama/Meta-Llama-3-8B-Instruct"
dir_p = "./safety_0627_dataset_res/"
res_dict = {}
if not os.path.exists(dir_p):
os.makedirs(dir_p)
res_dict_averaged = {}
for task in taskls:
for train_num in train_nums:
for m in mls:
temp_scorels = []
for itime in train_times:
prefix = "./safety_ckpts/safety_align"
if m == "vanilla":
ckpt = prefix + f"{task}{train_num}{itime}{m}___finally/"
elif m == "pretrained":
ckpt = f"./safety_ckpts/code---{task}{train_num}{itime}{m}_res.json"
elif m == "gpt-3.5-turbo-1106":
ckpt = m
elif m == "meta-llama/Meta-Llama-3-8B":
ckpt = m
else:
ckpt = prefix + f"{task}{train_num}{itime}{m}___period512/"
res_pth = ckpt + f"___{task}_safety_infer_res.json"
res_pth = res_pth.replace("/", "__").replace(".", "")
if not os.path.exists(dir_p + res_pth):
if m == "pretrained":
res_ls = infer_safety(
None,
task,
dir_p + res_pth,
test_set_take_num=500,
mnt=256,
base_model_name=base_model_name1,
)
else:
res_ls = infer_safety(
ckpt,
task,
dir_p + res_pth,
test_set_take_num=500,
mnt=256,
base_model_name=base_model_name1,
)
else:
# from collections import OrderedDict
with open(dir_p + res_pth, "r", encoding="utf8") as f:
res_ls = json.load(f, object_pairs_hook=OrderedDict)
query_ls, resls = zip(*res_ls)
score_mean_dict, score_dict_ls = eval_model.eval_ls(query_ls)
print(task, ckpt)
print(score_mean_dict)
res_dict[task + "-----" + res_pth] = score_mean_dict
scores = score_mean_dict
score_ls = [
scores["toxicity"],
scores["severe_toxicity"],
scores["insult"],
scores["profanity"],
scores["threat"],
]
temp_scorels.append(score_ls)
# obtain the mean value
# obtain the std value
temp_scorels = np.array(temp_scorels)
meanvaluels = np.mean(temp_scorels, axis=0).tolist()
stdvaluels = np.std(temp_scorels, axis=0, ddof=1).tolist()
res_dict_averaged[task + "--" + res_pth] = {
"mean": meanvaluels,
"std": stdvaluels,
}
with open(
dir_p + "Overall__safety_varytrain_num_inference_scores.json",
"w",
encoding="utf8",
) as f:
json.dump(res_dict, f, ensure_ascii=False, indent=4)
with open(dir_p + "OverallScoresAveraged.json", "w", encoding="utf8") as f:
json.dump(res_dict_averaged, f, ensure_ascii=False, indent=4)
print("OVERALL Save DONE.")
pprint(res_dict)
print("------------------------------------------")
pprint(res_dict_averaged)
return res_dict
# running entry
if __name__ == "__main__":
eval_varying_train_num()
print("EVERYTHING DONE.")