-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathevaluate_prompt.py
1689 lines (1477 loc) · 91.7 KB
/
evaluate_prompt.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
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from sanitize import sanitize, CodeProcessor
from prompt import Prompt
from evaluate import Evaluator
import json
from dataset import Dataset
import os
import ast
import itertools
import numpy as np
class ChatPromptEvaluator(object):
def __init__(self, sample_num = 20):
self.prompt_generator = Prompt(chat=True)
self.prompt_generator.load_templates()
self.sample_num = sample_num
def get_entrypoint(self, dataset, instance):
entry_point = ""
if dataset.name == "openai_humaneval":
entry_point += instance["entry_point"]
return entry_point
def process_solution(self, solution, instance, dataset):
if dataset.name == "openai_humaneval" and not solution.startswith("def"):
lines = solution.splitlines()
if len(lines) > 0:
lines[0] = " " + lines[0]
solution = instance["prompt"] + "\n".join(lines)
elif dataset.name == "openai_humaneval":
try:
ast.parse(solution)
except Exception as e:
lines = solution.splitlines()
if len(lines) > 0:
lines[0] = " " + lines[0]
solution = instance["prompt"] + "\n".join(lines)
return solution
def build_new_status(self):
return {
"status": "Unchecked",
"passed_solution": None,
"exec_time": None,
"failed_testcase": [],
"large_testcase": None,
"notes": {}
}
def is_unchecked(self, lst):
for status in lst:
if isinstance(status, str) or status == None:
return False
if status["status"] not in ["Unchecked", "PARSE_ERROR"]:
return False
return True
def find_result(self, dataset, prompt, name, rd, i, checked_outputs):
cur_name = name
if rd == 0:
if name.startswith("correctness"):
cur_name = "base"
return checked_outputs[dataset][prompt][cur_name][rd][i], [cur_name, rd, i]
elif name.startswith("time"):
cur_name = "correct_solutions"
return checked_outputs[dataset][prompt][cur_name][i], [cur_name, 0, i]
elif rd > 0:
if checked_outputs[dataset][prompt][cur_name][rd-1][i] == "<END>" or isinstance(checked_outputs[dataset][prompt][cur_name][rd-1][i], str):
return self.find_result(dataset, prompt, name, rd-1, i, checked_outputs)
else:
return checked_outputs[dataset][prompt][cur_name][rd-1][i], [cur_name, rd, i]
def write_batch_outputs(self, batch_output_file, output_file, hash_file):
batch_outputs = json.load(open(batch_output_file, "r"))
outputs = json.load(open(output_file, "r"))
hash_map = json.load(open(hash_file, "r"))
for dataset in outputs:
for prompt in outputs[dataset]:
for name in outputs[dataset][prompt]:
for j, res in enumerate(outputs[dataset][prompt][name]):
for i, r in enumerate(res):
if r == "<PENDING>":
if name != "base":
sig = f"{dataset}@{name}@{hash_map[prompt]}@{j}@{i}"
if sig not in batch_outputs:
print("Cannot find signature {} pending query, skipping.".format(sig))
outputs[dataset][prompt][name][j][i] = None
continue
if batch_outputs[sig] != None:
outputs[dataset][prompt][name][j][i] = batch_outputs[sig]["content"]
else:
outputs[dataset][prompt][name][j][i] = None
else:
sig = f"{dataset}@{name}@{hash_map[prompt]}@{j}"
if sig not in batch_outputs:
print("Cannot find signature {} pending query, skipping.".format(sig))
outputs[dataset][prompt][name][j][i] = None
continue
if batch_outputs[sig] != None:
outputs[dataset][prompt][name][j][i] = batch_outputs[sig]["content"][i]
else:
outputs[dataset][prompt][name][j][i] = None
with open(output_file, "w", encoding = "utf-8") as f:
f.write(json.dumps(outputs, sort_keys=True, indent=4, separators=(',', ': ')))
def get_solutions(self, outputs, dataset, prompt, no_modify = False, chat = True, codegen = False):
solutions = []
if prompt not in dataset.prompt2instance:
print('Cannot find the prompt of instance in dataset, skipped.')
return solutions
instance = dataset.prompt2instance[prompt]
for out in outputs:
if out == None:
solutions.append([-1, False])
else:
code = sanitize(out, self.get_entrypoint(dataset, instance), codegen = codegen, global_code = True if dataset.name in ["codeparrot/apps"] and not codegen else False, chat = chat)
code = self.process_solution(code, instance, dataset)
processor = CodeProcessor(code,entry_point = dataset.prompt2instance[prompt]["entry_point"] if "entry_point" in dataset.prompt2instance[prompt] else None, force_rename = True if dataset.name in ["openai_humaneval", "mbpp"] else False)
solutions.append(processor.run(no_modify = no_modify))
return solutions
def prepare_correctness_check(self, mode, rd, output_file, checked_file = None, chat = True, codegen = False):
if checked_file:
self.checked_outputs = json.load(open(checked_file, "r"))
else:
self.checked_outputs = {}
self.outputs = json.load(open(output_file, "r"))
indexes = {}
solutions = {}
for dataset in self.outputs:
print("Processing dataset: {}".format(dataset))
dataset_obj = Dataset(dataset, data_path = os.path.join("test_datasets/", dataset.replace("/", "_")), testfile_path = "datasets/MbppPlus.jsonl" if dataset == "mbpp" else None)
solutions[dataset] = {}
indexes[dataset] = {}
num = 0
failed_num = 0
if dataset not in self.checked_outputs:
self.checked_outputs[dataset] = {}
for prompt in self.outputs[dataset]:
solutions[dataset][prompt] = []
indexes[dataset][prompt] = {"failed": []}
if prompt not in self.checked_outputs[dataset] and checked_file == None:
self.checked_outputs[dataset][prompt] = {}
elif prompt not in self.checked_outputs[dataset]:
continue
for name in self.outputs[dataset][prompt]:
if mode != name and not name.startswith(mode):
if name in self.checked_outputs[dataset][prompt]:
continue
else:
raise ValueError("Checked outputs missing category: {}".format(name))
if name not in self.checked_outputs[dataset][prompt]:
self.checked_outputs[dataset][prompt][name] = []
if name == "time_original":
self.checked_outputs[dataset][prompt][name] = self.outputs[dataset][prompt][name]
processor = CodeProcessor(self.checked_outputs[dataset][prompt][name], force_rename = True if dataset in ["openai_humaneval", "mbpp"] else False)
ori = processor.run(no_modify = True)
if ori[0] == -1:
raise ValueError("Original solution parse error!")
solutions[dataset][prompt].append(ori)
indexes[dataset][prompt][ori[0]] = [[name, 0, 0]]
continue
for i, out in enumerate(self.outputs[dataset][prompt][name]):
if i < rd:
if len(self.checked_outputs[dataset][prompt][name]) <= i:
self.checked_outputs[dataset][prompt][name].append(out)
continue
if self.prompt_generator.gen_code(i, name):
if len(self.checked_outputs[dataset][prompt][name]) > i:
continue
temp_solutions = self.get_solutions(out, dataset_obj, prompt, chat = chat, codegen = codegen)
temp_checked = []
for j, ts in enumerate(temp_solutions):
if out[j] == None:
status = self.build_new_status()
status["status"] = "QUERY_ERROR"
temp_checked.append(status)
continue
elif (out[j].startswith("<") and out[j].endswith(">")):
temp_checked.append(out[j])
continue
num += 1
if ts[0] == -1:
indexes[dataset][prompt]["failed"].append([name, i, j])
failed_num += 1
status = self.build_new_status()
status["status"] = "PARSE_ERROR"
temp_checked.append(status)
elif ts[0] not in indexes[dataset][prompt]:
solutions[dataset][prompt].append(ts)
indexes[dataset][prompt][ts[0]] = [[name, i, j]]
status = self.build_new_status()
temp_checked.append(status)
else:
indexes[dataset][prompt][ts[0]].append([name, i, j])
status = self.build_new_status()
temp_checked.append(status)
self.checked_outputs[dataset][prompt][name].append(temp_checked)
else:
self.checked_outputs[dataset][prompt][name].append(out)
print("Totally {}/{} ({}) invalid solutions found.".format(failed_num, num, failed_num/num if num > 0 else 0))
self.checked_outputs = self.verify_natural_outputs(rd)
with open(output_file.replace(".json", "_CHECKED.json"), "w", encoding = "utf-8") as f:
f.write(json.dumps(self.checked_outputs, sort_keys=True, indent=4, separators=(',', ': ')))
with open(output_file.replace(".json", "_SOLUTIONS.json"), "w", encoding = "utf-8") as f:
f.write(json.dumps(solutions, sort_keys=True, indent=4, separators=(',', ': ')))
with open(output_file.replace(".json", "_INDEXES.json"), "w", encoding = "utf-8") as f:
f.write(json.dumps(indexes, sort_keys=True, indent=4, separators=(',', ': ')))
def prepare_time_measurement(self, result_dir, model, mode, rd):
checked_file = os.path.join(result_dir, model, mode, f"rd{rd}_CHECKED.json")
index_file = os.path.join(result_dir, model, mode, f"rd{rd}_INDEXES.json")
checked_outputs = json.load(open(checked_file, "r"))
indexes = json.load(open(index_file, "r"))
all_solutions = {}
for i in range(0, 5):
passed_solutions = json.load(open(os.path.join(result_dir, model, mode, f"rd{rd}_PASSED_SOLUTIONS_p{i}.json"), "r"))
for dataset in passed_solutions:
if dataset not in all_solutions:
all_solutions[dataset] = {}
for prompt in passed_solutions[dataset]:
all_solutions[dataset][prompt] = passed_solutions[dataset][prompt]
for dataset in checked_outputs:
for prompt in checked_outputs[dataset]:
if "correct_solutions" not in checked_outputs[dataset][prompt] and len(checked_outputs[dataset][prompt]) == 0:
continue
for i, status in enumerate(checked_outputs[dataset][prompt]["correct_solutions"]):
if isinstance(status, str):
continue
else:
processor = CodeProcessor(status["passed_solution"], force_rename = True if dataset in ["openai_humaneval", "mbpp"] else False)
solution = processor.run(no_modify = True)
if solution[0] == -1:
raise ValueError("Cannot parse correct solution!")
if prompt not in all_solutions[dataset]:
all_solutions[dataset][prompt] = []
all_solutions[dataset][prompt].append(solution)
if solution[0] not in indexes[dataset][prompt]:
indexes[dataset][prompt][solution[0]] = [["correct_solutions", 0, i]]
else:
indexes[dataset][prompt][solution[0]].append(["correct_solutions", 0, i])
if rd == 0 and mode == "time":
for dataset in indexes:
for prompt in indexes[dataset]:
for solution in indexes[dataset][prompt]:
if solution == "failed":
continue
new_indexes = []
for index in indexes[dataset][prompt][solution]:
if index[0] in ["time_simple_execution_feedback", "time_execution_feedback_with_testcase", "correct_solutions"]:
new_indexes.append(index)
if len(new_indexes) == 0:
prev_num = len(all_solutions[dataset][prompt])
new_solutions = []
for s in all_solutions[dataset][prompt]:
if s[0] != solution:
new_solutions.append(s)
all_solutions[dataset][prompt] = new_solutions
cur_num = len(all_solutions[dataset][prompt])
with open(os.path.join(result_dir, model, mode, f"rd{rd}_PASSED_SOLUTIONS.json"), "w", encoding = "utf-8") as f:
f.write(json.dumps(all_solutions, sort_keys=True, indent=4, separators=(',', ': ')))
with open(index_file, "w", encoding = "utf-8") as f:
f.write(json.dumps(indexes, sort_keys=True, indent=4, separators=(',', ': ')))
def prepare_groundtruth_comparison(self, result_dir, model, mode, rd, best_solution_file):
checked_file = os.path.join(result_dir, model, mode, f"rd{rd}_CHECKED.json")
checked_outputs = json.load(open(checked_file, "r"))
indexes = {}
best_solutions = json.load(open(best_solution_file, "r"))
solutions = {}
for dataset in checked_outputs:
solutions[dataset] = {}
indexes[dataset] = {}
for prompt in checked_outputs[dataset]:
solutions[dataset][prompt] = []
indexes[dataset][prompt] = {}
for name in checked_outputs[dataset][prompt]:
if not name.startswith(mode):
continue
for i, status in enumerate(checked_outputs[dataset][prompt][name][-1]):
if isinstance(status, str):
continue
elif "status" in status and status["status"] == "PASSED":
processor = CodeProcessor(status["passed_solution"], force_rename = True if dataset in ["openai_humaneval", "mbpp"] else False)
solution = processor.run(no_modify = True)
solutions[dataset][prompt].append(solution)
if solution[0] not in indexes[dataset][prompt]:
indexes[dataset][prompt][solution[0]] = []
indexes[dataset][prompt][solution[0]].append([name, len(checked_outputs[dataset][prompt][name])-1, i])
if "groundtruth" not in checked_outputs[dataset][prompt]:
checked_outputs[dataset][prompt]["groundtruth"] = best_solutions[dataset][prompt]
solutions[dataset][prompt].append(best_solutions[dataset][prompt])
indexes[dataset][prompt][best_solutions[dataset][prompt][0]] = [["groundtruth", 0, 0]]
with open(os.path.join(result_dir, model, mode, f"FINAL_CHECKED.json"), "w", encoding = "utf-8") as f:
f.write(json.dumps(checked_outputs, sort_keys=True, indent=4, separators=(',', ': ')))
with open(os.path.join(result_dir, model, mode, f"FINAL_PASSED_SOLUTIONS.json"), "w", encoding = "utf-8") as f:
f.write(json.dumps(solutions, sort_keys=True, indent=4, separators=(',', ': ')))
with open(os.path.join(result_dir, model, mode, f"FINAL_INDEXES.json"), "w", encoding = "utf-8") as f:
f.write(json.dumps(indexes, sort_keys=True, indent=4, separators=(',', ': ')))
def handle_natural_strings(self, lst):
ans = []
for string in lst:
if string == None:
status = self.build_new_status()
status["status"] = "QUERY_ERROR"
ans.append(status)
continue
if isinstance(string, dict):
ans.append(string)
continue
string = string.replace("\r\n", "\n").replace("\n\n", "\n")
if "```python" in string:
string = string.split("```python")[0]
if "```" in string:
string = string.split("```")[0]
if string.startswith("\n"):
string = string[1:]
if string.endswith("\n"):
string = string[:-1]
string = string.strip()
if string.split("\n")[-1].endswith(":"):
string = "\n".join(string.split("\n")[:-1])
if string.count("Comment:") > 1:
string = "Comment:".join(string.split("Comment:")[:1])
if len(string.replace("\n", "")) == 0:
status = self.build_new_status()
status["status"] = "QUERY_ERROR"
ans.append(status)
else:
ans.append(string)
return ans
def verify_natural_outputs(self, rd):
for dataset in self.checked_outputs:
for prompt in self.checked_outputs[dataset]:
for name in self.checked_outputs[dataset][prompt]:
if name == "correct_solutions":
continue
if name == "multiple_agents_with_reviewer":
if len(self.checked_outputs[dataset][prompt][name]) > 1 and rd == 1:
strings = []
for string in self.checked_outputs[dataset][prompt][name][1]:
if string == None:
status = self.build_new_status()
status["status"] = "QUERY_ERROR"
strings.append(status)
elif "[Agree]" in string:
comment = self.handle_natural_strings([string.split("[Agree]")[-1]])[0]
strings.append("[Agree]" + comment if comment != None else " ")
elif "[Disagree]" in string:
comment = self.handle_natural_strings([string.split("[Disagree]")[-1]])[0]
strings.append("[Disagree]" + comment if comment != None else " ")
else:
status = self.build_new_status()
status["status"] = "QUERY_ERROR"
strings.append(status)
self.checked_outputs[dataset][prompt][name][1] = self.handle_natural_strings(strings)
elif name == "multiple_agents_with_team":
if len(self.checked_outputs[dataset][prompt][name]) > 0 and rd == 0:
self.checked_outputs[dataset][prompt][name][0] = self.handle_natural_strings(self.checked_outputs[dataset][prompt][name][0])
if len(self.checked_outputs[dataset][prompt][name]) > 2 and rd == 2:
strings = []
for string in self.checked_outputs[dataset][prompt][name][2]:
if string == None:
status = self.build_new_status()
status["status"] = "QUERY_ERROR"
strings.append(status)
elif "[Agree]" in string:
comment = self.handle_natural_strings([string.split("[Agree]")[-1]])[0]
strings.append("[Agree]" + comment if comment != None else " ")
elif "[Disagree]" in string:
comment = self.handle_natural_strings([string.split("[Disagree]")[-1]])[0]
strings.append("[Disagree]" + comment if comment != None else " ")
else:
status = self.build_new_status()
status["status"] = "QUERY_ERROR"
strings.append(status)
self.checked_outputs[dataset][prompt][name][2] = self.handle_natural_strings(strings)
if len(self.checked_outputs[dataset][prompt][name]) > 3 and rd == 3:
self.checked_outputs[dataset][prompt][name][3] = self.handle_natural_strings(self.checked_outputs[dataset][prompt][name][3])
elif not self.prompt_generator.gen_code(rd, name) and len(self.checked_outputs[dataset][prompt][name]) > rd:
self.checked_outputs[dataset][prompt][name][rd] = self.handle_natural_strings(self.checked_outputs[dataset][prompt][name][rd])
return self.checked_outputs
def estimate_pass_at_k(
self,
num_samples,
num_correct,
k: int,
):
"""
Estimates pass@k of each problem and returns them in an array.
"""
def estimator(n: int, c: int, k: int) -> float:
"""
Calculates 1 - comb(n - c, k) / comb(n, k).
"""
if n - c < k:
return 1.0
return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1))
if isinstance(num_samples, int):
num_samples_it = itertools.repeat(num_samples, len(num_correct))
else:
assert len(num_samples) == len(num_correct)
num_samples_it = iter(num_samples)
return np.array(
[estimator(int(n), int(c), k) for n, c in zip(num_samples_it, num_correct)]
)
def evaluate_pass_rate(self, result_dir, model, mode, rd = None):
if rd != None:
checked_outputs = json.load(open(os.path.join(result_dir, model, mode, f"rd{rd}_CHECKED.json"), "r"))
else:
checked_outputs = json.load(open(os.path.join(result_dir, model, mode, f"FINAL_CHECKED.json"), "r"))
prompt_generator = Prompt(chat=True)
prompt_generator.load_templates()
correct_nums = {}
for dataset in checked_outputs:
correct_nums[dataset] = {}
for prompt in checked_outputs[dataset]:
for name in checked_outputs[dataset][prompt]:
if name == "correct_solutions":
if name not in correct_nums[dataset]:
correct_nums[dataset][name] = []
num = 0
for i, status in enumerate(checked_outputs[dataset][prompt][name]):
if isinstance(status, dict) and "status" in status and status["status"] in ["PASSED", "TIME_MEASURED"]:
num += 1
correct_nums[dataset][name].append(num)
continue
if rd != None and name not in ["correct_solutions", "groundtruth"] and not prompt_generator.gen_code(rd, name):
continue
if name == "groundtruth":
continue
if name not in correct_nums[dataset]:
correct_nums[dataset][name] = []
num = 0
for i, status in enumerate(checked_outputs[dataset][prompt][name][-1]):
if status == "<END>":
if rd != None:
status, _ = self.find_result(dataset, prompt, name, len(checked_outputs[dataset][prompt][name]) - 1, i, checked_outputs)
else:
continue
if isinstance(status, dict) and "status" in status and status["status"] in ["PASSED", "TIME_MEASURED"]:
num += 1
correct_nums[dataset][name].append(num)
pass_rates = {}
ks = [1, 5, 8, 10, 20]
for dataset in correct_nums:
pass_rates[dataset] = {}
for name in correct_nums[dataset]:
pass_rates[dataset][name] = {}
for k in ks:
pass_rates[dataset][name][k] = sum(self.estimate_pass_at_k(20, correct_nums[dataset][name], k))/len(correct_nums[dataset][name])
if rd != None:
result_file = os.path.join(result_dir, model, mode, f"rd{rd}_pass_rate.json")
else:
result_file = os.path.join(result_dir, model, mode, f"FINAL_pass_rate.json")
with open(result_file, "w", encoding = "utf-8") as f:
f.write(json.dumps(pass_rates, sort_keys=True, indent=4, separators=(',', ': ')))
def evaluate_correctness(self, result_dir):
models = [
"_transformers_models--meta-llama--Meta-Llama-3-70B-Instruct_snapshots_e8cf5276ae3e97cfde8a058e64a636f2cde47820",
"gpt-3.5-turbo"
]
results = {}
for m in models:
results[m] = {}
checked_outputs_base = json.load(open(os.path.join(result_dir, m, "base", f"rd0_CHECKED.json"), "r"))
checked_outputs_rd0 = json.load(open(os.path.join(result_dir, m, "correctness", f"rd0_CHECKED.json"), "r"))
checked_outputs_rd1 = json.load(open(os.path.join(result_dir, m, "correctness", f"rd1_CHECKED.json"), "r"))
checked_outputs_final = json.load(open(os.path.join(result_dir, m, "time", f"FINAL_CHECKED.json"), "r"))
correct_nums = {}
ks = [1, 5, 8, 10, 20]
key_map = {
"base": checked_outputs_base,
"correctness_testcase_feedback": checked_outputs_rd0,
"correctness_reflection_and_feedback": checked_outputs_rd1
}
prompts = {}
for dataset in checked_outputs_final:
prompts[dataset] = []
for prompt in checked_outputs_final[dataset]:
min_groundtruth_time = None
for status in checked_outputs_final[dataset][prompt]["groundtruth"]:
if status["status"] == "TIME_MEASURED":
if min_groundtruth_time == None:
min_groundtruth_time = status["exec_time"]
elif status["exec_time"] < min_groundtruth_time:
min_groundtruth_time = status["exec_time"]
if min_groundtruth_time == None:
continue
else:
prompts[dataset].append(prompt)
nums = {}
for key in key_map:
for dataset in key_map[key]:
if dataset not in correct_nums:
correct_nums[dataset] = {}
for prompt in key_map[key][dataset]:
if prompt not in prompts[dataset]:
continue
for name in key_map[key][dataset][prompt]:
if name == key and name == "base":
if name not in correct_nums[dataset]:
correct_nums[dataset][name] = {}
best = {}
for k in ks:
best[k] = 0
if k not in correct_nums[dataset][name]:
correct_nums[dataset][name][k] = 0
for i, status in enumerate(key_map[key][dataset][prompt][name][-1]):
if isinstance(status, dict) and "status" in status and status["status"] in ["PASSED", "TIME_MEASURED"]:
for k in ks:
if i < k:
best[k] += 1
for k in ks:
if best[k] > 0:
correct_nums[dataset][name][k] += 1
elif name == key:
if name not in correct_nums[dataset]:
correct_nums[dataset][name] = {}
best = {}
for k in ks:
best[k] = 0
if k not in correct_nums[dataset][name]:
correct_nums[dataset][name][k] = 0
for i, status in enumerate(key_map[key][dataset][prompt][name][-1]):
if status == "<END>":
status, _ = self.find_result(dataset, prompt, name, len(key_map[key][dataset][prompt][name]) - 1, i, key_map[key])
if isinstance(status, dict) and "status" in status and status["status"] in ["PASSED", "TIME_MEASURED"]:
for k in ks:
if i < k:
best[k] += 1
for k in ks:
if best[k] > 0:
correct_nums[dataset][name][k] += 1
for dataset in correct_nums:
results[m][dataset] = {}
for name in correct_nums[dataset]:
results[m][dataset][name] = {}
for k in correct_nums[dataset][name]:
results[m][dataset][name][k] = correct_nums[dataset][name][k] / len(prompts[dataset])
result_file = os.path.join(result_dir, f"correctness.json")
csv_file = os.path.join(result_dir, f"correctness.csv")
lines = []
for m in results:
lines.append(m + "+" * 20)
for dataset in results[m]:
lines.append(dataset + "="*10)
lines.append("Prompt,Best@1,Best@8,Best@20")
for name in results[m][dataset]:
lines.append("{},{},{},{}".format(
name,
format(results[m][dataset][name][1] * 100, ".2f"),
format(results[m][dataset][name][8] * 100, ".2f"),
format(results[m][dataset][name][20] * 100, ".2f")
))
with open(result_file, "w", encoding = "utf-8") as f:
f.write(json.dumps(results, sort_keys=True, indent=4, separators=(',', ': ')))
with open(csv_file, "w", encoding = "utf-8") as f:
f.write("\n".join(lines))
def evaluate_execution_time(self, result_dir, model, mode, fallback = True):
checked_file = os.path.join(result_dir, model, mode, f"FINAL_CHECKED.json")
checked_outputs = json.load(open(checked_file, "r"))
ks = [1, 5, 8, 10, 20]
nums = {}
gt_speedup = {}
gt_opt = {}
total_num = {}
correctness = {}
overall_num = {}
for dataset in checked_outputs:
nums[dataset] = {}
gt_speedup[dataset] = {}
gt_opt[dataset] = {}
total_num[dataset] = {}
correctness[dataset] = {}
overall_num[dataset] = {}
for prompt in checked_outputs[dataset]:
min_groundtruth_time = None
for status in checked_outputs[dataset][prompt]["groundtruth"]:
if status["status"] == "TIME_MEASURED":
if min_groundtruth_time == None:
min_groundtruth_time = status["exec_time"]
elif status["exec_time"] < min_groundtruth_time:
min_groundtruth_time = status["exec_time"]
if min_groundtruth_time == None:
continue
for name in checked_outputs[dataset][prompt]:
if not name.startswith("time") and name != "base":
continue
if name not in nums[dataset]:
nums[dataset][name] = {}
gt_speedup[dataset][name] = {}
gt_opt[dataset][name] = {}
correctness[dataset][name] = {}
total_num[dataset][name] = 0
for k in ks:
gt_speedup[dataset][name][k] = 0
gt_opt[dataset][name][k] = 0
nums[dataset][name][k] = 0
correctness[dataset][name][k] = 0
overall_num[dataset][name] = 0
gt_speedup[dataset][name]["avg"] = 0
gt_opt[dataset][name]["avg"] = 0
correctness[dataset][name]["avg"] = 0
best = {}
correct_num = {}
for k in ks:
best[k] = 0
correct_num[k] = 0
num = 0
temp_gt_speedup = 0
temp_gt_opt = 0
overall_num[dataset][name] += 1
for i, status in enumerate(checked_outputs[dataset][prompt][name][-1]):
if isinstance(status, dict) and status["status"] == "TIME_MEASURED":
cur_status = status
elif isinstance(checked_outputs[dataset][prompt]["correct_solutions"][i], dict) and checked_outputs[dataset][prompt]["correct_solutions"][i]["status"] == "TIME_MEASURED" and fallback and name != "base":
cur_status = checked_outputs[dataset][prompt]["correct_solutions"][i]
else:
continue
if min_groundtruth_time / cur_status["exec_time"] > 100 and dataset in ["openai_humaneval", "mbpp"]:
continue
for k in ks:
if i < k:
if best[k] == 0:
best[k] = cur_status["exec_time"]
elif best[k] > 0 and cur_status["exec_time"] < best[k]:
best[k] = cur_status["exec_time"]
correct_num[k] += 1
num += 1
temp_gt_speedup += min_groundtruth_time / cur_status["exec_time"]
if (min_groundtruth_time - cur_status["exec_time"]) / min_groundtruth_time > 0.1:
temp_gt_opt += 1
if num > 0:
total_num[dataset][name] += 1
gt_speedup[dataset][name]["avg"] += temp_gt_speedup / num
gt_opt[dataset][name]["avg"] += temp_gt_opt / num
correctness[dataset][name]["avg"] += num / 20
for k in ks:
if correct_num[k] > 0:
correctness[dataset][name][k] += 1
if best[k] > 0:
nums[dataset][name][k] += 1
gt_speedup[dataset][name][k] += min_groundtruth_time / best[k]
if (min_groundtruth_time - best[k]) / min_groundtruth_time > 0.1:
gt_opt[dataset][name][k] += 1
for name in gt_speedup[dataset]:
for k in ks:
gt_speedup[dataset][name][k] = gt_speedup[dataset][name][k] / nums[dataset][name][k]
gt_opt[dataset][name][k] = gt_opt[dataset][name][k] / overall_num[dataset][name]
#gt_opt[dataset][name][k] = gt_opt[dataset][name][k] / nums[dataset][name][k]
correctness[dataset][name][k] = correctness[dataset][name][k] / overall_num[dataset][name]
gt_speedup[dataset][name]["avg"] = gt_speedup[dataset][name]["avg"] / total_num[dataset][name]
gt_opt[dataset][name]["avg"] = gt_opt[dataset][name]["avg"] / overall_num[dataset][name]
correctness[dataset][name]["avg"] = correctness[dataset][name]["avg"] / overall_num[dataset][name]
data = {}
for dataset in gt_speedup:
data[dataset] = {
"gt_speedup": gt_speedup[dataset],
"gt_opt": gt_opt[dataset],
"correctness": correctness[dataset],
"num": overall_num[dataset]
}
if fallback:
result_file = os.path.join(result_dir, model, mode, f"FINAL_exec_time.json")
else:
result_file = os.path.join(result_dir, model, mode, f"FINAL_exec_time_nofallback.json")
with open(result_file, "w", encoding = "utf-8") as f:
f.write(json.dumps(data, indent=4, separators=(',', ': ')))
def evaluate_execution_time_old(self, result_dir, model, mode):
checked_file = os.path.join(result_dir, model, mode, f"FINAL_CHECKED.json")
checked_outputs = json.load(open(checked_file, "r"))
ks = [1, 5, 8, 10, 20]
nums = {}
gt_speedup = {}
gt_opt = {}
ori_speedup = {}
ori_opt = {}
total_num = {}
correctness = {}
overall_num = {}
for dataset in checked_outputs:
nums[dataset] = {}
gt_speedup[dataset] = {}
gt_opt[dataset] = {}
ori_speedup[dataset] = {}
ori_opt[dataset] = {}
total_num[dataset] = {}
correctness[dataset] = {}
overall_num[dataset] = {}
for prompt in checked_outputs[dataset]:
min_groundtruth_time = None
for status in checked_outputs[dataset][prompt]["groundtruth"]:
if status["status"] == "TIME_MEASURED":
if min_groundtruth_time == None:
min_groundtruth_time = status["exec_time"]
elif status["exec_time"] < min_groundtruth_time:
min_groundtruth_time = status["exec_time"]
if min_groundtruth_time == None:
continue
for name in checked_outputs[dataset][prompt]:
if not name.startswith("time") or name == "time_multiple_agents_with_reviewer":
continue
if name not in nums[dataset]:
nums[dataset][name] = {}
gt_speedup[dataset][name] = {}
gt_opt[dataset][name] = {}
correctness[dataset][name] = 0
total_num[dataset][name] = 0
for k in ks:
gt_speedup[dataset][name][k] = 0
gt_opt[dataset][name][k] = 0
nums[dataset][name][k] = 0
gt_speedup[dataset][name]["avg"] = 0
gt_opt[dataset][name]["avg"] = 0
ori_speedup[dataset][name] = 0
ori_opt[dataset][name] = 0
overall_num[dataset][name] = 0
best = {}
for k in ks:
best[k] = 0
num = 0
temp_ori_speedup = 0
temp_ori_opt = 0
temp_gt_speedup = 0
temp_gt_opt = 0
correct_num = 0
for i, status in enumerate(checked_outputs[dataset][prompt][name][-1]):
if isinstance(status, dict) and status["status"] == "TIME_MEASURED":
if min_groundtruth_time / status["exec_time"] > 100 and dataset in ["openai_humaneval", "mbpp"]:
continue
for k in ks:
if i < k:
if best[k] == 0:
best[k] = status["exec_time"]
elif best[k] > 0 and status["exec_time"] < best[k]:
best[k] = status["exec_time"]
num += 1
temp_ori_speedup += checked_outputs[dataset][prompt]["correct_solutions"][i]["exec_time"] / status["exec_time"]
temp_gt_speedup += min_groundtruth_time / status["exec_time"]
if (checked_outputs[dataset][prompt]["correct_solutions"][i]["exec_time"] - status["exec_time"]) / checked_outputs[dataset][prompt]["correct_solutions"][i]["exec_time"] >= 0.1:
temp_ori_opt += 1
if (min_groundtruth_time - status["exec_time"]) / min_groundtruth_time > 0.1:
temp_gt_opt += 1
if isinstance(checked_outputs[dataset][prompt]["correct_solutions"][i], dict) and checked_outputs[dataset][prompt]["correct_solutions"][i]["status"] == "TIME_MEASURED":
correct_num += 1
if correct_num > 0:
overall_num[dataset][name] += 1
if num > 0:
ori_speedup[dataset][name] += temp_ori_speedup / num
ori_opt[dataset][name] += temp_ori_opt / num
gt_speedup[dataset][name]["avg"] += temp_gt_speedup / num
gt_opt[dataset][name]["avg"] += temp_gt_opt / num
total_num[dataset][name] += 1
correctness[dataset][name] += num / correct_num
for k in ks:
if best[k] > 0:
nums[dataset][name][k] += 1
gt_speedup[dataset][name][k] += min_groundtruth_time / best[k]
if (min_groundtruth_time - best[k]) / min_groundtruth_time > 0.1:
gt_opt[dataset][name][k] += 1
for name in gt_speedup[dataset]:
for k in ks:
gt_speedup[dataset][name][k] = gt_speedup[dataset][name][k] / nums[dataset][name][k]
gt_opt[dataset][name][k] = gt_opt[dataset][name][k] / nums[dataset][name][k]
gt_speedup[dataset][name]["avg"] = gt_speedup[dataset][name]["avg"] / total_num[dataset][name]
gt_opt[dataset][name]["avg"] = gt_opt[dataset][name]["avg"] / total_num[dataset][name]
ori_speedup[dataset][name] = ori_speedup[dataset][name] / total_num[dataset][name]
ori_opt[dataset][name] = ori_opt[dataset][name] / total_num[dataset][name]
correctness[dataset][name] = correctness[dataset][name] / overall_num[dataset][name]
data = {}
for dataset in gt_speedup:
data[dataset] = {
"gt_speedup": gt_speedup[dataset],
"gt_opt": gt_opt[dataset],
"ori_speedup": ori_speedup[dataset],
"ori_opt": ori_opt[dataset],
"correctness": correctness[dataset]
}
result_file = os.path.join(result_dir, model, mode, f"FINAL_exec_time_test.json")
with open(result_file, "w", encoding = "utf-8") as f:
f.write(json.dumps(data, indent=4, separators=(',', ': ')))
def get_better_solutions(self, result_dir, model, mode, name):
checked_file = os.path.join(result_dir, model, mode, f"FINAL_CHECKED.json")
checked_outputs = json.load(open(checked_file, "r"))
best_solutions = {}
for dataset in checked_outputs:
best_solutions[dataset] = {}
for prompt in checked_outputs[dataset]:
min_groundtruth_time = None
min_groundtruth = None
for status in checked_outputs[dataset][prompt]["groundtruth"]:
if status["status"] == "TIME_MEASURED":
if min_groundtruth_time == None:
min_groundtruth_time = status["exec_time"]
min_groundtruth = status["passed_solution"]
elif status["exec_time"] < min_groundtruth_time:
min_groundtruth_time = status["exec_time"]
min_groundtruth = status["passed_solution"]
if min_groundtruth_time == None:
continue
min_time = None
min_solution = None
for i, status in enumerate(checked_outputs[dataset][prompt][name][-1]):
if isinstance(status, dict) and status["status"] == "TIME_MEASURED":
cur_status = status
else:
continue
if min_time == None:
min_time = cur_status["exec_time"]
min_solution = status["passed_solution"]
elif cur_status["exec_time"] < min_time:
min_time = cur_status["exec_time"]
min_solution = status["passed_solution"]
if min_time == None or min_solution == None:
continue
speedup = min_groundtruth_time / min_time
if speedup < 2 :
continue
if prompt not in best_solutions[dataset]:
best_solutions[dataset][prompt] = [min_solution, min_groundtruth, speedup]
with open("better_solutions.json", "w", encoding = "utf-8") as f:
f.write(json.dumps(best_solutions, sort_keys=True, indent=4, separators=(',', ': ')))
def finalize_correctness_check(self, result_dir, model, mode, rd, task_num = 5, clean = False):
indexes = json.load(open(os.path.join(result_dir, model, mode, f"rd{rd}_INDEXES.json"), "r"))
checked_outputs = json.load(open(os.path.join(result_dir, model, mode, f"rd{rd}_CHECKED.json"), "r"))
solutions = json.load(open(os.path.join(result_dir, model, mode, f"rd{rd}_SOLUTIONS.json"), "r"))
for i in range(0, task_num):
passed_solutions = json.load(open(os.path.join(result_dir, model, mode, f"rd{rd}_PASSED_SOLUTIONS_p{i}.json"), "r"))
failed_cases = json.load(open(os.path.join(result_dir, model, mode, f"rd{rd}_FAILED_TESTCASES_p{i}.json"), "r"))
for dataset in failed_cases:
for prompt in failed_cases[dataset]:
for i, testcases in enumerate(failed_cases[dataset][prompt]):
if len(testcases) > 0:
for index in indexes[dataset][prompt][solutions[dataset][prompt][i][0]]:
checked_outputs[dataset][prompt][index[0]][index[1]][index[2]]["status"] = "TESTCASE_FAILED"
checked_outputs[dataset][prompt][index[0]][index[1]][index[2]]["failed_testcase"] = testcases
for dataset in passed_solutions:
for prompt in passed_solutions[dataset]:
for solution in passed_solutions[dataset][prompt]:
for index in indexes[dataset][prompt][solution[0]]:
checked_outputs[dataset][prompt][index[0]][index[1]][index[2]]["passed_solution"] = solution[0]
checked_outputs[dataset][prompt][index[0]][index[1]][index[2]]["status"] = "PASSED"
if clean:
for dataset in checked_outputs:
deleted_prompts = []
for prompt in checked_outputs[dataset]:
for name in checked_outputs[dataset][prompt]:
if name.startswith(mode) and self.prompt_generator.round_exist(rd, name):
try:
if self.is_unchecked(checked_outputs[dataset][prompt][name][rd]):
deleted_prompts.append(prompt)
continue
except Exception as e:
print(name, prompt, rd)
exit()
for i, status in enumerate(checked_outputs[dataset][prompt][name][rd]):
if isinstance(status, str):
continue
elif status == None:
checked_outputs[dataset][prompt][name][rd][i] = self.build_new_status()
checked_outputs[dataset][prompt][name][rd][i]["status"] = "QUERY_ERROR"
continue
if status["status"] == "Unchecked":
status["status"] = "TIMEOUT"
'''
for prompt in deleted_prompts:
del checked_outputs[dataset][prompt]
'''
with open(os.path.join(result_dir, model, mode, f"rd{rd}_CHECKED.json"), "w") as f:
f.write(json.dumps(checked_outputs, sort_keys=True, indent=4, separators=(',', ': ')))
def finalize_time_measurement(self, result_dir, model, mode, task_num = 10, rd = None):
if rd != None:
checked_file = os.path.join(result_dir, model, mode, f"rd{rd}_CHECKED.json")
checked_outputs = json.load(open(checked_file, "r"))
indexes = json.load(open(os.path.join(result_dir, model, mode, f"rd{rd}_INDEXES.json"), "r"))
solutions = json.load(open(os.path.join(result_dir, model, mode, f"rd{rd}_PASSED_SOLUTIONS.json"), "r"))
else:
checked_file = os.path.join(result_dir, model, mode, f"FINAL_CHECKED.json")
checked_outputs = json.load(open(checked_file, "r"))
indexes = json.load(open(os.path.join(result_dir, model, mode, f"FINAL_INDEXES.json"), "r"))
solutions = json.load(open(os.path.join(result_dir, model, mode, f"FINAL_PASSED_SOLUTIONS.json"), "r"))
for i in range(0, task_num):
if rd != None:
time_costs = json.load(open(os.path.join(result_dir, model, mode, f"rd{rd}_TIME_COSTS_p{i}.json"), "r"))
large_cases = json.load(open(os.path.join(result_dir, model, mode, f"rd{rd}_LARGE_TESTCASES_p{i}.json"), "r"))
else:
if not os.path.exists(os.path.join(result_dir, model, mode, f"FINAL_TIME_COSTS_p{i}.json")):
print(f"Cannot find test cost files for split #{i}.")
continue
time_costs = json.load(open(os.path.join(result_dir, model, mode, f"FINAL_TIME_COSTS_p{i}.json"), "r"))
large_cases = json.load(open(os.path.join(result_dir, model, mode, f"FINAL_LARGE_TESTCASES_p{i}.json"), "r"))
for dataset in time_costs:
for prompt in time_costs[dataset]:
for i, cost in enumerate(time_costs[dataset][prompt]):
for index in indexes[dataset][prompt][solutions[dataset][prompt][i][0]]:
if index[0] in ["correct_solutions", "groundtruth"]:
if checked_outputs[dataset][prompt][index[0]][index[2]]["status"] not in ["PASSED", "TIME_MEASURED"]:
print("Inconsistent data occurred, status: {}".format(checked_outputs[dataset][prompt][index[0]][index[2]]["status"]))