-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbert_reranker.py
1035 lines (862 loc) · 42.8 KB
/
bert_reranker.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
# -*- coding: utf-8 -*-
"""bert_reranker_yield.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1Ef6bVuyVC6aUEFbKG597NF_NC5wVvMNA
"""
#!pip install transformers==2.2.1
#!pip install tensorboardX
#!pip install pandas
from __future__ import absolute_import, division, print_function
import argparse
import glob
import logging
import os
import random
import pickle
import re
import numpy as np
import pandas as pd
import torch
from torch.utils.data import (DataLoader, RandomSampler, WeightedRandomSampler, SequentialSampler,
TensorDataset)
from torch.utils.data.distributed import DistributedSampler
from tensorboardX import SummaryWriter
from tqdm import tqdm, trange
import sys
from transformers import (WEIGHTS_NAME, BertConfig,
BertForSequenceClassification, BertTokenizer,
XLMConfig, XLMForSequenceClassification,
XLMTokenizer, XLNetConfig,
XLNetForSequenceClassification,
XLNetTokenizer)
from transformers import AdamW, get_linear_schedule_with_warmup
logger = logging.getLogger(__name__)
ALL_MODELS = sum((tuple(conf.pretrained_config_archive_map.keys()) for conf in (BertConfig, XLNetConfig, XLMConfig)), ())
MODEL_CLASSES = {
'bert': (BertConfig, BertForSequenceClassification, BertTokenizer),
'xlnet': (XLNetConfig, XLNetForSequenceClassification, XLNetTokenizer),
'xlm': (XLMConfig, XLMForSequenceClassification, XLMTokenizer),
}
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
def compute_AP(sorted_labels):
num_hits = 0.0
ap = 0.0
if np.sum(sorted_labels) == 0:
return 0.0
for i, ll in enumerate(sorted_labels):
if ll == 0:
continue
num_hits += 1
ap += num_hits / (i + 1)
return ap / np.sum(sorted_labels)
def compute_metrics(examples, preds, labels):
logit_1 = preds[:, 1] - preds[:, 0]
#print("logits diff: ",logit_1)
acc = (np.argmax(preds, axis=1) == labels).mean()
print("accuracy: ",acc)
print(len(examples),len(preds),len(labels))
idx_start = 0
prev_query = examples[0].text_a
ap_list = []
predictions = []
for i, example in enumerate(examples):
#print("processing example: ",i, example.text_a,prev_query)
if example.text_a == prev_query:
continue
relevant_logits = logit_1[idx_start:i]
relevant_labels = labels[idx_start:i]
relevant_examples = examples[idx_start:i]
#print(relevant_logits,relevant_labels,relevant_examples)
sorted_preds, sorted_labels, sorted_examples = zip(*sorted(zip(relevant_logits, relevant_labels,relevant_examples), key=lambda e: e[0],reverse=True))
predictions.extend([se.guid for se in sorted_examples])
# assert(len(sorted_labels) == 4950)
ap_list.append(compute_AP(sorted_labels))
prev_query = example.text_a
idx_start = i
relevant_logits = logit_1[idx_start:]
relevant_labels = labels[idx_start:]
relevant_examples = examples[idx_start:]
sorted_preds, sorted_labels, sorted_examples = zip(*sorted(zip(relevant_logits, relevant_labels, relevant_examples),key=lambda e: e[0], reverse=True))
predictions.extend([se.guid for se in sorted_examples])
# assert (len(sorted_labels) == 4950)
ap_list.append(compute_AP(sorted_labels))
return {"acc": acc, "map": np.mean(ap_list)}, predictions
class InputExample(object):
"""A single training/test example for simple sequence classification."""
def __init__(self, guid, text_a, text_b=None, label=None):
"""Constructs a InputExample.
Args:
guid: Unique id for the example.
text_a: string. The untokenized text of the first sequence. For single
sequence tasks, only this sequence must be specified.
text_b: (Optional) string. The untokenized text of the second sequence.
Only must be specified for sequence pair tasks.
label: (Optional) string. The label of the example. This should be
specified for train and dev examples, but not for test examples.
"""
self.guid = guid
self.text_a = text_a
self.text_b = text_b
self.label = label
class InputFeatures(object):
"""A single set of features of data."""
def __init__(self, input_ids, input_mask, segment_ids, label_id):
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.label_id = label_id
# String used to indicate a blank
BLANK_STR = "___"
# Create a hypothesis statement from the the input fill-in-the-blank statement and answer choice.
def create_hypothesis(fitb, choice):
if ". " + BLANK_STR in fitb or fitb.startswith(BLANK_STR):
choice = choice[0].upper() + choice[1:]
else:
choice = choice.lower()
if not fitb.endswith(BLANK_STR):
choice = choice.rstrip(".")
hypothesis = re.sub("__+", choice.strip(), fitb)
return hypothesis
# Identify the wh-word in the question and replace with a blank
def replace_wh_word_with_blank(question_str):
wh_word_offset_matches = []
wh_words = ["which", "what", "where", "when", "how", "who", "why"]
for wh in wh_words:
m = re.search(wh + "\?[^\.]*[\. ]*$", question_str.lower())
if m:
wh_word_offset_matches = [(wh, m.start())]
break
else:
m = re.search(wh + "[ ,][^\.]*[\. ]*$", question_str.lower())
if m:
wh_word_offset_matches.append((wh, m.start()))
if len(wh_word_offset_matches):
wh_word_offset_matches.sort(key=lambda x: x[1])
wh_word_found = wh_word_offset_matches[0][0]
wh_word_start_offset = wh_word_offset_matches[0][1]
question_str = re.sub("\?$", ".", question_str.strip())
fitb_question = (question_str[:wh_word_start_offset] + BLANK_STR +
question_str[wh_word_start_offset + len(wh_word_found):])
return fitb_question.replace(BLANK_STR + " of the following", BLANK_STR)
elif re.match(".*[^\.\?] *$", question_str):
return question_str + " " + BLANK_STR
else:
return re.sub(" this[ \?]", " ___ ", question_str)
def get_fitb_from_question(question_text):
fitb = replace_wh_word_with_blank(question_text)
if not re.match(".*_+.*", fitb):
print("Can't create hypothesis from: '{}'. Appending {} !".format(question_text, BLANK_STR))
fitb = re.sub("[\.\? ]*$", "", question_text.strip()) + BLANK_STR
return fitb
class TG2019RerankProcessor:
def get_train_examples(self, args):
"""Gets a collection of `InputExample`s for the train set."""
df_questions = pd.read_csv(args.train_questions_file, sep='\t').dropna(subset=["explanation"]).reset_index()
return self._create_examples(df_questions, args.mcq_choices, args.facts_file)
def get_dev_examples(self, args):
"""Gets a collection of `InputExample`s for the dev set."""
df_questions = pd.read_csv(args.dev_questions_file, sep='\t').dropna(subset=["explanation"]).reset_index()
return self._create_examples(df_questions, args.mcq_choices, args.facts_file)
def get_test_examples(self, args):
"""Gets a collection of `InputExample`s for the test set."""
df_questions = pd.read_csv(args.test_questions_file, sep='\t')
df_questions = df_questions[df_questions['flags'].str.lower().isin(('success', 'ready'))]
return self._create_examples(df_questions, args.mcq_choices, args.facts_file)
def get_labels(self):
"""Gets the list of labels for this data set."""
return ["0", "1"]
def _create_examples(self, df_questions, mcq_choices, facts_file):
# Remove wrong choices
def remove_wrong_answer_choices(row, choices):
delimiters="(A)","(B)","(C)","(D)","(E)","(1)","(2)","(3)","(4)"
regexPattern = '|'.join(map(re.escape, delimiters))
ques=row['question']
qa=re.split(regexPattern, ques)
#print(qa)
ans=row['AnswerKey']
#print(qa)
if ans=="A" or ans=="1":
ch=qa[1]
elif ans=="B" or ans=="2":
ch=qa[2]
elif ans=="C" or ans=="3":
ch=qa[3]
elif ans=="D" or ans=="4":
ch=qa[4]
else:
ch=qa[5]
fitb_q=get_fitb_from_question(qa[0])
processed_q=create_hypothesis(fitb_q,ch)
return processed_q
if mcq_choices != "all":
df_questions["ProcessedQuestion"] = df_questions.apply(remove_wrong_answer_choices, 1,
choices=mcq_choices)
else:
df_questions["ProcessedQuestion"] = df_questions["question"]
#for q in df_questions["ProcessedQuestion"]:
# print(q)
df_facts = pd.read_csv(facts_file, sep='\t', index_col="uid")
examples = []
for i_q, question in df_questions.iterrows():
if i_q % 10 ==0:
print(i_q)
qid = question["QuestionID"]
explanations = [e.split('|')[0] for e in question["explanation"].split(' ')]
for uid, fact in df_facts.iterrows():
guid = '###'.join([qid, uid])
examples.append(InputExample(guid=guid, text_a=question["ProcessedQuestion"], text_b=fact["text"],
label="1" if uid in explanations else "0"))
return examples
def _truncate_seq_pair(tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer sequence
# one token at a time. This makes more sense than truncating an equal percent
# of tokens from each, since if one sequence is very short then each token
# that's truncated likely contains more information than a longer sequence.
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_length:
break
if len(tokens_a) > len(tokens_b):
tokens_a.pop()
else:
tokens_b.pop()
def check_sampling_index(num_samples,examples):
label_list=["0", "1"]
label_map = {label: i for i, label in enumerate(label_list)}
count=0
li=[]
print('creating label array...')
for example in examples:
label_id = label_map[example.label]
if(label_id)==0 and count<=10000000:
li.append(label_id)
count+=1
elif (label_id)==0 and count>10000000:
continue
else:
li.append(label_id)
print("number of examples being used: ",len(li))
label_array = np.asarray(li, dtype=np.int32)
class_pos=np.sum(label_array==1)
class_neg=np.sum(label_array==0)
print('number of samples in both classes:')
print(class_pos,class_neg)
sampler_weights = np.zeros(len(label_array))
label_map = {label:i for i, label in enumerate(label_list)}
#print(label_map)
for label in label_list:
sampler_weights[label_array == label_map[label]] = 1. / np.mean(label_array == label_map[label])
#print(sampler_weights)
print("sampler weightes created..")
train_sampler = WeightedRandomSampler(sampler_weights, num_samples=num_samples, replacement= False)
sampling_indices=list(train_sampler)
print("sampler indices created...")
with open('sampled_indices.pkl','wb') as wr:
pickle.dump(sampling_indices,wr)
return set(sampling_indices)
def get_sampled_indices():
with open('sampled_indices.pkl','rb') as wr:
indices=pickle.load(wr)
return set(indices)
def convert_examples_to_features(filename,batch_size,examples, label_list, max_seq_length,
tokenizer, output_mode,
cls_token_at_end=False, pad_on_left=False,
cls_token='[CLS]', sep_token='[SEP]', pad_token=0,
sequence_a_segment_id=0, sequence_b_segment_id=1,
cls_token_segment_id=1, pad_token_segment_id=0,
mask_padding_with_zero=True):
""" Loads a data file into a list of `InputBatch`s
`cls_token_at_end` define the location of the CLS token:
- False (Default, BERT/XLM pattern): [CLS] + A + [SEP] + B + [SEP]
- True (XLNet/GPT pattern): A + [SEP] + B + [SEP] + [CLS]
`cls_token_segment_id` define the segment id associated to the CLS token (0 for BERT, 2 for XLNet)
"""
if "train" in filename:
total_samples_to_generate=500000
if (os.path.exists('sampled_indices.pkl')):
sampling_indices=get_sampled_indices()
else:
sampling_indices=check_sampling_index(total_samples_to_generate,examples)
label_map = {label: i for i, label in enumerate(label_list)}
print("number of examples to be processed: ",len(examples))
# with open(filename,'ab') as p:
for (ex_index, example) in enumerate(examples):
#feat=[]
dict={}
if "train" in filename:
if ex_index not in sampling_indices:
continue
if ex_index % 50000 == 0:
logger.info("Writing example %d of %d" % (ex_index, len(examples)))
tokens_a = tokenizer.tokenize(example.text_a)
tokens_b = None
if example.text_b:
tokens_b = tokenizer.tokenize(example.text_b)
# Modifies `tokens_a` and `tokens_b` in place so that the total
# length is less than the specified length.
# Account for [CLS], [SEP], [SEP] with "- 3"
_truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)
else:
# Account for [CLS] and [SEP] with "- 2"
if len(tokens_a) > max_seq_length - 2:
tokens_a = tokens_a[:(max_seq_length - 2)]
tokens = tokens_a + [sep_token]
segment_ids = [sequence_a_segment_id] * len(tokens)
if tokens_b:
tokens += tokens_b + [sep_token]
segment_ids += [sequence_b_segment_id] * (len(tokens_b) + 1)
if cls_token_at_end:
tokens = tokens + [cls_token]
segment_ids = segment_ids + [cls_token_segment_id]
else:
tokens = [cls_token] + tokens
segment_ids = [cls_token_segment_id] + segment_ids
input_ids = tokenizer.convert_tokens_to_ids(tokens)
# The mask has 1 for real tokens and 0 for padding tokens. Only real
# tokens are attended to.
input_mask = [1 if mask_padding_with_zero else 0] * len(input_ids)
# Zero-pad up to the sequence length.
padding_length = max_seq_length - len(input_ids)
if pad_on_left:
input_ids = ([pad_token] * padding_length) + input_ids
input_mask = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask
segment_ids = ([pad_token_segment_id] * padding_length) + segment_ids
else:
input_ids = input_ids + ([pad_token] * padding_length)
input_mask = input_mask + ([0 if mask_padding_with_zero else 1] * padding_length)
segment_ids = segment_ids + ([pad_token_segment_id] * padding_length)
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
if output_mode == "classification":
label_id = label_map[example.label]
elif output_mode == "regression":
label_id = float(example.label)
else:
raise KeyError(output_mode)
if ex_index < 5:
logger.info("*** Example ***")
logger.info("guid: %s" % (example.guid))
logger.info("tokens: %s" % " ".join(
[str(x) for x in tokens]))
logger.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
logger.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
logger.info("segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
logger.info("label: %s (id = %d)" % (example.label, label_id))
#feat.append(InputFeatures(input_ids=input_ids,input_mask=input_mask,segment_ids=segment_ids,label_id=label_id))
dict['input_ids']= input_ids
dict['input_mask']=input_mask
dict['segment_ids']=segment_ids
dict['label_id']=label_id
with open(filename,'ab') as p:
pickle.dump(dict,p)
from torch.utils.data import IterableDataset
class MyDataset(IterableDataset):
def __init__(self,args,filename):
self.args=args
self.filename=filename
def process(self,filename):
with open(self.filename, "rb") as f:
while True:
try:
yield pickle.load(f)
except EOFError:
break
def __iter__(self):
dataset=self.process(self.filename)
return dataset
def load_examples(args, task, mode='train'):
print("current mode: ",mode)
processor = TG2019RerankProcessor()
output_mode = "classification"
# Load data features from cache or dataset file
cached_examples_file = os.path.join(args.data_dir, 'examples_{}_{}_{}_{}'.format(
mode,
list(filter(None, args.model_name_or_path.split('/'))).pop(),
str(args.max_seq_length),
str(task)))
if args.cached_examples_file:
cached_examples_file = args.cached_examples_file
if os.path.exists(cached_examples_file):
logger.info("Loading examples from cached file %s", cached_examples_file)
examples = torch.load(cached_examples_file)
else:
if mode == 'train':
logger.info("Creating examples from dataset file at %s", args.train_questions_file)
examples = processor.get_train_examples(args)
elif mode == 'dev':
logger.info("Creating examples from dataset file at %s", args.dev_questions_file)
examples = processor.get_dev_examples(args)
elif mode == 'test':
logger.info("Creating examples from dataset file at %s", args.test_questions_file)
examples = processor.get_test_examples(args)
else:
raise ValueError("Unhandled mode {}".format(mode))
if args.local_rank in [-1, 0]:
logger.info("Saving examples into cached file %s", cached_examples_file)
torch.save(examples, cached_examples_file)
return examples
#import _pickle as cPickle
def train(args, train_dataset, model, tokenizer, label_list, num_samples):
""" Train the model """
if args.local_rank in [-1, 0]:
tb_writer = SummaryWriter()
args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu)
#train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.train_batch_size)
#train_dataloader_iter = iter(train_dataloader)
train_dataloader = DataLoader(train_dataset, batch_size=args.train_batch_size)
num_batches=num_samples//args.train_batch_size
if args.max_steps > 0:
t_total = args.max_steps
#args.num_train_epochs = args.max_steps // (len(train_dataloader) // args.gradient_accumulation_steps) + 1
args.num_train_epochs = args.max_steps //( num_batches // args.gradient_accumulation_steps) + 1
else:
# t_total = len(train_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs
t_total = num_batches// args.gradient_accumulation_steps * args.num_train_epochs
# Prepare optimizer and schedule (linear warmup and decay)
no_decay = ['bias', 'LayerNorm.weight']
optimizer_grouped_parameters = [
{'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], 'weight_decay': args.weight_decay},
{'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
]
optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)
scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=args.warmup_steps,
num_training_steps=t_total)
if args.fp16:
try:
from apex import amp
except ImportError:
raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.")
model, optimizer = amp.initialize(model.to('cuda'), optimizer, opt_level=args.fp16_opt_level)
# print("len of train dataloader: ",len(train_dataloader))
# print("len of train dataset: ",len(train_dataset))
# Train!
logger.info("***** Running training *****")
logger.info(" Num examples = %d", num_samples)
logger.info(" Num Epochs = %d", args.num_train_epochs)
logger.info(" Instantaneous batch size per GPU = %d", args.per_gpu_train_batch_size)
logger.info(" Total train batch size (w. parallel, distributed & accumulation) = %d",
args.train_batch_size * args.gradient_accumulation_steps * (torch.distributed.get_world_size() if args.local_rank != -1 else 1))
logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps)
logger.info(" Total optimization steps = %d", t_total)
global_step = 0
tr_loss, logging_loss = 0.0, 0.0
model.zero_grad()
train_iterator = trange(int(args.num_train_epochs), desc="Epoch", disable=args.local_rank not in [-1, 0])
set_seed(args) # Added here for reproductibility (even between python 2 and 3)
for _ in train_iterator:
epoch_iterator = tqdm(train_dataloader, desc="Iteration", disable=args.local_rank not in [-1, 0])
for step, batch in enumerate(epoch_iterator):
#while True:
# step=0
# batch = next(train_dataloader_iter)
model.train()
#batch = tuple(t.to(args.device) for t in batch)
a=torch.stack(list(map(torch.stack, zip(*(batch['input_ids']))))).to(args.device)
b=torch.stack(list(map(torch.stack, zip(*(batch['input_mask']))))).to(args.device)
c=torch.stack(list(map(torch.stack, zip(*(batch['segment_ids']))))).to(args.device)
d=batch['label_id'].to(args.device)
inputs = {'input_ids': a,
'attention_mask': b,
'token_type_ids': c if args.model_type in ['bert', 'xlnet'] else None, # XLM don't use segment_ids
'labels': d}
outputs = model(**inputs)
loss = outputs[0] # model outputs are always tuple in pytorch-transformers (see doc)
if args.n_gpu > 1:
loss = loss.mean() # mean() to average on multi-gpu parallel training
if args.gradient_accumulation_steps > 1:
loss = loss / args.gradient_accumulation_steps
if args.fp16:
with amp.scale_loss(loss, optimizer) as scaled_loss:
scaled_loss.backward()
torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args.max_grad_norm)
else:
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)
tr_loss += loss.item()
if (step + 1) % args.gradient_accumulation_steps == 0:
scheduler.step() # Update learning rate schedule
optimizer.step()
model.zero_grad()
global_step += 1
if args.local_rank in [-1, 0] and args.logging_steps > 0 and global_step % args.logging_steps == 0:
# Log metrics
tb_writer.add_scalar('lr', scheduler.get_lr()[0], global_step)
tb_writer.add_scalar('loss', (tr_loss - logging_loss)/args.logging_steps, global_step)
logging_loss = tr_loss
if args.local_rank == -1 and args.evaluate_during_training and global_step % args.evaluation_steps == 0:
# Only evaluate when single GPU otherwise metrics may not average well
results = evaluate(args, model, tokenizer, label_list)
for key, value in results.items():
tb_writer.add_scalar('eval_{}'.format(key), value, global_step)
if args.local_rank in [-1, 0] and args.save_steps > 0 and global_step % args.save_steps == 0:
# Save model checkpoint
output_dir = os.path.join(args.output_dir, 'checkpoint-{}'.format(global_step))
if not os.path.exists(output_dir):
os.makedirs(output_dir)
model_to_save = model.module if hasattr(model, 'module') else model # Take care of distributed/parallel training
model_to_save.save_pretrained(output_dir)
torch.save(args, os.path.join(output_dir, 'training_args.bin'))
logger.info("Saving model checkpoint to %s", output_dir)
if args.max_steps > 0 and global_step > args.max_steps:
epoch_iterator.close()
break
if args.max_steps > 0 and global_step > args.max_steps:
train_iterator.close()
break
if args.local_rank in [-1, 0]:
tb_writer.close()
return global_step, tr_loss / global_step
def evaluate(args, model, tokenizer, label_list, prefix=""):
eval_task = args.task_name
eval_output_dir = args.output_dir
results = {}
eval_examples=load_examples(args,eval_task,mode='dev')
mode='dev'
cached_features_file = os.path.join(args.data_dir,'features_{}_{}_{}_{}'.format(mode,list(filter(None, args.model_name_or_path.split('/'))).pop(),str(args.max_seq_length),str(eval_task)))
if args.cached_features_file:
cached_features_file = args.cached_features_file
if os.path.exists(cached_features_file):
logger.info("Loading features from cached file %s", cached_features_file)
else:
convert_examples_to_features(cached_features_file,args.per_gpu_eval_batch_size,eval_examples, label_list, args.max_seq_length, tokenizer, args.output_mode,
cls_token_at_end=bool(args.model_type in ['xlnet']), # xlnet has a cls token at the end
cls_token=tokenizer.cls_token,
sep_token=tokenizer.sep_token,
cls_token_segment_id=2 if args.model_type in ['xlnet'] else 1,
pad_on_left=bool(args.model_type in ['xlnet']), # pad on the left for xlnet
pad_token_segment_id=4 if args.model_type in ['xlnet'] else 0)
print("written features to disk, now loading file...")
eval_dataset=MyDataset(args,cached_features_file)
if not os.path.exists(eval_output_dir) and args.local_rank in [-1, 0]:
os.makedirs(eval_output_dir)
args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu)
# Note that DistributedSampler samples randomly
#eval_sampler = SequentialSampler(eval_dataset) if args.local_rank == -1 else DistributedSampler(eval_dataset)
#eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size)
eval_dataloader = DataLoader(eval_dataset, batch_size=args.eval_batch_size)
# Eval!
logger.info("***** Running evaluation {} *****".format(prefix))
logger.info(" Num examples = %d", len(eval_examples))
logger.info(" Batch size = %d", args.eval_batch_size)
eval_loss = 0.0
nb_eval_steps = 0
preds = None
out_label_ids = None
eval_file=os.path.join(eval_output_dir, "tg2020_eval_preds{}.npy".format(prefix))
with open(eval_file,'ab') as f:
for batch in tqdm(eval_dataloader, desc="Evaluating"):
model.eval()
#batch = tuple(t.to(args.device) for t in batch)
a=torch.stack(list(map(torch.stack, zip(*(batch['input_ids']))))).to(args.device)
b=torch.stack(list(map(torch.stack, zip(*(batch['input_mask']))))).to(args.device)
c=torch.stack(list(map(torch.stack, zip(*(batch['segment_ids']))))).to(args.device)
d=batch['label_id'].to(args.device)
with torch.no_grad():
inputs = {'input_ids': a,
'attention_mask': b,
'token_type_ids': c if args.model_type in ['bert', 'xlnet'] else None, # XLM don't use segment_ids
'labels': d}
outputs = model(**inputs)
tmp_eval_loss, logits = outputs[:2]
eval_loss += tmp_eval_loss.mean().item()
nb_eval_steps += 1
preds = logits.detach().cpu().numpy()
np.save(f, preds)
out_label_ids = inputs['labels'].detach().cpu().numpy()
eval_loss = eval_loss / nb_eval_steps
# print("predictions: ",preds)
# print("output label id",out_label_ids)
return results
def predict(args, model, tokenizer, label_list, prefix=""):
eval_task = args.task_name
eval_output_dir = args.output_dir
results = {}
mode='test'
eval_examples=load_examples(args,eval_task,mode='test')
cached_features_file = os.path.join(args.data_dir,'features_{}_{}_{}_{}'.format(mode,list(filter(None, args.model_name_or_path.split('/'))).pop(),str(args.max_seq_length),str(eval_task)))
if args.cached_features_file:
cached_features_file = args.cached_features_file
if os.path.exists(cached_features_file):
logger.info("Loading features from cached file %s", cached_features_file)
else:
logger.info("Creating features from cached examples file.... ")
convert_examples_to_features(cached_features_file,args.per_gpu_train_batch_size,eval_examples, label_list, args.max_seq_length, tokenizer, args.output_mode,
cls_token_at_end=bool(args.model_type in ['xlnet']), # xlnet has a cls token at the end
cls_token=tokenizer.cls_token,
sep_token=tokenizer.sep_token,
cls_token_segment_id=2 if args.model_type in ['xlnet'] else 1,
pad_on_left=bool(args.model_type in ['xlnet']), # pad on the left for xlnet
pad_token_segment_id=4 if args.model_type in ['xlnet'] else 0)
print("written features to disk, now loading file...")
eval_dataset=MyDataset(args,cached_features_file)
if not os.path.exists(eval_output_dir) and args.local_rank in [-1, 0]:
os.makedirs(eval_output_dir)
args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu)
# Note that DistributedSampler samples randomly
#eval_sampler = SequentialSampler(eval_dataset) if args.local_rank == -1 else DistributedSampler(eval_dataset)
#eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size)
eval_dataloader = DataLoader(eval_dataset, batch_size=args.eval_batch_size)
# Predict!
logger.info("***** Running prediction {} *****".format(prefix))
logger.info(" Num examples = %d", len(eval_examples))
logger.info(" Batch size = %d", args.eval_batch_size)
nb_eval_steps = 0
preds = None
eval_file=os.path.join(eval_output_dir, "tg2020_test_preds{}.npy".format(prefix))
for batch in tqdm(eval_dataloader, desc="Evaluating"):
model.eval()
#batch = tuple(t.to(args.device) for t in batch)
a=torch.stack(list(map(torch.stack, zip(*(batch['input_ids']))))).to(args.device)
b=torch.stack(list(map(torch.stack, zip(*(batch['input_mask']))))).to(args.device)
c=torch.stack(list(map(torch.stack, zip(*(batch['segment_ids']))))).to(args.device)
with torch.no_grad():
inputs = {'input_ids': a,
'attention_mask': b,
'token_type_ids': c if args.model_type in ['bert', 'xlnet'] else None, # XLM don't use segment_ids
}
outputs = model(**inputs)
logits = outputs[0]
nb_eval_steps += 1
preds = logits.detach().cpu().numpy()
with open(eval_file,'ab') as f:
np.save(f, preds)
base_path=''
class Args1:
TRAIN_QUESTIONS_FILE= base_path + "questions/questions.train.tsv"
DEV_QUESTIONS_FILE= base_path +"questions/questions.dev.tsv"
TEST_QUESTIONS_FILE= base_path +"questions/questions.test.tsv"
FACTS_FILE= base_path +"questions/explanations.tsv"
DATA_DIR=base_path +"questions"
RERANK_TRAIN_SEQ=72
RERANK_PRED_SEQ=140
RERANK_OUTPUT_DIR= base_path +"outputs/bert_rerank_correctchoices_unweighted/"
PATH_RANK_TRAIN_SEQ=90
PATH_RANK_TRAIN_TFIDF=25
PATH_RANK_PRED_SEQ=140
PATH_RANK_PRED_TFIDF=50
PATH_RANK_OUTPUT_DIR= base_path + "outputs/bert_path_rank_correctchoices_unweighted_k25_1e/"
model_type= "bert"
model_name_or_path= "bert-base-uncased"
task_name= "TG2020"
do_train=1
do_eval=1
do_lower_case=1
data_dir=DATA_DIR
max_seq_length=RERANK_TRAIN_SEQ
per_gpu_eval_batch_size=64
per_gpu_train_batch_size=64
learning_rate= 2e-5
num_train_epochs= 3.0
logging_steps= 5000
evaluate_during_training= 1
evaluation_steps= 25000
save_steps= 5000
output_dir=RERANK_OUTPUT_DIR
train_questions_file=TRAIN_QUESTIONS_FILE
dev_questions_file=DEV_QUESTIONS_FILE
facts_file=FACTS_FILE
mcq_choices= "correct"
do_predict = 0
## Other parameters
weighted_sampling=0
config_name=""
tokenizer_name=""
cached_examples_file=""
cached_features_file=""
cache_dir=""
gradient_accumulation_steps = 1
weight_decay = 0.0
adam_epsilon = 1e-8
max_grad_norm = 1.0
overwrite_cache= 1
overwrite_output_dir= 1
no_cuda= 1
logging_steps= 50
eval_all_checkpoints = 1
seed = 42
warmup_steps = 0
max_steps = -1
fp16= 0
fp16_opt_level= "O1"
local_rank = -1
class Args2:
TEST_QUESTIONS_FILE=base_path + "questions/questions.test.tsv"
FACTS_FILE=base_path + "questions/explanations.tsv"
DATA_DIR=base_path + "questions"
RERANK_PRED_SEQ=140
RERANK_OUTPUT_DIR=base_path + "outputs/bert_rerank_correctchoices_unweighted/"
# Get predictions from bert-reranker (base predictions)
model_type= "bert"
model_name_or_path= "bert-base-uncased"
task_name= "TG2020"
do_predict= 1
do_lower_case= 1
data_dir = DATA_DIR
max_seq_length = RERANK_PRED_SEQ
output_dir = RERANK_OUTPUT_DIR
test_questions_file = TEST_QUESTIONS_FILE
facts_file= FACTS_FILE
mcq_choices= "correct"
#Other parameters
do_train=0
do_eval=0
evaluation_steps=50
overwrite_cache= 1
overwrite_output_dir= 1
save_steps= 50
logging_steps= 50
eval_all_checkpoints = 1
seed = 42
warmup_steps = 0
max_steps = -1
fp16= 0
fp16_opt_level= "O1"
local_rank = -1
per_gpu_train_batch_size = 64
per_gpu_eval_batch_size = 64
learning_rate = 5e-5
evaluate_during_training = 1
num_train_epochs = 3.0
no_cuda=0
weighted_sampling=0
config_name=""
tokenizer_name=""
cached_examples_file=""
cached_features_file=""
cache_dir=""
gradient_accumulation_steps = 1
weight_decay = 0.0
adam_epsilon = 1e-8
max_grad_norm = 1.0
def main():
mode=sys.argv[1]
if mode=='train':
args = Args1()
if mode=='test':
args = Args2()
if os.path.exists(args.output_dir) and os.listdir(args.output_dir) and args.do_train and not args.overwrite_output_dir:
raise ValueError("Output directory ({}) already exists and is not empty. Use --overwrite_output_dir to overcome.".format(args.output_dir))
# Setup CUDA, GPU & distributed training
if args.local_rank == -1 or args.no_cuda:
device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
args.n_gpu = torch.cuda.device_count()
else: # Initializes the distributed backend which will take care of sychronizing nodes/GPUs
torch.cuda.set_device(args.local_rank)
device = torch.device("cuda", args.local_rank)
torch.distributed.init_process_group(backend='nccl')
args.n_gpu = 1
args.device = device
# Setup logging
logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt = '%m/%d/%Y %H:%M:%S',
level = logging.INFO if args.local_rank in [-1, 0] else logging.WARN)
logger.warning("Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s",
args.local_rank, device, args.n_gpu, bool(args.local_rank != -1), args.fp16)
# Set seed
set_seed(args)
# Prepare task
args.task_name = args.task_name.lower()
processor = TG2019RerankProcessor()
args.output_mode = "classification"
label_list = processor.get_labels()
num_labels = len(label_list)
# Load pretrained model and tokenizer
if args.local_rank not in [-1, 0]:
torch.distributed.barrier() # Make sure only the first process in distributed training will download model & vocab
args.model_type = args.model_type.lower()
config_class, model_class, tokenizer_class = MODEL_CLASSES[args.model_type]
config = config_class.from_pretrained(args.config_name if args.config_name else args.model_name_or_path, num_labels=num_labels, finetuning_task=args.task_name)
tokenizer = tokenizer_class.from_pretrained(args.tokenizer_name if args.tokenizer_name else args.model_name_or_path, do_lower_case=args.do_lower_case)
model = model_class.from_pretrained(args.model_name_or_path, from_tf=bool('.ckpt' in args.model_name_or_path), config=config)
if args.local_rank == 0:
torch.distributed.barrier() # Make sure only the first process in distributed training will download model & vocab
# Distributed and parallel training
model.to(args.device)
if args.local_rank != -1:
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank],
output_device=args.local_rank,
find_unused_parameters=True)
elif args.n_gpu > 1:
model = torch.nn.DataParallel(model)
logger.info("Training/evaluation parameters %s", args)
# Training
if args.do_train:
task=args.task_name
mode='train'
train_examples=load_examples(args,task,mode)
cached_features_file = os.path.join(args.data_dir,'features_{}_{}_{}_{}'.format(mode,list(filter(None, args.model_name_or_path.split('/'))).pop(),str(args.max_seq_length),str(task)))
if args.cached_features_file:
cached_features_file = args.cached_features_file
if os.path.exists(cached_features_file):
logger.info("Loading features from cached file %s", cached_features_file)
else:
convert_examples_to_features(cached_features_file,args.per_gpu_train_batch_size,train_examples, label_list, args.max_seq_length, tokenizer, args.output_mode,
cls_token_at_end=bool(args.model_type in ['xlnet']), # xlnet has a cls token at the end
cls_token=tokenizer.cls_token,
sep_token=tokenizer.sep_token,
cls_token_segment_id=2 if args.model_type in ['xlnet'] else 1,
pad_on_left=bool(args.model_type in ['xlnet']), # pad on the left for xlnet
pad_token_segment_id=4 if args.model_type in ['xlnet'] else 0)
print("written features to disk, now loading file...")
train_dataset=MyDataset(args,cached_features_file)
#print("type of object from mydataset: ",type(out))
#print(type(train_dataset))
num_samples=500000
print("number of training samples: ",num_samples)
global_step, tr_loss = train(args, train_dataset, model, tokenizer, label_list, num_samples)
logger.info(" global_step = %s, average loss = %s", global_step, tr_loss)
# Saving best-practices: if you use defaults names for the model, you can reload it using from_pretrained()
if args.do_train and (args.local_rank == -1 or torch.distributed.get_rank() == 0):
# Create output directory if needed
if not os.path.exists(args.output_dir) and args.local_rank in [-1, 0]:
os.makedirs(args.output_dir)
logger.info("Saving model checkpoint to %s", args.output_dir)
# Save a trained model, configuration and tokenizer using `save_pretrained()`.
# They can then be reloaded using `from_pretrained()`
model_to_save = model.module if hasattr(model, 'module') else model # Take care of distributed/parallel training
model_to_save.save_pretrained(args.output_dir)
tokenizer.save_pretrained(args.output_dir)
# Good practice: save your training arguments together with the trained model
torch.save(args, os.path.join(args.output_dir, 'training_args.bin'))
# Load a trained model and vocabulary that you have fine-tuned
model = model_class.from_pretrained(args.output_dir)
tokenizer = tokenizer_class.from_pretrained(args.output_dir)
model.to(args.device)