-
Notifications
You must be signed in to change notification settings - Fork 1
/
evaluate.py
707 lines (661 loc) · 23.6 KB
/
evaluate.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
# Turn level 2.0
import json
import os
from tqdm import tqdm
from typing import Literal, List, Union
from utils.misc import get_logger
from utils.constants import INFERENCE_OUTPUT, EVALUATION_OUTPUT
from nltk.tokenize import sent_tokenize
from strictfire import StrictFire
from utils.openai_generate import generate
# from tests.mocks import openai_generate_evaluate_mock as generate
OUTPUT_FOLDER = "output"
TASK_NAMES = [
"refinement_single",
"refinement_multi",
"refinement_multi_gold",
"expansion_single",
"expansion_multi",
"expansion_multi_gold",
"follow-up_single",
"follow-up_multi",
"follow-up_multi_gold",
]
DOCUMENTS = [json.loads(row) for row in open("raw_data/documents.jsonl")]
JUDGE_MODEL = "gpt-4-0613"
TEMPERATURE = 0
MAX_NEW_TOKENS = 1024
# Trim the topic.
for doc in DOCUMENTS:
doc["gen_resp"] = doc["gen_resp"].split("\n\n", 1)[1]
logger = get_logger(
name=__name__,
console_level="info",
file_level="debug",
log_path=os.path.join("log", "evaluate.log"),
maxBytes=10000000,
)
# require document and queries
# queries from predictions
# document from id
def evaluate_refinement_single(filename: str):
model = filename.split("_")[-1].split(".")[0]
prompt_template = open("prompts/refinement_single_evaluation.txt").read()
data = [json.loads(row) for row in open(filename)]
n_complete = sum(
"gen_resp" in turn for dial in data for turn in dial["conv"]
)
visited_ids = set()
out_filename = os.path.join(
EVALUATION_OUTPUT, "refinement", os.path.split(filename)[-1]
)
os.makedirs(os.path.dirname(out_filename), exist_ok=True)
outputs = []
if os.path.exists(out_filename):
outputs = [json.loads(row) for row in open(out_filename)]
for row in outputs:
visited_ids.add(row["id"])
total = 200
if len(outputs) == total:
logger.info(f"Evaluated refinement_single for {model}")
return
if n_complete != total:
logger.info(
f"`{filename}` only has {n_complete} outputs. It should have"
f" {total}."
)
pbar = tqdm(total=total, desc=f"Evaluate {filename}")
n_evaluate = 0
for dial_i, dial in enumerate(data):
for turn_i, turn in enumerate(dial["conv"]):
doc_i = int(turn["id"].split("_")[0]) - 1
doc: str = DOCUMENTS[doc_i]["gen_resp"]
_id = f"{dial['id']}"
if (
_id in visited_ids
or not turn["do_inference"]
or "gen_resp" not in turn
):
pbar.update(1)
continue
query = turn["inst"]
resp = turn["gen_resp"]
word_count = len(resp.split())
sent_count = len(sent_tokenize(resp))
prompt = (
prompt_template.replace("{response}", resp)
.replace("{content}", doc)
.replace("{num_words}", str(word_count))
.replace("{num_sent}", str(sent_count))
.replace("{constraints}", query)
)
resp, prompt_len, token_per_second = generate(
model_name=JUDGE_MODEL,
prompt=prompt,
temperature=TEMPERATURE,
max_tokens=MAX_NEW_TOKENS,
)
outputs.append({
"gen_resp": resp,
"from": filename,
"prompt": prompt,
"prompt_len": prompt_len,
"id": _id,
"turn": 1,
})
pbar.update(1)
n_evaluate += 1
if len(outputs) % 10 == 0:
with open(out_filename, "w", encoding="utf-8") as f:
f.write(
"\n".join([
json.dumps(row, ensure_ascii=False)
for row in outputs
])
)
pbar.refresh()
logger.info(
f"Evaluated {n_evaluate} instances in refinement_single for"
f" {model} . Output saved in {out_filename}."
)
def evaluate_refinement_multi(filename: str):
prompt_template = open("prompts/refinement_multi_evaluation.txt").read()
model = filename.split("_")[-1].split(".")[0]
data = [json.loads(row) for row in open(filename)]
n_complete = sum(
"gen_resp" in turn for dial in data for turn in dial["conv"]
)
visited_ids = set()
out_filename = os.path.join(
EVALUATION_OUTPUT, "refinement", os.path.split(filename)[-1]
)
os.makedirs(os.path.dirname(out_filename), exist_ok=True)
outputs = []
if os.path.exists(out_filename):
outputs = [json.loads(row) for row in open(out_filename)]
for row in outputs:
visited_ids.add(row["id"])
total = 480
task_name = "refinement_multi"
if "gold" in filename:
task_name += "_gold"
if len(outputs) == total:
logger.info(f"Evaluated {task_name} for {model}")
return
if n_complete != total:
logger.info(
f"`{filename}` only has {n_complete} outputs. It should have 480."
)
prev_task_type = ""
pbar = tqdm(total=total, desc=f"Evaluate {filename}")
n_evaluate = 0
for dial_i, dial in enumerate(data):
doc_i = int(dial["conv"][0]["id"].split("_")[0]) - 1
doc: str = DOCUMENTS[doc_i]["gen_resp"]
constraints = []
prev_task_type: str = dial["conv"][0]["id"].split("_")[1]
resp_turn_i = 0
for turn_i, turn in enumerate(dial["conv"]):
_id = f"{dial['id']}#{turn['id']}"
resp_turn_i += turn["do_inference"]
if (
_id in visited_ids
or not turn["do_inference"]
or "gen_resp" not in turn
):
pbar.update(1)
continue
cur_task_type = turn["id"].split("_")[1]
if prev_task_type != cur_task_type:
constraints = []
prev_task_type = cur_task_type
query = turn["inst"]
constraints.append(query)
resp = turn["gen_resp"]
word_count = len(resp.split())
sent_count = len(sent_tokenize(resp))
prompt = (
prompt_template.replace("{response}", resp)
.replace("{content}", doc)
.replace("{num_words}", str(word_count))
.replace("{num_sent}", str(sent_count))
.replace(
"{constraints}",
"\n".join(
[f"{i}. {c}" for i, c in enumerate(constraints, 1)]
),
)
)
resp, prompt_len, token_per_second = generate(
model_name=JUDGE_MODEL,
prompt=prompt,
temperature=TEMPERATURE,
max_tokens=MAX_NEW_TOKENS,
)
outputs.append({
"gen_resp": resp,
"from": filename,
"prompt": prompt,
"prompt_len": prompt_len,
"id": _id,
"turn": resp_turn_i,
})
n_evaluate += 1
pbar.update(1)
visited_ids.add(_id)
if len(outputs) % 10 == 0:
with open(out_filename, "w", encoding="utf-8") as f:
f.write(
"\n".join([
json.dumps(row, ensure_ascii=False)
for row in outputs
])
)
with open(out_filename, "w", encoding="utf-8") as f:
f.write(
"\n".join([json.dumps(row, ensure_ascii=False) for row in outputs])
)
pbar.refresh()
logger.info(
f"Evaluated {n_evaluate} instances in {task_name} for"
f" {model} . Output saved in {out_filename}."
)
def evaluate_follow_up_multi(filename: str):
prompt_template = open("prompts/mt-bench_evaluation.txt").read()
model = filename.split("_")[-1].split(".")[0]
data = [json.loads(row) for row in open(filename)]
n_complete = sum(
"gen_resp" in turn
for dial in data
for turn in dial["conv"]
if turn["do_inference"]
)
visited_ids = set()
out_filename = os.path.join(
EVALUATION_OUTPUT, "follow-up", os.path.split(filename)[-1]
)
os.makedirs(os.path.dirname(out_filename), exist_ok=True)
outputs = []
if os.path.exists(out_filename):
outputs = [json.loads(row) for row in open(out_filename)]
for row in outputs:
visited_ids.add(row["id"])
total = 240
task_name = "follow-up_multi"
if "gold" in filename:
task_name += "_gold"
if len(outputs) == total:
logger.info(f"Evaluated {task_name} for {model}")
return
if n_complete != total:
logger.info(
f"`{filename}` only has {n_complete} outputs. It should have"
f" {total}."
)
pbar = tqdm(total=total, desc=f"Evaluate {filename}")
n_evaluate = 0
for dial in data:
resp_turn_i = 0
for i, turn in enumerate(dial["conv"]):
resp_turn_i += turn["do_inference"]
_id = f"{dial['id']}#{turn['id']}"
if not turn["do_inference"]:
continue
if _id in visited_ids or "gen_resp" not in turn:
pbar.update(1)
continue
resp = turn["gen_resp"].strip()
conversation = [
f"User: {dial['conv'][i-1]['user'].strip()}",
f"Assistant: {dial['conv'][i-1]['sys'].strip()}",
f"User: {turn['user'].strip()}",
f"Assistant: {resp}",
]
word_count = len(resp.split())
sent_count = len(sent_tokenize(resp))
prompt = (
prompt_template.replace(
"{conversation}", "\n".join(conversation)
)
.replace("{num_words}", str(word_count))
.replace("{num_sent}", str(sent_count))
)
resp, prompt_len, token_per_second = generate(
model_name=JUDGE_MODEL,
prompt=prompt,
temperature=TEMPERATURE,
max_tokens=MAX_NEW_TOKENS,
)
outputs.append({
"gen_resp": resp,
"from": filename,
"prompt": prompt,
"prompt_len": prompt_len,
"id": _id,
"turn": resp_turn_i,
})
n_evaluate += 1
pbar.update(1)
visited_ids.add(_id)
if len(outputs) % 10 == 0:
with open(out_filename, "w", encoding="utf-8") as f:
f.write(
"\n".join([
json.dumps(row, ensure_ascii=False)
for row in outputs
])
)
with open(out_filename, "w", encoding="utf-8") as f:
f.write(
"\n".join([json.dumps(row, ensure_ascii=False) for row in outputs])
)
pbar.refresh()
logger.info(
f"Evaluated {n_evaluate} instances in {task_name} for"
f" {model} . Output saved in {out_filename}."
)
def evaluate_expansion(filename: str, mode: Literal["single", "multi"]):
prompt_template = open("prompts/expansion_evaluation.txt").read()
data = [json.loads(row) for row in open(filename)]
model = filename.split("_")[-1].split(".")[0]
n_complete = sum(
"gen_resp" in turn
for dial in data
for turn in dial["conv"]
if turn["do_inference"]
)
visited_ids = set()
out_filename = os.path.join(
EVALUATION_OUTPUT, "expansion", os.path.split(filename)[-1]
)
os.makedirs(os.path.dirname(out_filename), exist_ok=True)
outputs = []
if os.path.exists(out_filename):
outputs = [json.loads(row) for row in open(out_filename)]
for row in outputs:
visited_ids.add(row["id"])
total = 70
task_name = f"expansion_{mode}"
if "gold" in filename:
task_name += "_gold"
if len(outputs) == total:
logger.info(f"Evaluated {task_name} for {model}")
return
if n_complete != total:
logger.info(
f"`{filename}` only has {n_complete} outputs. It should have"
f" {total}."
)
pbar = tqdm(total=total, desc=f"Evaluate {filename}")
n_evaluate = 0
for dial in data:
resp_turn_i = 0
for i, turn in enumerate(dial["conv"]):
resp_turn_i += turn["do_inference"]
if mode == "multi":
_id = f"{dial['id']}#{turn['id']}"
else:
_id = f"{dial['id']}"
if (
_id in visited_ids
or not turn["do_inference"]
or "gen_resp" not in turn
):
pbar.update(1)
continue
if mode == "multi":
doc_i = int(turn["id"].split("_")[0]) - 1
else:
doc_i = int(turn["id"].split("#")[1].split("_")[0]) - 1
doc: str = DOCUMENTS[doc_i]["gen_resp"]
inst = turn["inst"]
resp = turn["gen_resp"].strip()
prompt = (
prompt_template.replace("{response}", resp)
.replace("{content}", doc)
.replace("{constraints}", inst)
)
resp, prompt_len, token_per_second = generate(
model_name=JUDGE_MODEL,
prompt=prompt,
temperature=TEMPERATURE,
max_tokens=MAX_NEW_TOKENS,
)
outputs.append({
"gen_resp": resp,
"from": filename,
"prompt": prompt,
"prompt_len": prompt_len,
"id": _id,
"turn": resp_turn_i,
})
n_evaluate += 1
pbar.update(1)
visited_ids.add(_id)
if len(outputs) % 10 == 0:
with open(out_filename, "w", encoding="utf-8") as f:
f.write(
"\n".join([
json.dumps(row, ensure_ascii=False)
for row in outputs
])
)
with open(out_filename, "w", encoding="utf-8") as f:
f.write(
"\n".join([json.dumps(row, ensure_ascii=False) for row in outputs])
)
pbar.refresh()
logger.info(
f"Evaluated {n_evaluate} instances in {task_name} for"
f" {model} . Output saved in {out_filename}."
)
def evaluate_follow_up_single(filename: str):
prompt_template = open("prompts/mt-bench_evaluation.txt").read()
data = [json.loads(row) for row in open(filename)]
model = filename.split("_")[-1].split(".")[0]
n_complete = sum(
"gen_resp" in turn
for dial in data
for turn in dial["conv"]
if turn["do_inference"]
)
visited_ids = set()
out_filename = os.path.join(
EVALUATION_OUTPUT, "follow-up", os.path.split(filename)[-1]
)
os.makedirs(os.path.dirname(out_filename), exist_ok=True)
outputs = []
if os.path.exists(out_filename):
outputs = [json.loads(row) for row in open(out_filename)]
for row in outputs:
visited_ids.add(row["id"])
total = 240
if len(outputs) == total:
logger.info(f"Evaluated follow-up_single for {model}")
return
if n_complete != total:
logger.info(
f"`{filename}` only has {n_complete} outputs. It should have"
f" {total}."
)
pbar = tqdm(total=total, desc=f"Evaluate {filename}")
n_evaluate = 0
for dial in data:
for i, turn in enumerate(dial["conv"]):
_id = f"{dial['id']}"
if (
_id in visited_ids
or not turn["do_inference"]
or "gen_resp" not in turn
):
pbar.update(1)
continue
resp = turn["gen_resp"].strip()
dial_id, turn_id = dial["id"].split("#")
conversation = [
f"User: {turn['user'].strip()}",
f"Assistant: {resp}",
]
word_count = len(resp.split())
sent_count = len(sent_tokenize(resp))
prompt = (
prompt_template.replace(
"{conversation}", "\n".join(conversation)
)
.replace("{num_words}", str(word_count))
.replace("{num_sent}", str(sent_count))
)
resp, prompt_len, token_per_second = generate(
model_name=JUDGE_MODEL,
prompt=prompt,
temperature=TEMPERATURE,
max_tokens=MAX_NEW_TOKENS,
)
outputs.append({
"gen_resp": resp,
"from": filename,
"prompt": prompt,
"prompt_len": prompt_len,
"id": _id,
"turn": 1,
})
pbar.update(1)
n_evaluate += 1
visited_ids.add(_id)
if len(outputs) % 10 == 0:
with open(out_filename, "w", encoding="utf-8") as f:
f.write(
"\n".join([
json.dumps(row, ensure_ascii=False)
for row in outputs
])
)
with open(out_filename, "w", encoding="utf-8") as f:
f.write(
"\n".join([json.dumps(row, ensure_ascii=False) for row in outputs])
)
pbar.refresh()
logger.info(
f"Evaluated {n_evaluate} instances in follow-up_single for"
f" {model} . Output saved in {out_filename}."
)
def evaluate_refinement_ablation(filename: str):
prompt_template = open("prompts/refinement_multi_evaluation.txt").read()
model = filename.split("_")[-1].split(".")[0]
data = [json.loads(row) for row in open(filename)]
n_complete = sum(
"gen_resp" in turn for dial in data for turn in dial["conv"]
)
visited_ids = set()
out_filename = os.path.join(
EVALUATION_OUTPUT, "refinement", os.path.split(filename)[-1]
)
os.makedirs(os.path.dirname(out_filename), exist_ok=True)
outputs = []
if os.path.exists(out_filename):
outputs = [json.loads(row) for row in open(out_filename)]
for row in outputs:
visited_ids.add(row["id"])
total = 120
task_name = "refinement_ablation"
if "front" in filename:
task_name += "_front"
else:
task_name += "_middle"
if len(outputs) == total:
logger.info(f"Evaluated {task_name} for {model}")
return
if n_complete != total:
logger.info(
f"`{filename}` only has {n_complete} outputs. It should have 480."
)
prev_task_type = ""
pbar = tqdm(total=total, desc=f"Evaluate {filename}")
n_evaluate = 0
for dial_i, dial in enumerate(data):
doc_i = int(dial["conv"][0]["id"].split("_")[0]) - 1
doc: str = DOCUMENTS[doc_i]["gen_resp"]
constraints = []
prev_task_type: str = dial["conv"][0]["id"].split("_")[1]
resp_turn_i = 0
for turn_i, turn in enumerate(dial["conv"]):
_id = f"{dial['id']}#{turn['id']}"
resp_turn_i += turn["do_inference"]
if (
_id in visited_ids
or not turn["do_inference"]
or "gen_resp" not in turn
):
pbar.update(1)
continue
cur_task_type = turn["id"].split("_")[1]
if prev_task_type != cur_task_type:
constraints = []
prev_task_type = cur_task_type
query = turn["inst"]
constraints.append(query)
resp = turn["gen_resp"]
word_count = len(resp.split())
sent_count = len(sent_tokenize(resp))
prompt = (
prompt_template.replace("{response}", resp)
.replace("{content}", doc)
.replace("{num_words}", str(word_count))
.replace("{num_sent}", str(sent_count))
.replace(
"{constraints}",
"\n".join(
[f"{i}. {c}" for i, c in enumerate(constraints, 1)]
),
)
)
resp, prompt_len, token_per_second = generate(
model_name=JUDGE_MODEL,
prompt=prompt,
temperature=TEMPERATURE,
max_tokens=MAX_NEW_TOKENS,
)
outputs.append({
"gen_resp": resp,
"from": filename,
"prompt": prompt,
"prompt_len": prompt_len,
"id": _id,
"turn": resp_turn_i,
"n_distract_turn": turn["n_distracts"],
})
n_evaluate += 1
pbar.update(1)
visited_ids.add(_id)
if len(outputs) % 10 == 0:
with open(out_filename, "w", encoding="utf-8") as f:
f.write(
"\n".join([
json.dumps(row, ensure_ascii=False)
for row in outputs
])
)
with open(out_filename, "w", encoding="utf-8") as f:
f.write(
"\n".join([json.dumps(row, ensure_ascii=False) for row in outputs])
)
pbar.refresh()
logger.info(
f"Evaluated {n_evaluate} instances in {task_name} for"
f" {model} . Output saved in {out_filename}."
)
def main(
model_name: str,
task_names: Union[
List[
Literal[
"refinement_single",
"refinement_multi",
"refinement_multi_gold",
"expansion_single",
"expansion_multi",
"expansion_multi_gold",
"follow-up_single",
"follow-up_multi",
"follow-up_multi_gold",
]
],
Literal["all"],
] = "all",
):
if task_names == "all":
task_names = TASK_NAMES
elif isinstance(task_names, str):
task_names = [task_names]
for task_name in task_names:
if task_name not in TASK_NAMES:
raise ValueError(
f"``{task_name}` does not require GPT-4 evaluation."
)
task_type, task_subtype = task_name.split("_", 1)
filename = os.path.join(
INFERENCE_OUTPUT, task_type, f"{task_subtype}_{model_name}.jsonl"
)
if not os.path.exists(filename):
continue
if task_name in ["refinement_multi", "refinement_multi_gold"]:
# GPT-4 Turn Evaluation Multi Inst
evaluate_refinement_multi(filename)
elif task_name == "refinement_single":
evaluate_refinement_single(
filename
) # GPT-4 Single Turn Evalaution
elif task_name in ["follow-up_multi", "follow-up_gold"]:
evaluate_follow_up_multi(filename) # MT-Bench-Autoregressive
elif task_name in ["follow-up_single"]:
evaluate_follow_up_single(filename) # MT-Bench-Single Evaluation
elif task_name in ["expansion_multi", "expansion_multi_gold"]:
evaluate_expansion(filename, "multi") # MT-Bench-Autoregressive
elif task_name in ["expansion_single"]:
evaluate_expansion(
filename, "single"
) # MT-Bench-Single Evaluation
elif "refinement_ablation_irrelevant" in task_name:
evaluate_refinement_ablation(filename)
if __name__ == "__main__":
StrictFire(main)