-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain.py
1232 lines (1091 loc) · 54.7 KB
/
train.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
import utils
from utils import prepare_dataset
from utils import split_data_into_TrainValTest
import utils.var as var
from utils.metric import outer_computer_metrics
import pandas as pd
import json
from scipy.special import softmax
from utils.utils import itemwise_avg_kappa
import os
import shutil
from datasets import Dataset
import datasets
from transformers import DataCollatorWithPadding
from transformers import Trainer
from model.dataset import IncontextDataset
from ExperimentLogger import ExperimentLogger as el
from model.ModelFactory import ModelFactory as mf
from transformers.utils import (
is_sagemaker_mp_enabled,
is_torch_tpu_available,
)
from collections import defaultdict
from model.dataset import rerange_data,rerange_examples
from model.examplesRetriever import KNNRetriever
if is_torch_tpu_available(check_device=False):
import torch_xla.core.xla_model as xm
import torch_xla.debug.metrics as met
import torch_xla.distributed.parallel_loader as pl
import math
import os
import random
import re
import shutil
import time
import warnings
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
from tqdm.auto import tqdm
skip_first_batches = None
import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, Dataset, RandomSampler, SequentialSampler
if is_sagemaker_mp_enabled():
import smdistributed.modelparallel.torch as smp
#from smdistributed.modelparallel import __version__ as SMP_VERSION
#IS_SAGEMAKER_MP_POST_1_10 = version.parse(SMP_VERSION) >= version.parse("1.10")
from transformers.trainer_pt_utils import smp_forward_backward, smp_forward_only, smp_gather, smp_nested_concat
else:
IS_SAGEMAKER_MP_POST_1_10 = False
from model.dataset import DataCollatorWithPadding
from transformers.debug_utils import DebugOption, DebugUnderflowOverflow
from transformers.modeling_utils import PreTrainedModel, load_sharded_checkpoint, unwrap_model
from transformers.models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, MODEL_MAPPING_NAMES
from transformers.trainer_pt_utils import (
IterableDatasetShard,
find_batch_size,
nested_concat,
nested_detach,
nested_numpify,
nested_truncate,
reissue_pt_warnings,
)
from transformers.trainer_utils import (
PREFIX_CHECKPOINT_DIR,
BestRun,
EvalLoopOutput,
EvalPrediction,
ShardedDDPOption,
denumpify_detensorize,
has_length,
speed_metrics,
)
from transformers.training_args import OptimizerNames, ParallelMode, TrainingArguments
from transformers.utils import (
is_sagemaker_mp_enabled,
is_torch_tpu_available,
logging,
)
logger = logging.get_logger(__name__)
# Name of the files used for checkpointing
TRAINING_ARGS_NAME = "training_args.bin"
TRAINER_STATE_NAME = "trainer_state.json"
OPTIMIZER_NAME = "optimizer.pt"
SCHEDULER_NAME = "scheduler.pt"
SCALER_NAME = "scaler.pt"
class MyTrainer(Trainer):
def __init__(self, args, device):
if 'saved_models' in args.lm:
#model_path = os.path.abspath(args.lm)
args.lm = os.path.abspath(args.lm)
self.extra_info = {'label2': [var.EVAL_LABEL, var.EST_SCORE]}
self.device = device
self.args = args
self.input_args = args
self.all_metrics = {}
# load question information
with open('question.json', 'r') as f:
question_info = json.load(f)
self.question_info = question_info
"""
1. Prepare label and model information
"""
training_dataset = pd.read_csv(args.train_path)
training_dataset = prepare_dataset(training_dataset, args)
if args.task != 'all':
if args.task not in var.QUESTION_LIST:
args.task = var.NAME_TO_QUESTION[args.task]
training_dataset = training_dataset[training_dataset['qid'] == args.task]
if args.fair_train:
if args.group != 'all':
args.feature_n = len(training_dataset[args.group].value_counts())
self.question2id = {value:i for i, value in enumerate(var.QUESTION_LIST)}
self.num_questions = len(self.question2id)
self.args.num_questions = self.num_questions
model, tokenizer = self.prepare_model(training_dataset)
"""
2. Prepare dataloader
"""
dataset_dict = self.prepare_dataloader(training_dataset)
"""
3. Initilized the trainer
"""
#3.1 set up trainner
data_collator = DataCollatorWithPadding(tokenizer= self.tokenizer)
#3.2 set up evaluation metrics
compute_metrics = outer_computer_metrics(args, id2label=self.id2label)
training_args = TrainingArguments(
output_dir=args.save_model_dir,
learning_rate=args.lr,
per_device_train_batch_size=args.batch_size,
per_device_eval_batch_size=args.batch_size,
num_train_epochs=args.iters,
weight_decay=args.decay,
evaluation_strategy="epoch",
#save_strategy="epoch",
save_strategy="epoch",
metric_for_best_model = args.best_metric,
load_best_model_at_end=True,
push_to_hub=False,
report_to="wandb",
seed=args.seed,
#remove_unused_columns = False,
)
super().__init__(
model=model,
args=training_args,
train_dataset=dataset_dict["train"],
eval_dataset=dataset_dict["val"],
tokenizer=tokenizer,
data_collator=data_collator,
compute_metrics=compute_metrics,
)
self.test_dataset = dataset_dict['test']
def prepare_model(self, training_dataset):
args = self.args
training_dataset['label'] = training_dataset['label'].astype(str)
labels = set(list(training_dataset['label']))
id2label = {}
id_count = 0
for elem in sorted(list(labels)):
id2label[id_count] = elem
id_count += 1
label2id = dict((v, k) for k, v in id2label.items())
num_label = len(labels)
self.id2label = id2label
self.label2id = label2id
if args.num_label:
num_label = args.num_label
self.num_label = num_label
(model, tokenizer) = mf.produce_model_and_tokenizer(args, num_label, id2label, label2id)
self.model = model
self.tokenizer = tokenizer
return model, tokenizer
def reload_new_model(self, args = None):
if args is None:
args = self.input_args
(model, tokenizer) = mf.produce_model_and_tokenizer(args, self.num_label, self.id2label, self.label2id)
self.model = model.to(self.device.type)
self.tokenizer = tokenizer
if args.retriever.name=='knn':
if args.retriever.same:
self.retriever.update_model(args, model=model,tokenizer=tokenizer,
pooling='bert', num_label=self.num_label, id2label=self.id2label,
label2id=self.label2id)
if not args.analysis:
self.retriever.create_examples_embedding(self.train_dataset.to_pandas())
return model, tokenizer
def prepare_dataloader(self, training_dataset):
"""
Prepare dataloader
"""
args = self.args
tokenizer = self.tokenizer
label_dict = self.label2id
def preprocess_function_base(examples):
# todo write own data collator that can take non-tensor input
result = tokenizer(examples["text"], truncation=True)
try:
label_ids = [label_dict[str(label)] for label in examples['label']]
except:
label_ids = [label_dict[str(int(label))] for label in examples['label']]
result['label_ids'] = label_ids
result['label_str'] = examples['label']
result['label'] = result['label_ids']
return result
def preprocess_function_in_context(examples):
if args.question_id:
temp = []
for x, y in zip(examples['text'], examples['qid']):
if y is None or y == '':
temp.append(x)
else:
temp.append(x + 'Question id: ' + y)
examples['text'] = temp
if args.closed_form:
temp = []
for x, y in zip(examples['text'], examples[var.CONTEXT_ALL]):
if y is None or y == '':
temp.append(x)
else:
temp.append(x + 'Closed form response: ' + y)
examples['text'] = temp
result = preprocess_function_base(examples)
return result
if args.base: # the basic classification problem
preprocess_function = preprocess_function_base
elif args.in_context:
preprocess_function = preprocess_function_in_context
if args.reduce:
train, val, test = split_data_into_TrainValTest(training_dataset, args=args)
iddf = pd.read_csv(args.reduce_path)
reduce_list = iddf['id'].tolist()
train = train[train['id'].isin(reduce_list)]
val = val[val['id'].isin(reduce_list)]
if len(val):
val = test
test = test[test['id'].isin(reduce_list)]
elif args.split:
train, val, test = split_data_into_TrainValTest(training_dataset, args = args)
elif args.eval_only:
train, val, test = split_data_into_TrainValTest(training_dataset, args=args)
#train = training_dataset
#val = prepare_dataset(pd.read_csv(args.test_path), args)
#test = val
else:
raise 'not define how to split the data'
if args.test_path:
test = pd.read_csv(args.test_path)
if 'fold' not in test.columns:
test['fold'] = 0
test['text1'], test['text2'], test['id'] = '', '', test['student_id']
test = prepare_dataset(test, args)
if args.task != 'all':
if args.task not in var.QUESTION_LIST:
args.task = var.NAME_TO_QUESTION[args.task]
test = test[test['qid'] == args.task]
rerange_data(train,args)
rerange_data(val, args)
rerange_data(test,args)
_, examples = rerange_examples(train)
if args.debug:
if args.prompting:
train = train.sample(n=50, replace=False)
test, val = train, train
elif args.analysis:
qdf_list = []
for key, qdf in list(train.groupby('qid')):
qdf = qdf.sample(n=1000, replace=False)
qdf_list.append(qdf)
train = pd.concat(qdf_list)
#val = val.sample(n=100, replace=False)
#test = test.sample(n=100, replace=False)
elif args.loop_eval:
train = train.sample(n=1000, replace=False)
test = test.sample(n=100, replace=False)
val = val.sample(n=100, replace=False)
else:
train = train.sample(n=1000, replace=False)
test, val = train, train
utils.safe_makedirs(args.save_model_dir)
#test.to_csv(args.save_model_dir + 'test.csv')
if args.retriever.name=='knn':
if args.retriever.same:
retriever = KNNRetriever(args, model=self.model, tokenizer=self.tokenizer,
pooling='bert', num_label=self.num_label, id2label=self.id2label,
label2id=self.label2id)
else:
retriever = KNNRetriever(args, num_label=self.num_label, id2label=self.id2label, label2id=self.label2id)
if not args.analysis:
retriever.create_examples_embedding(train)
elif args.same:
retriever = KNNRetriever(args, model = self.model,
pooling='bert', num_label=self.num_label, id2label=self.id2label, label2id=self.label2id)
else:
retriever = None
self.retriever = retriever
"""
Add question-wise dataset for testing
"""
question_wise_test = list(test.groupby('qid'))
if not args.examples or args.base:
question_wise_test = {key: Dataset.from_pandas(item) for key, item in question_wise_test}
train, val, test = Dataset.from_pandas(train), Dataset.from_pandas(val), Dataset.from_pandas(test)
dataset_dict = datasets.DatasetDict({'train': train, 'val': val, 'test': test})
dataset_dict.update(question_wise_test)
dataset_dict = dataset_dict.map(preprocess_function, batched=True)
self.dataset_dict = dataset_dict
else:
train_dataset = IncontextDataset(tokenizer=tokenizer, data=train, args=args,
labels_dict = self.label2id, question_dict = self.question2id, question_info=self.question_info)
val_dataset = IncontextDataset(tokenizer=tokenizer, data=val, args=args,
labels_dict = self.label2id, example=train,
question_dict = self.question2id, retriever=retriever, eval=True, question_info=self.question_info)
test_dataset = IncontextDataset(tokenizer=tokenizer, data=test,args=args,
labels_dict = self.label2id, example=train,
question_dict = self.question2id, retriever=retriever, eval=True, question_info=self.question_info)
self.dataset_dict = datasets.DatasetDict({'train': train_dataset, 'val': val_dataset, 'test': test_dataset})
# question_wise_test = {key: IncontextDataset(tokenizer=tokenizer, data=item, args=args,
# labels_dict = self.label2id, example=train[train['qid'] == key],
# question_dict = self.question2id) for key, item in question_wise_test}
# self.dataset_dict.update(question_wise_test)
if args.group_train:
def build_dataset(g_name, data, example, alias=''):
group_wise = list(data.groupby(g_name))
group_dataset = {f"{g_name}_{key}_{alias}": IncontextDataset(tokenizer=tokenizer, data=item, args=args,
labels_dict = self.label2id, example=example[example[g_name] == key],
question_dict = self.question2id) for key, item in group_wise}
return group_dataset
group_info = var.group_info
if args.group == 'all': group_list = list(group_info.keys())
else: group_list = [args.group]
self.group_list = group_list
for g_name in group_list:
test_group = build_dataset(g_name, test, train, 'test')
train_group = build_dataset(g_name, train, train, 'train')
val_group = build_dataset(g_name, val, train, 'val')
self.dataset_dict.update(test_group)
self.dataset_dict.update(train_group)
self.dataset_dict.update(val_group)
return self.dataset_dict
def save_best_model_and_remove_the_rest(self, alias=''):
"""
Save the best model to saved_models/test_name/best/~
Remove the rest of checkpoints saved models
"""
run_dir = self._get_output_dir(trial=None)
output_dir = os.path.join(run_dir, 'best'+alias)
self.save_model(output_dir, _internal_call=True)
dir_list = os.listdir(run_dir)
for directory in dir_list:
if directory.startswith("checkpoint"):
# Construct the full path to the directory and remove it
dir_path = os.path.join(run_dir, directory)
shutil.rmtree(dir_path)
def save_metrics(self, metrics, alias=''):
el.log(metrics)
path = os.path.join(self.args.output_dir + alias + 'metrics.json')
with open(path, "w") as f:
json.dump(metrics, f, indent=4, sort_keys=True)
q = pd.DataFrame.from_dict(self.question_info).T
q = q[['name','type']]
m = pd.DataFrame(metrics, index=[0]).T
#m = pd.DataFrame.from_dict(metrics).T
m = m.join(q)
m.to_csv(self.args.output_dir + alias + 'metrics.csv')
def predict_to_save(self, data:Dataset, alias=''):
"""
:param data: the data to evaluate
:return: the dataframe with an extra column named "predict"
"""
#todo need to check label 1
predicts = self.predict(data)
data_df = data.to_pandas()
predictions = predicts.predictions
if isinstance(predictions, tuple):
predictions = predictions[0]
pred = np.argmax(predictions, axis=1)
pred = list(map(lambda x: self.id2label[x], list(pred)))
if self.input_args.expectation:
distribution = softmax(predictions, axis=1)
if self.input_args.expectation:
expectation = np.sum(distribution * self.model.values.detach().cpu().numpy(), axis=1)
pred = list(map(round, expectation))
data_df['predict'] = pred
distribution = softmax(predictions, axis=1)
data_df['d'] = list(distribution)
all_metrics = self.itemwise_score(data_df)
data_df, metrics = itemwise_avg_kappa(data_df)
all_metrics.update(metrics)
data_df.to_csv(self.args.output_dir + alias + '_predict.csv',index=False)
self.save_metrics(all_metrics, alias)
self.save_metrics(self.all_metrics, 'epoch')
return data_df
def prompting_predict_to_save(self, data, alias=''):
prompting_path = 'conf/prompting.txt'
score_list = ['1', '1A', '1B', '2', '2A', '2B', '3']
#todo need to write in parallel way to save time
def generate_completion(prompt, model, tokenizer, device):
inputs = tokenizer.encode(prompt, return_tensors='pt').to(device)
input_length = inputs.size()[1]
output = model.generate(inputs, max_length=input_length + 50, num_return_sequences=1, do_sample=True)
completion = tokenizer.decode(output[:, input_length:][0], skip_special_tokens=True)
return completion
def extract_information(string, pattern):
#pattern = rf"<{pattern}>(.*?)</{pattern}>"
#match = re.search(pattern, string)
#if match:
# return match.group(1)
string = string.split("<" +pattern + ">")[1]
string = string.split("</" + pattern + ">")[0]
return string
def extrat_score_out(string):
for s in score_list:
if s in string:
return s
return '1'
id2simplelabel = {k: int(re.sub(r"\D", "", k)) for k in score_list}
# dataloader = self.get_test_dataloader(data)
# for step, inputs in enumerate(dataloader):
with open(prompting_path, 'r') as file:
prompts = file.read()
data_df = data.to_pandas()
predict = []
full_predict = []
for qid, qdf in tqdm(list(data_df.groupby('qid')), position=0):
prompt = extract_information(prompts, qid)
for text in tqdm(zip(qdf['text1'].values.tolist(), qdf['text2'].values.tolist()), total=len(qdf), position=0):
text1, text2 = text
prompt = prompt.replace('TEXT1', text1)
prompt = prompt.replace('TEXT2', text2)
result = generate_completion(prompt, self.model, self.tokenizer, self.device)
score = extrat_score_out(result)
full_predict.append(result)
predict.append(score)
data_df['predict'] = predict
data_df['full_predict'] = full_predict
#calculate itemwise information
data_df = data_df[['id', 'qid', 'text', 'predict', 'label_str','full_predict']]
data_df.to_csv(self.args.output_dir + alias + 'test_predict.csv')
preds = np.array(list(map(lambda x: id2simplelabel[x], predict)))
labels = np.array(list(map(lambda x: id2simplelabel[x], data_df['label_str'].values.tolist())))
metrics = self.compute_metrics(EvalPrediction(predictions=preds, label_ids=labels))
metrics = denumpify_detensorize(metrics)
self.log(metrics)
self.save_metrics(metrics, alias)
def loop_eval(self, data, alias):
args, num_label, id2label, label2id = self.input_args, self.num_label, self.id2label, self.label2id
run_dir = self.input_args.loop_eval
dir_list = os.listdir(run_dir)
all_metrics = {}
for i, directory in enumerate(dir_list):
if 'checkpoint' in directory:
epoch = re.sub(r"\D", "", directory)
elif 'best' in directory:
epoch = ''
else:
continue
i = epoch
self.input_args.lm = run_dir + directory
#(model, tokenizer) = mf.produce_model_and_tokenizer(args, num_label, id2label, label2id)
#self.model = model.to(self.device.type)
self.reload_new_model(args)
predicts = self.predict(data)
data_df = data.to_pandas()
predictions = predicts.predictions
if isinstance(predictions, tuple):
predictions = predictions[0]
pred = np.argmax(predictions, axis=1)
pred = list(map(lambda x: self.id2label[x], list(pred)))
if args.expectation:
distribution = softmax(predictions,axis=1)
if self.input_args.expectation:
expectation = np.sum(distribution * self.model.values.detach().cpu().numpy(), axis=1)
pred = list(map(round,expectation))
if args.save_logit:
distribution = np.around(softmax(predictions,axis=1),3)
data_df['d' + epoch] = list(distribution)
# data_df['regression_predict' + str(i)]= list(np.sum(distribution * self.model.values.detach().cpu().numpy(), axis=1))
data_df['predict' + str(i)] = pred
temp = self.itemwise_score(data_df, epoch=str(i))
all_metrics[i] = temp
self.log(temp)
print(temp)
#data_df, metrics = itemwise_avg_kappa(data_df, epoch=str(i))
#all_metrics[i].update(metrics)
data_df, metrics = itemwise_avg_kappa(data_df)
self.save_metrics(all_metrics, alias)
data_df.to_csv(run_dir + alias + '_predict.csv', index=False)
def group_train(self):
group_list = self.group_list
group_info = var.group_info
vals= []
tests = []
for g_name in group_list:
for group_i in group_info[g_name]:
self.reload_new_model()
train = self.dataset_dict[f'{g_name}_{group_i}_train']
val = self.dataset_dict[f'{g_name}_{group_i}_val']
test = self.dataset_dict[f'{g_name}_{group_i}_test']
self.train_dataset = train
self.eval_dataset = val
self.test_dataset = test
self.train()
self.save_best_model_and_remove_the_rest(alias=f'{g_name}_{group_i}')
val, test = val.to_pandas(), test.to_pandas()
val['type'] = f"{g_name}_{group_i}"
val[g_name]=group_i
test['type'] = f"{g_name}_{group_i}"
test[g_name] = group_i
vals.append(val)
tests.append(test)
vals = pd.concat(vals)
tests = pd.concat(tests)
vals.to_csv(self.args.output_dir + '/val_predict.csv', index=False)
tests.to_csv(self.args.output_dir + '/test_predict.csv', index=False)
#aggregate all result
def itemwise_score(self, data_df, prefix = '', epoch = ''):
try:
epoch = str(int(self.state.epoch))
except:
pass
all_metrics = {}
for qid, qdf in list(data_df.groupby('qid')):
qdf['predict'+epoch] = qdf['predict'+epoch].astype('int')
qdf['label'] = qdf['label'].astype('int')
preds = np.array(qdf['predict'+epoch].values.tolist())
labels = np.array(qdf['label'].values.tolist())
if self.input_args.label == 2:
other = {}
other[var.EVAL_LABEL] = np.array(qdf[var.EVAL_LABEL].values.tolist())
other[var.EST_SCORE] = np.array(qdf[var.EST_SCORE].values.tolist())
metrics = self.compute_metrics(EvalPrediction(predictions=preds, label_ids=labels, inputs= other), id=False)
else:
metrics = self.compute_metrics(EvalPrediction(predictions=preds, label_ids=labels))
metrics = denumpify_detensorize(metrics)
qid = var.QUESTION_TO_NAME[qid]
all_score = defaultdict(int)
#prefix += epoch
for key in list(metrics.keys()):
if not key.startswith(f"{qid}_"):
value = metrics.pop(key)
if prefix !='':
#metrics[f"{epoch}_{prefix}_{qid}_{key}"] = value
metrics[f"{prefix}_{qid}_{key}"] = value
all_score[f"{prefix}_{key}"] += value
else:
#metrics[f"{epoch}_{qid}_{key}"] = value
metrics[f"{qid}_{key}"] = value
all_score[f"{key}"] += value
all_metrics.update(metrics)
all_metrics.update(all_score)
return all_metrics
def compute_loss(self, model, inputs, return_outputs=False):
"""
How the loss is computed by Trainer. By default, all models return the loss in the first element.
Subclass and override for custom behavior.
"""
if self.label_smoother is not None and "labels" in inputs:
labels = inputs.pop("labels")
else:
labels = None
if self.input_args.label == 2:
others = {}
for key in self.extra_info['label2']:
others.update({key:inputs.pop(key)})
outputs = model(**inputs)
if self.args.past_index >= 0:
self._past = outputs[self.args.past_index]
if labels is not None:
if unwrap_model(model)._get_name() in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES.values():
loss = self.label_smoother(outputs, labels, shift_labels=True)
else:
loss = self.label_smoother(outputs, labels)
else:
if isinstance(outputs, dict) and "loss" not in outputs:
raise ValueError(
"The model did not return a loss from the inputs, only the following keys: "
f"{','.join(outputs.keys())}. For reference, the inputs it received are {','.join(inputs.keys())}."
)
# We don't use .loss here since the model may return tuples instead of ModelOutput.
loss = outputs["loss"] if isinstance(outputs, dict) else outputs[0]
if self.input_args.label == 2:
outputs = (outputs, others)
return (loss, outputs) if return_outputs else loss
def prediction_step(
self,
model: nn.Module,
inputs: Dict[str, Union[torch.Tensor, Any]],
prediction_loss_only: bool,
ignore_keys: Optional[List[str]] = None,
) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]:
"""
Perform an evaluation step on `model` using `inputs`.
Subclass and override to inject custom behavior.
Args:
model (`nn.Module`):
The model to evaluate.
inputs (`Dict[str, Union[torch.Tensor, Any]]`):
The inputs and targets of the model.
The dictionary will be unpacked before being fed to the model. Most models expect the targets under the
argument `labels`. Check your model's documentation for all accepted arguments.
prediction_loss_only (`bool`):
Whether or not to return the loss only.
ignore_keys (`Lst[str]`, *optional*):
A list of keys in the output of your model (if it is a dictionary) that should be ignored when
gathering predictions.
Return:
Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]: A tuple with the loss,
logits and labels (each being optional).
"""
has_labels = False if len(self.label_names) == 0 else all(inputs.get(k) is not None for k in self.label_names)
# For CLIP-like models capable of returning loss values.
# If `return_loss` is not specified or being `None` in `inputs`, we check if the default value of `return_loss`
# is `True` in `model.forward`.
return_loss = inputs.get("return_loss", None)
other_info = None
if return_loss is None:
return_loss = self.can_return_loss
loss_without_labels = True if len(self.label_names) == 0 and return_loss else False
inputs = self._prepare_inputs(inputs)
if ignore_keys is None:
if hasattr(self.model, "config"):
ignore_keys = getattr(self.model.config, "keys_to_ignore_at_inference", [])
else:
ignore_keys = []
# labels may be popped when computing the loss (label smoothing for instance) so we grab them first.
if has_labels or loss_without_labels:
labels = nested_detach(tuple(inputs.get(name) for name in self.label_names))
if len(labels) == 1:
labels = labels[0]
else:
labels = None
with torch.no_grad():
if is_sagemaker_mp_enabled():
raw_outputs = smp_forward_only(model, inputs)
if has_labels or loss_without_labels:
if isinstance(raw_outputs, dict):
loss_mb = raw_outputs["loss"]
logits_mb = tuple(v for k, v in raw_outputs.items() if k not in ignore_keys + ["loss"])
else:
loss_mb = raw_outputs[0]
logits_mb = raw_outputs[1:]
loss = loss_mb.reduce_mean().detach().cpu()
logits = smp_nested_concat(logits_mb)
else:
loss = None
if isinstance(raw_outputs, dict):
logits_mb = tuple(v for k, v in raw_outputs.items() if k not in ignore_keys)
else:
logits_mb = raw_outputs
logits = smp_nested_concat(logits_mb)
else:
if has_labels or loss_without_labels:
with self.compute_loss_context_manager():
loss, outputs = self.compute_loss(model, inputs, return_outputs=True)
loss = loss.mean().detach()
if self.input_args.label==2:
other_info = outputs[1]
outputs = outputs[0]
if isinstance(outputs, dict):
#logits = tuple(v for k, v in outputs.items() if k not in ignore_keys + ["loss"])
logits = outputs['logits']
else:
logits = outputs[1:]
else:
loss = None
with self.compute_loss_context_manager():
outputs = model(**inputs)
if isinstance(outputs, dict):
logits = tuple(v for k, v in outputs.items() if k not in ignore_keys)
else:
logits = outputs
if self.args.past_index >= 0:
self._past = outputs[self.args.past_index - 1]
if prediction_loss_only:
return (loss, None, None)
logits = nested_detach(logits)
if len(logits) == 1:
logits = logits[0]
return (loss, logits, labels, other_info)
def evaluation_loop(
self,
dataloader,
description: str,
prediction_loss_only: Optional[bool] = None,
ignore_keys: Optional[List[str]] = None,
metric_key_prefix: str = "eval",
) -> EvalLoopOutput:
"""
Prediction/evaluation loop, shared by `Trainer.evaluate()` and `Trainer.predict()`.
Works both with or without labels.
"""
args = self.args
prediction_loss_only = prediction_loss_only if prediction_loss_only is not None else args.prediction_loss_only
model = self._wrap_model(self.model, training=False, dataloader=dataloader)
# if full fp16 or bf16 eval is wanted and this ``evaluation`` or ``predict`` isn't called
# while ``train`` is running, cast it to the right dtype first and then put on device
if not self.is_in_train:
if args.fp16_full_eval:
model = model.to(dtype=torch.float16, device=args.device)
elif args.bf16_full_eval:
model = model.to(dtype=torch.bfloat16, device=args.device)
batch_size = self.args.eval_batch_size
logger.info(f"***** Running {description} *****")
if has_length(dataloader):
logger.info(f" Num examples = {self.num_examples(dataloader)}")
else:
logger.info(" Num examples: Unknown")
logger.info(f" Batch size = {batch_size}")
model.eval()
self.callback_handler.eval_dataloader = dataloader
# Do this before wrapping.
eval_dataset = getattr(dataloader, "dataset", None)
if is_torch_tpu_available():
dataloader = pl.ParallelLoader(dataloader, [args.device]).per_device_loader(args.device)
if args.past_index >= 0:
self._past = None
# Initialize containers
# losses/preds/labels on GPU/TPU (accumulated for eval_accumulation_steps)
losses_host = None
preds_host = None
labels_host = None
inputs_host = None
# losses/preds/labels on CPU (final containers)
all_losses = None
all_preds = None
all_labels = None
all_inputs = None
other_hosts = defaultdict(lambda : None)
# Will be useful when we have an iterable dataset so don't know its length.
observed_num_examples = 0
# Main evaluation loop
for step, inputs in enumerate(dataloader):
# Update the observed num examples
observed_batch_size = find_batch_size(inputs)
if observed_batch_size is not None:
observed_num_examples += observed_batch_size
# For batch samplers, batch_size is not known by the dataloader in advance.
if batch_size is None:
batch_size = observed_batch_size
# Prediction step
loss, logits, labels, other_info = self.prediction_step(model, inputs, prediction_loss_only, ignore_keys=ignore_keys)
if len(labels) == 1:
logits = logits.unsqueeze(1).T
inputs_decode = self._prepare_input(inputs["input_ids"]) if args.include_inputs_for_metrics else None
if is_torch_tpu_available():
xm.mark_step()
# Update containers on host
if loss is not None:
losses = self._nested_gather(loss.repeat(batch_size))
losses_host = losses if losses_host is None else torch.cat((losses_host, losses), dim=0)
if labels is not None:
labels = self._pad_across_processes(labels)
labels = self._nested_gather(labels)
labels_host = labels if labels_host is None else nested_concat(labels_host, labels, padding_index=-100)
if inputs_decode is not None:
inputs_decode = self._pad_across_processes(inputs_decode)
inputs_decode = self._nested_gather(inputs_decode)
inputs_host = (
inputs_decode
if inputs_host is None
else nested_concat(inputs_host, inputs_decode, padding_index=-100)
)
if logits is not None:
logits = self._pad_across_processes(logits)
logits = self._nested_gather(logits)
if self.preprocess_logits_for_metrics is not None:
logits = self.preprocess_logits_for_metrics(logits, labels)
preds_host = logits if preds_host is None else nested_concat(preds_host, logits, padding_index=-100)
if other_info is not None:
for key, value in other_info.items():
value = self._pad_across_processes(value)
value = self._nested_gather(value)
other_hosts[key] = value if other_hosts[key] is None else nested_concat(other_hosts[key], value,
padding_index=-100)
self.control = self.callback_handler.on_prediction_step(args, self.state, self.control)
# Gather all tensors and put them back on the CPU if we have done enough accumulation steps.
if args.eval_accumulation_steps is not None and (step + 1) % args.eval_accumulation_steps == 0:
if losses_host is not None:
losses = nested_numpify(losses_host)
all_losses = losses if all_losses is None else np.concatenate((all_losses, losses), axis=0)
if preds_host is not None:
logits = nested_numpify(preds_host)
all_preds = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-100)
if inputs_host is not None:
inputs_decode = nested_numpify(inputs_host)
all_inputs = (
inputs_decode
if all_inputs is None
else nested_concat(all_inputs, inputs_decode, padding_index=-100)
)
if labels_host is not None:
labels = nested_numpify(labels_host)
all_labels = (
labels if all_labels is None else nested_concat(all_labels, labels, padding_index=-100)
)
# Set back to None to begin a new accumulation
losses_host, preds_host, inputs_host, labels_host = None, None, None, None
if args.past_index and hasattr(self, "_past"):
# Clean the state at the end of the evaluation loop
delattr(self, "_past")
# Gather all remaining tensors and put them back on the CPU
if losses_host is not None:
losses = nested_numpify(losses_host)
all_losses = losses if all_losses is None else np.concatenate((all_losses, losses), axis=0)
if preds_host is not None:
logits = nested_numpify(preds_host)
all_preds = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-100)
if inputs_host is not None:
inputs_decode = nested_numpify(inputs_host)
all_inputs = (
inputs_decode if all_inputs is None else nested_concat(all_inputs, inputs_decode, padding_index=-100)
)
if labels_host is not None:
labels = nested_numpify(labels_host)
all_labels = labels if all_labels is None else nested_concat(all_labels, labels, padding_index=-100)
all_others = defaultdict(lambda: None)
if len(other_hosts) != 0:
for key, value in other_hosts.items():
other = nested_numpify(other_hosts[key])
all_others[key] = other if all_others[key] is None else np.concatenate(all_others[key], other, padding_index=-100)
# Number of samples
if has_length(eval_dataset):
num_samples = len(eval_dataset)
# The instance check is weird and does not actually check for the type, but whether the dataset has the right
# methods. Therefore we need to make sure it also has the attribute.
elif isinstance(eval_dataset, IterableDatasetShard) and getattr(eval_dataset, "num_examples", 0) > 0:
num_samples = eval_dataset.num_examples
else:
if has_length(dataloader):
num_samples = self.num_examples(dataloader)
else: # both len(dataloader.dataset) and len(dataloader) fail
num_samples = observed_num_examples
if num_samples == 0 and observed_num_examples > 0:
num_samples = observed_num_examples
# Number of losses has been rounded to a multiple of batch_size and in a distributed training, the number of
# samplers has been rounded to a multiple of batch_size, so we truncate.
if all_losses is not None:
all_losses = all_losses[:num_samples]
if all_preds is not None:
all_preds = nested_truncate(all_preds, num_samples)
if all_labels is not None:
all_labels = nested_truncate(all_labels, num_samples)
if all_inputs is not None:
all_inputs = nested_truncate(all_inputs, num_samples)
if len(all_others) != 0:
for key, value in all_others.items():
all_others[key] = nested_truncate(value, num_samples)
# Metrics!
if self.compute_metrics is not None and all_preds is not None and all_labels is not None:
if args.include_inputs_for_metrics:
metrics = self.compute_metrics(
EvalPrediction(predictions=all_preds, label_ids=all_labels, inputs=all_inputs)
)
else:
if self.input_args.label == 2:
metrics = self.compute_metrics(EvalPrediction(predictions=all_preds,
label_ids=all_labels, inputs=all_others))
else:
metrics = self.compute_metrics(EvalPrediction(predictions=all_preds, label_ids=all_labels))
else:
metrics = {}
# To be JSON-serializable, we need to remove numpy types or zero-d tensors
metrics = denumpify_detensorize(metrics)
if all_losses is not None:
metrics[f"{metric_key_prefix}_loss"] = all_losses.mean().item()
if hasattr(self, "jit_compilation_time"):
metrics[f"{metric_key_prefix}_jit_compilation_time"] = self.jit_compilation_time
# Prefix all keys with metric_key_prefix + '_'
for key in list(metrics.keys()):
if not key.startswith(f"{metric_key_prefix}_"):
metrics[f"{metric_key_prefix}_{key}"] = metrics.pop(key)
return EvalLoopOutput(predictions=all_preds, label_ids=all_labels, metrics=metrics, num_samples=num_samples)
def _maybe_log_save_evaluate(self, tr_loss, model, trial, epoch, ignore_keys_for_eval):
if self.control.should_log:
if is_torch_tpu_available():
xm.mark_step()
logs: Dict[str, float] = {}
# all_gather + mean() to get average loss over all processes
tr_loss_scalar = self._nested_gather(tr_loss).mean().item()
# reset tr_loss to zero
tr_loss -= tr_loss
logs["loss"] = round(tr_loss_scalar / (self.state.global_step - self._globalstep_last_logged), 4)
logs["learning_rate"] = self._get_learning_rate()
self._total_loss_scalar += tr_loss_scalar
self._globalstep_last_logged = self.state.global_step
self.store_flos()
self.log(logs)
metrics = None
if self.control.should_evaluate:
if isinstance(self.eval_dataset, dict):
for eval_dataset_name, eval_dataset in self.eval_dataset.items():
metrics = self.evaluate(
eval_dataset=eval_dataset,
ignore_keys=ignore_keys_for_eval,
metric_key_prefix=f"eval_{eval_dataset_name}",