-
Notifications
You must be signed in to change notification settings - Fork 0
/
glue_process.py
807 lines (714 loc) · 28.7 KB
/
glue_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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
"""
======================================================================
GLUE_PROCESS ---
Process GLUE dataset.
Author: Zi Liang <[email protected]>
Copyright © 2024, ZiLiang, all rights reserved.
Created: 1 March 2024
======================================================================
"""
import os
if __name__ == "__main__":
os.environ["CUDA_VISIBLE_DEVICES"] = "7"
# ------------------------ Code --------------------------------------
import torch
from datasets import load_dataset
from openai import OpenAI as oa
# import time
import json
from collections import OrderedDict
import os
from math import exp
import random
from pprint import pprint
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 transformers import AutoModelForCausalLM,AutoTokenizer
from peft import PeftModel
import numpy as np
task_prompt_map = {
"cola": "Assess the following sentence and classify it as 'acceptable' or 'unacceptable'.",
# "mnli": "Assess the relationship between the given sentences and classify it as 'entailment', 'neutral', or 'contradiction'.",
"mrpc": "Evaluate the given pair of sentences and determine if they are 'equivalent' or 'not_equivalent'.",
"qnli": "Assess if the given context entails the answer to the question and respond with 'entailment' or 'not_entailment'.",
"qqp": "Assess the following pair of questions and classify them as 'equivalent' or 'not_equivalent'.",
"rte": "Assess the relationship between the given sentences and classify it as 'entailment' or 'not_entailment'.",
"sst2": "Determine whether the following text is 'positive' or 'negative'.",
"wnli": "Assess the relationship between the given sentences and classify it as 'entailment' or 'not_entailment'.",
}
def load_glue_nonlabel(lm_tokenizer,
task_name,
train_num=1,
max_length=1024,
):
# some preliminary knowledge of GLUE
tasks_we_used = [
"cola", "mnli",
"mrpc",
"qnli", "qqp", "rte", "sst2",
"wnli",]
task_label_map = {
"cola": {"1": "acceptable", "0": "unacceptable"},
"mnli": {"1": "neutral", "0": "entailment", "2": "contradiction"},
"mrpc": {"1": "equivalent", "2": "not_equivalent"},
"qnli": {"1": "not_entailment", "0": "entailment"},
"qqp": {"1": "duplicate", "0": "not_duplicate"},
"rte": {"1": "not_entailment", "0": "entailment"},
"sst2": {"1": "positive", "0": "negative"},
"wnli": {"0": "not_entailment", "1": "entailment"},
}
task_key_map = {
"mrpc": ["sentence1", "sentence2"],
"qnli": ["question", "sentence"],
"qqp": ["question1", "question2"],
"rte": ["sentence1", "sentence2"],
"wnli": ["sentence1", "sentence2"],
}
single_input_tasks = ["cola", "sst2",]
double_input_tasks = ["mrpc", "qnli", "qqp", "rte", "wnli",]
assert task_name in tasks_we_used
V = lm_tokenizer.vocab_size
dataset_name = "glue"
trainset_text = load_dataset(dataset_name, task_name,
split=f"train")\
.shuffle(seed=20240306).to_iterable_dataset().take(train_num)
sets = trainset_text
inp_ls = []
# collecting the input prompts
if task_name in single_input_tasks:
for d in trainset_text:
inps = d["sentence"]
inp_ls.append(inps)
# break
elif task_name == "mnli":
for d in sets:
inps = d["premise"]+" <SEP> "+d["hypothesis"]
# label = d["label"]
inp_ls.append(inps)
elif task_name in double_input_tasks:
for d in sets:
inps = d[task_key_map[task_name][0]]+" <SEP> " +\
d[task_key_map[task_name][1]]
# label = d["label"]
# label = task_label_map[task_name][str(label)]
inp_ls.append(inps)
else:
print(f"task name: {task_name} not found.")
pp = task_prompt_map[task_name]
prompts = [f"Instruction: {pp} User: {x} Assistant: "
for x in inp_ls]
p_idxls = []
for p in prompts:
p_idxls.append(lm_tokenizer(p, return_tensors="pt").input_ids[0])
return p_idxls, None, None, None
def load_glue_datals(lm_tokenizer,
task_name,
train_num=1,
model_name="gpt-3.5-turbo-1106",
topk=5,
max_length=1024,
openai_tmp_save_pth="./STEALED_PKLS/glue_openai_probs_res1__",
):
# some preliminary knowledge of GLUE
tasks_we_used = [
"cola", "mnli",
"mrpc",
"qnli", "qqp", "rte", "sst2",
"wnli",]
task_label_map = {
"cola": {"1": "acceptable", "0": "unacceptable"},
"mnli": {"1": "neutral", "0": "entailment", "2": "contradiction"},
"mrpc": {"1": "equivalent", "2": "not_equivalent"},
"qnli": {"1": "not_entailment", "0": "entailment"},
"qqp": {"1": "duplicate", "0": "not_duplicate"},
"rte": {"1": "not_entailment", "0": "entailment"},
"sst2": {"1": "positive", "0": "negative"},
"wnli": {"0": "not_entailment", "1": "entailment"},
}
task_key_map = {
"mrpc": ["sentence1", "sentence2"],
"qnli": ["question", "sentence"],
"qqp": ["question1", "question2"],
"rte": ["sentence1", "sentence2"],
"wnli": ["sentence1", "sentence2"],
}
single_input_tasks = ["cola", "sst2",]
double_input_tasks = ["mrpc", "qnli", "qqp", "rte", "wnli",]
assert task_name in tasks_we_used
V = lm_tokenizer.vocab_size
dataset_name = "glue"
trainset_text = load_dataset(dataset_name, task_name,
split=f"train")\
.shuffle(seed=20240306).to_iterable_dataset().take(train_num)
sets = trainset_text
inp_ls = []
# collecting the input prompts
if task_name in single_input_tasks:
for d in trainset_text:
inps = d["sentence"]
inp_ls.append(inps)
# break
elif task_name == "mnli":
for d in sets:
inps = d["premise"]+" <SEP> "+d["hypothesis"]
# label = d["label"]
inp_ls.append(inps)
elif task_name in double_input_tasks:
for d in sets:
inps = d[task_key_map[task_name][0]]+" <SEP> " +\
d[task_key_map[task_name][1]]
# label = d["label"]
# label = task_label_map[task_name][str(label)]
inp_ls.append(inps)
else:
print(f"task name: {task_name} not found.")
pp = task_prompt_map[task_name]
prompts = [f"Instruction: {pp} User: {x} Assistant: "
for x in inp_ls]
p_idxls = []
for p in prompts:
p_idxls.append(lm_tokenizer(p, return_tensors="pt").input_ids[0])
# p_idxls = lm_tokenizer(prompts,
# # padding="longest",
# # truncation=True,
# # max_length=max_length,
# return_tensors="pt"
# ).input_ids
openai_tmp_save_pth += f"task_{task_name}-trainNUM_{train_num}.pkl"
if not os.path.exists(openai_tmp_save_pth):
print("RUNNING ChatGPT Stealing...")
text2ls = []
idx2_dist_ls = []
probsls = []
for iii_bgn, q in tqdm(enumerate(inp_ls),
desc="ChatGPT Inference:"):
qd = [{"role": "system", "content": "Instruction: "+pp},
{"role": "user", "content": q}]
res = chatWithOpenAI__LogLogits(
model_name,
qd,
topk,
)
resp, logprb = res
bgn_idx = lm_tokenizer([resp],
# padding="longest",
truncation=True,
max_length=max_length,
return_tensors="pt"
).input_ids[0][0]
idx2 = p_idxls[iii_bgn].tolist()
logits_distr = torch.nn.functional.one_hot(
p_idxls[iii_bgn][1:],
num_classes=V,
).float()
# logits_distr[logits_distr<1e-9]=1e-10
logits_distr = torch.log(logits_distr)
idx2_dist = [[x,] for x in idx2]
for i in range(len(idx2_dist)):
for _ in range(topk-1):
idxxx = random.randint(0, V-1)
idx2_dist[i].append(idxxx)
idx2_dist = idx2_dist[1:]
# print(logits_distr.shape)
# logits_distr=logits_distr[torch.tensor(idx2_dist,
# dtype=torch.long)]
logits_distr = torch.gather(logits_distr, 1,
torch.tensor(idx2_dist,
dtype=torch.long))
logits_distr = [logits_distr[i]
for i in range(len(logits_distr))]
for i, topkdict in enumerate(logprb):
selected_token = topkdict.token
subtokens = lm_tokenizer.tokenize(selected_token)
sub_idxes = lm_tokenizer.convert_tokens_to_ids(subtokens)
idx2.extend(sub_idxes)
topk_tokens = [x.token for x in topkdict.top_logprobs]
topk_subtokenss = [lm_tokenizer.tokenize(x)
for x in topk_tokens]
topk_subidxes = [lm_tokenizer.convert_tokens_to_ids(x)
for x in topk_subtokenss]
topk_logits = [x.logprob
for x in topkdict.top_logprobs]
# topk_logits = [exp(x) for x in topk_logits]
# idx2_dist.extend(topk_subidxes)
# logits_distr.extend(topk_logits)
for j in range(len(subtokens)):
# dist = torch.tensor(topk_logits)
idx2_tmp_token_dist = torch.zeros(topk,
dtype=torch.long)
dist = torch.tensor(topk_logits)
# print("dist: ",dist)
for k, subidx in enumerate(topk_subidxes):
if len(subidx) <= j:
idx2_tmp_token_dist[k] = subidx[0]
else:
idx2_tmp_token_dist[k] = subidx[j]
logits_distr.append(dist)
idx2_dist.append(idx2_tmp_token_dist)
# print("logits_distr: ",logits_distr)
# print("idx2: ",idx2)
# print("idx2_dist: ",idx2_dist)
# print(len(idx2), len(logits_distr))
assert len(idx2) == len(logits_distr)+1
probsls.append(logits_distr)
text2ls.append(idx2)
idx2_dist_ls.append(idx2_dist)
with open(openai_tmp_save_pth,
'wb') as f:
pickle.dump([text2ls, probsls, idx2_dist_ls],
f,)
else:
print("Directly Loading...")
# from collections import OrderedDict
with open(openai_tmp_save_pth, 'rb') as f:
data = pickle.load(f,)
text2ls = data[0]
probsls = data[1]
idx2_dist_ls = data[2]
return p_idxls, text2ls, probsls, idx2_dist_ls
def infer_glue(modelname, task_name, res_pth,
test_set_take_num=500,
mnt=32,
base_model=None,
):
"""Infer the hf's pretraining models in GLUE"""
save_pth = res_pth
if base_model is not None:
# load model based on our idea
model = AutoModelForCausalLM.from_pretrained(
base_model,
device_map="auto",
# trust_remote_code=True,
torch_dtype=torch.bfloat16,
)
model = PeftModel.from_pretrained(model, modelname)
tokenizer = AutoTokenizer\
.from_pretrained(base_model)
tokenizer.pad_token = tokenizer.eos_token
tokenizer.padding_side = "right"
prompt = task_prompt_map[task_name]
# tasks for evaluation
tasks_name = ["valid_parentheses", "bool_logic",
"un_multi", "squad_v2",
"sst2", "wnli", "rte",
"mnli", "cola", "qqp",
"qnli", "mrpc",]
glue_ds = ["ax", "cola", "mnli",
"mnli_matched",
"mnli_mismatched", "mrpc",
"qnli", "qqp", "rte", "sst2",
"stsb", "wnli",]
tasks_we_used = [
"cola", "mnli",
"mrpc",
"qnli", "qqp", "rte", "sst2",
"wnli",]
task_label_map = {
"cola": {"1": "acceptable", "0": "unacceptable"},
# "mnli": {"1": "neutral", "0": "entailment", "2": "contradiction"},
"mrpc": {"1": "equivalent", "0": "not_equivalent"},
"qnli": {"1": "not_entailment", "0": "entailment"},
"qqp": {"1": "duplicate", "0": "not_duplicate"},
"rte": {"1": "not_entailment", "0": "entailment"},
"sst2": {"1": "positive", "0": "negative"},
"wnli": {"0": "not_entailment", "1": "entailment"},
}
task_key_map = {
"mrpc": ["sentence1", "sentence2"],
"qnli": ["question", "sentence"],
"qqp": ["question1", "question2"],
"rte": ["sentence1", "sentence2"],
"wnli": ["sentence1", "sentence2"],
}
single_input_tasks = ["cola", "sst2",]
double_input_tasks = ["mrpc", "qnli", "qqp", "rte", "wnli",]
assert task_name in tasks_we_used
dataset = load_dataset("glue", task_name)
res_ls = []
if task_name in single_input_tasks:
if len(dataset["validation"]) > test_set_take_num:
sets = dataset["validation"].shuffle(20240307)\
.to_iterable_dataset().take(test_set_take_num)
# sets = dataset["train"].shuffle(20240306)\
# .to_iterable_dataset().take(test_set_take_num)
else:
sets = dataset["validation"]
# sets=sets.shuffle(seed=20240307)
iii = 0
for d in tqdm(sets,total=test_set_take_num,):
iii += 1
if iii == 1 or iii == test_set_take_num:
print(d)
inps = d["sentence"]
label = d["label"]
label = task_label_map[task_name][str(label)]
final_inps = "Instruction: " + prompt +\
" User: "+inps+" Assistant: "
inpsidx=tokenizer.encode(
final_inps,
max_length=128,
padding="longest",
return_tensors="pt",
)
inpsidx=inpsidx.to("cuda")
res = model.generate(
inpsidx,
max_new_tokens=mnt,)[0]
res = tokenizer.decode(res)
if final_inps in res:
res = res.split(final_inps)[1]
else:
res = res
res_ls.append((res, label))
print("Generations: ", res)
# break
elif task_name == "mnli":
if len(dataset["validation_matched"]) > test_set_take_num:
sets = dataset["validation_matched"]\
.to_iterable_dataset().take(test_set_take_num)
else:
sets = dataset["validation_matched"]
for d in tqdm(sets,total=test_set_take_num,):
inps = d["premise"]+"SEP"+d["hypothesis"]
label = d["label"]
label = task_label_map[task_name][str(label)]
final_inps = "Instruction: " + prompt +\
" User: "+inps+" Assistant: "
inpsidx=tokenizer.encode(
final_inps,
max_length=128,
padding="longest",
return_tensors="pt",
)
inpsidx=inpsidx.to("cuda")
res = model.generate(
inpsidx,
max_new_tokens=mnt,)[0]
res = tokenizer.decode(res)
if final_inps in res:
res = res.split(final_inps)[1]
else:
res = res
res_ls.append((res, label))
elif task_name in double_input_tasks:
if len(dataset["validation"]) > test_set_take_num:
sets = dataset["validation"]\
.to_iterable_dataset().take(test_set_take_num)
else:
sets = dataset["validation"]
for d in tqdm(sets,total=test_set_take_num,):
inps = d[task_key_map[task_name][0]]+"SEP" +\
d[task_key_map[task_name][1]]
label = d["label"]
print(f"task name: {task_name} Label: {label}")
label = task_label_map[task_name][str(label)]
final_inps = "Instruction: " + prompt +\
" User: "+inps+" Assistant: "
inpsidx=tokenizer.encode(
final_inps,
max_length=128,
padding="longest",
return_tensors="pt",
)
inpsidx=inpsidx.to("cuda")
res = model.generate(
inpsidx,
max_new_tokens=mnt,)[0]
res = tokenizer.decode(res)
if final_inps in res:
res = res.split(final_inps)[1]
else:
res = res
res_ls.append((res, label))
# break
else:
print(f"task name: {task_name} not found.")
with open(save_pth, 'w', encoding='utf8') as f:
json.dump(res_ls, f, ensure_ascii=False, indent=4)
model=None
return res_ls
# normal import
task_label_map = {
"cola": {"1": "acceptable", "0": "unacceptable"},
# "mnli": {"1": "neutral", "0": "entailment", "2": "contradiction"},
"mrpc": {"1": "equivalent", "0": "not_equivalent"},
"qnli": {"1": "not_entailment", "0": "entailment"},
"qqp": {"1": "duplicate", "0": "not_duplicate"},
"rte": {"1": "not_entailment", "0": "entailment"},
"sst2": {"1": "positive", "0": "negative"},
"wnli": {"0": "not_entailment", "1": "entailment"},
}
def eval_glue(task, res):
predict_ls = []
label_ls = []
submap = task_label_map[task]
sm_r = {v: k for k, v in submap.items()}
text_dict = list(sm_r.keys())
for res_sent, lbl in res:
# print(res_sent)
res_sent = res_sent.lower()
# label_ls.append(float(sm_r[lbl]))
if "not" in text_dict[0] or "not" in text_dict[1]:
if "not" in text_dict[0]:
if "not" in res_sent:
vv = float(sm_r[text_dict[0]])
else:
vv = float(sm_r[text_dict[1]])
else:
if "not" in res_sent:
vv = float(sm_r[text_dict[1]])
else:
vv = float(sm_r[text_dict[0]])
else:
if text_dict[0] in res_sent and text_dict[1] not in res_sent:
vv = float(sm_r[text_dict[0]])
else:
vv = float(sm_r[text_dict[1]])
predict_ls.append(vv)
label_ls.append(float(sm_r[lbl]))
metric_ls = [accuracy_score, precision_score, recall_score, f1_score]
scores = []
for m in metric_ls:
scores.append(m(label_ls, predict_ls))
return scores
def evaluation_datas():
test_task_ckpt_ls = [
# original
["cola", "google/gemma-2b"],
# ablation study
# ["cola","./POD_SAVE_CKPTs/kd_3Epochkd_256cola___finally"],
["cola", "./POD_SAVE_CKPTs/cola_3Epochvanilla_256cola___finally/"],
["cola", "./POD_SAVE_CKPTs/cola_3Epochkd_256cola___finally/"],
# ## method comparison
["cola",
"./POD_SAVE_CKPTs/vary_period0306cola/Complex-lord_256cola___period0"],
["cola",
"./POD_SAVE_CKPTs/vary_period0306cola/Complex-lord_256cola___period1"],
["cola",
"./POD_SAVE_CKPTs/vary_period0306cola/Complex-lord_256cola___period2"],
["cola",
"./POD_SAVE_CKPTs/vary_period0306cola/lord_256cola___period0"],
["cola",
"./POD_SAVE_CKPTs/vary_period0306cola/lord_256cola___period1"],
["cola",
"./POD_SAVE_CKPTs/vary_period0306cola/lord_256cola___period2"],
["cola",
"./POD_SAVE_CKPTs/vary_period0306cola/reinforce-lord_256cola___period0"],
["cola",
"./POD_SAVE_CKPTs/vary_period0306cola/reinforce-lord_256cola___period1"],
["cola",
"./POD_SAVE_CKPTs/vary_period0306cola/reinforce-lord_256cola___period2"],
# varying periods
["cola",
"./POD_SAVE_CKPTs/vary_period_complex/Complex-lord256cola1100___period0"
],
["cola",
"./POD_SAVE_CKPTs/vary_period_complex/Complex-lord256cola1100___period1"
],
["cola",
"./POD_SAVE_CKPTs/vary_period_complex/Complex-lord256cola1100___period2"
],
["cola",
"./POD_SAVE_CKPTs/vary_period_complex/Complex-lord256cola1100___period3"
],
["cola",
"./POD_SAVE_CKPTs/vary_period_complex/Complex-lord256cola1100___period4"
],
["cola",
"./POD_SAVE_CKPTs/vary_period_complex/Complex-lord256cola1100___period5"
],
["cola",
"./POD_SAVE_CKPTs/vary_period_complex/Complex-lord256cola1100___period6"
],
["cola",
"./POD_SAVE_CKPTs/vary_period_complex/Complex-lord256cola1100___period7"
],
["cola",
"./POD_SAVE_CKPTs/vary_period_complex/Complex-lord256cola1100___period8"
],
["cola",
"./POD_SAVE_CKPTs/vary_period_complex/Complex-lord256cola1100___period9"
],
]
res_dict = {}
dir_p = "./glue_res/"
if not os.path.exists(dir_p):
os.makedirs(dir_p)
for task_ckpt in test_task_ckpt_ls:
task, ckpt = task_ckpt
res_pth = ckpt+f"___{task}_glue_infer_res.json"
res_pth = res_pth.replace("/", "__").replace(".", "")
if not os.path.exists(dir_p+res_pth):
res_ls = infer_glue(ckpt, task, dir_p+res_pth)
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)
scores = eval_glue(task, res_ls)
print(task, ckpt)
print(scores)
res_dict[task+"-----"+ckpt] = scores
with open(dir_p+"glue_inference_scores.json",
'w', encoding='utf8') as f:
json.dump(res_dict, f, ensure_ascii=False, indent=4)
print("OVERALL Save DONE.")
pprint(res_dict)
def glue_big_evals():
# methodls = ["Complex-lord", "vanilla", "kd", "black--Complex-lord"]
methodls = ["vanilla", "kd",]
train_times = [str(x+1) for x in range(5)]
dir_p = "./GLUE_infers/"
res_dict = {}
for task in task_prompt_map.keys():
res_dict[task] = {}
for m in methodls:
for itime in train_times:
if not os.path.exists(dir_p):
os.makedirs(dir_p)
prefix = "./GLUE_ckpts/"
if m == "Complex-lord" or m == "black--Complex-lord":
ckpt = prefix+f"{task}{m}256100__{itime}___period2"
else:
ckpt = prefix+f"{task}{m}256100__{itime}___finally"
res_pth = ckpt+f"___{task}_glue_infer_res.json"
res_pth = res_pth.replace("/", "__").replace(".", "")
if not os.path.exists(dir_p+res_pth):
res_ls = infer_glue(ckpt, task, dir_p+res_pth,
test_set_take_num=100)
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)
scores = eval_glue(task, res_ls)
print(task, ckpt)
print(scores)
res_dict[task][task+"-----"+ckpt] = scores
with open(dir_p+"glue_inference_scores5times.json",
'w', encoding='utf8') as f:
json.dump(res_dict, f, ensure_ascii=False, indent=4)
print("OVERALL Save DONE.")
pprint(res_dict)
def eval_varying_train_num():
taskls = [
"cola",
]
mls = [
"vanilla",
"LoRD-VI",
]
train_times = [
"1",
# "2",
# "3",
# "4",
# "5",
]
train_nums = [
# "8",
# "16",
# "32",
# "64",
# "128",
# "256",
# "512",
"1024",
]
base_model_name1="meta-llama/Meta-Llama-3-8B-Instruct"
dir_p = "./glue_0702_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 = "./wmt16_ckpts/WMTTT0519"
prefix = "./NEW_VARYING_QUERYTIME_CKPTS/text2sql"
if m=="vanilla" or m =="kd":
ckpt = (
prefix
+ f"{task}{train_num}{itime}{m}___finally/"
)
elif train_num in ["256", "512", "1024"]:
num=str(int(4*int(train_num)))
ckpt = prefix + \
f"{task}{train_num}{itime}{m}___period{num}/"
else:
ckpt = prefix + \
f"{task}{train_num}{itime}{m}___period512/"
res_pth = ckpt+f"___{task}_glue_infer_res.json"
res_pth = res_pth.replace("/", "__").replace(".", "")
if not os.path.exists(dir_p+res_pth):
res_ls = infer_glue(ckpt,
task,
dir_p+res_pth,
test_set_take_num=500,
mnt=32,
base_model=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)
scores = eval_glue(task, res_ls)
print(task, ckpt)
print(scores)
res_dict[task+"-----"+res_pth] = scores
score_ls=scores
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__glue_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
if __name__ == "__main__":
# from transformers import AutoTokenizer
# tokenizer = AutoTokenizer.from_pretrained("google/gemma-2b")
# res = load_glue_datals(tokenizer,
# "cola",
# train_num=3,
# model_name="gpt-3.5-turbo-1106",
# topk=5,
# max_length=1024,
# openai_tmp_save_pth="./temp.pkl.deletethis.txt",
# )
# prompt=res[0]
# text2=res[1]
# print("-------------------------")
# print(tokenizer.decode(prompt[0]))
# print(tokenizer.decode(text2[0]))
# print("-------------------------")
# print(tokenizer.decode(prompt[1]))
# print(tokenizer.decode(text2[1]))
# print("-------------------------")
# print(tokenizer.decode(prompt[2]))
# print(tokenizer.decode(text2[2]))
# print("-------------------------")
# evaluation_datas()
# glue_big_evals()
eval_varying_train_num()