-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdmix.py
1679 lines (1429 loc) · 67.6 KB
/
dmix.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 csv
from nltk.tokenize import word_tokenize
from tqdm import tqdm
import pickle
import pandas as pd
import math
import nltk
nltk.download('punkt')
import torch
import torch.nn as nn
from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler,
TensorDataset)
import torch.multiprocessing as mp
import torch.nn.functional as F
from pytorch_pretrained_bert import BertTokenizer
from pytorch_pretrained_bert.optimization import BertAdam
from sklearn.metrics import precision_score, recall_score, roc_curve, auc, confusion_matrix, accuracy_score
import numpy as np
import os
from random import shuffle
from datetime import datetime
import time
import logging
import copy
import random
from torch.multiprocessing import Pool
torch.multiprocessing.set_sharing_strategy('file_system')
from functools import partial
import csv
from nltk.tokenize import word_tokenize
from tqdm import tqdm
import pickle
import pandas as pd
import math
import nltk
nltk.download('punkt')
import torch
import torch.nn as nn
import torch.nn.functional as F
from pytorch_pretrained_bert import BertTokenizer
from pytorch_pretrained_bert.optimization import BertAdam
from sklearn.metrics import precision_score, recall_score, roc_curve, auc, confusion_matrix
from sklearn.metrics import classification_report
import bisect
import os
import pdb
import logging
import sys
import socket
import re
import time
from scipy.stats import spearmanr
USE_COLAB = False
logger = logging.getLogger('')
import re
REPLACE_NO_SPACE = re.compile("(\.)|(\;)|(\:)|(\!)|(\')|(\?)|(\,)|(\")|(\()|(\))|(\[)|(\])|(\d+)")
REPLACE_WITH_SPACE = re.compile("(<br\s*/><br\s*/>)|(\-)|(\/)")
NO_SPACE = ""
SPACE = " "
def preprocess_reviews(reviews):
reviews = REPLACE_NO_SPACE.sub(NO_SPACE, reviews.lower())
reviews = REPLACE_WITH_SPACE.sub(SPACE, reviews)
return reviews
def eval(preds, y):
assert len(preds) == len(y)
z = np.zeros(len(preds))
for i, p in enumerate(preds):
if (p-math.floor(p)) < 0.5:
z[i] = math.floor(p)
else:
z[i] = math.floor(p) + 1
prec_score = precision_score(np.array(y), z,average="micro")
rec_score = recall_score(np.array(y), z,average="micro")
f1_score = (2 * prec_score * rec_score) / (prec_score + rec_score)
# making other metric 0 as they dont signify anything in multiclass
roc_auc, tn, fp, fn, tp, error_rate = 0,0,0,0,0,0
return (prec_score, rec_score, f1_score, roc_auc, tn, fp, fn, tp, error_rate)
def Average(lst):
return sum(lst) / len(lst)
def trainMix(model, scheduler, optimizer, numEpochs, train_dataloader, eval_dataloader, outLocation, out_file, device, n_gpu = 1 ):
performance = []
error_rates = []
print("N_GPU", n_gpu)
# training
logger.info("Number of Epochs: {}".format(numEpochs))
for epoch in range(numEpochs):
train_loss = 0
correct = 0
total = 0
train_preds = []
train_targets = []
performance.append({})
# looping through the training set
model.train()
for step, batch in enumerate(tqdm(train_dataloader, desc="Iteration")):
batch = tuple(t.to(device) for t in batch)
input_ids, input_mask, segment_ids, label_ids, ids = batch
loss, logits, lam = model(input_ids, segment_ids, input_mask, label_ids, ids,1)
if n_gpu > 1:
loss = loss.mean() # mean() to average on multi-gpu.
loss.backward()
total += label_ids.size(0)
train_loss += loss.item()
optimizer.step()
optimizer.zero_grad()
correct += logits.eq(label_ids).cpu().sum().float()
logger.info('epoch:' + str(epoch) + ' loss:' + str(train_loss) + ' Accuracy:' + str(correct/total))
del train_preds
del train_loss
del train_targets
if eval_dataloader is not None:
model.eval()
test_preds = []
test_targets = []
for input_ids, input_mask, segment_ids, label_ids, ids in eval_dataloader:
input_ids = input_ids.to(device)
input_mask = input_mask.to(device)
segment_ids = segment_ids.to(device)
label_ids = label_ids.to(device)
with torch.no_grad():
logits = model(input_ids, segment_ids, input_mask)
logits = logits.detach().cpu().numpy()
label_ids = label_ids.to('cpu').numpy()
test_preds.append(logits)
test_targets.append(label_ids)
test_preds = [k[i] for k in test_preds for i in range(k.shape[0])]
test_targets = [i for item in test_targets for i in item]
preds = np.array(test_preds)
test_prediction = np.array(test_targets)
np.save("test_preds.npy",preds)
np.save("test_targets.npy",test_prediction)
test_eval = eval(test_preds, test_targets)
logger.info('epoch:' + str(epoch) + ' precision:' + str(test_eval[0]) + ' recall:' +
str(test_eval[1]) + ' f1:' + str(test_eval[2]) + ' roc_auc:' + str(test_eval[3]) +
' false positive:' + str(test_eval[5]) + ' Error Rate:' + str(test_eval[8]))
del test_preds
del test_targets
logger.info("Model File: {}".format(out_file + str(epoch) + '.bin'))
def setup_logger(logger_name, log_file, level=logging.INFO):
'''This sets up a python logger that follows the amazon guidelines for logging.
'''
log = logging.getLogger('')
formatter = logging.Formatter("%(asctime)s crm_logger %(process)d-0@" +
socket.gethostname() +
":0 [%(levelname)s] %(filename)s:%(lineno)d " +
"%(message)s",
"%c")
file_handler = logging.FileHandler(log_file, mode='a', encoding='utf-8')
file_handler.setFormatter(formatter)
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
log.setLevel(level)
log.addHandler(stream_handler)
log.addHandler(file_handler)
modelType = 'BERT_MR_MIX-UP_10_2e-5_single no pre attn full hidden layer 00-8 BCELOSS fixed'
dataStorageLocation = '/content/gdrive/My Drive/Research/mixup/MR'
#logFolder = 'data/logs'
logFolder = '/content/gdrive/My Drive/Research/mixup/MR/logs'
args = {
"train_size": -1,
"val_size": -1,
"full_data_dir": dataStorageLocation,
"data_dir": dataStorageLocation,
"task_name": "news_cat_label",
"no_cuda": False,
"bert_model": 'bert-base-uncased',
"max_seq_length": 61,
"do_train": True,
"do_eval": True,
"do_lower_case": True,
"train_batch_size": 8,
"eval_batch_size": 8,
"learning_rate": 2e-5,
"num_train_epochs": 10.0,
"warmup_proportion": 0.1,
"no_cuda": False,
"local_rank": -1,
"seed": 42,
"gradient_accumulation_steps": 1,
"optimize_on_cpu": False,
"fp16": False,
"loss_scale": 128
}
if not os.path.exists(dataStorageLocation):
os.makedirs(dataStorageLocation)
if not os.path.exists(logFolder):
os.makedirs(logFolder)
lr = args['learning_rate']
numEpochs = args['num_train_epochs']
batch_size = args['train_batch_size']
class InputExample(object):
"""A single training/test example for simple sequence classification."""
def __init__(self, guid, text_a, text_b=None, labels=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.
labels: (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.labels = labels
class InputFeatures(object):
"""A single set of features of data."""
def __init__(self, input_ids, input_mask, segment_ids, label_ids,ids):
self.input_ids = input_ids
self.input_mask = input_mask # attention_mask
self.segment_ids = segment_ids # token_type_ids
self.label_ids = label_ids
self.ids = ids
class DataProcessor(object):
"""Base class for data converters for sequence classification data sets."""
def get_train_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the train set."""
raise NotImplementedError()
def get_dev_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the dev set."""
raise NotImplementedError()
def get_test_examples(self, data_dir, data_file_name, size=-1):
"""Gets a collection of `InputExample`s for the dev set."""
raise NotImplementedError()
def get_labels(self):
"""Gets the list of labels for this data set."""
raise NotImplementedError()
class LabelTextProcessor(DataProcessor):
def __init__(self, data_dir):
self.data_dir = data_dir
self.labels = None
def get_train_examples(self, data, size=-1):
#filename = 'train.csv'
#logger.info("LOOKING AT {}".format(os.path.join(data_dir, filename)))
if size == -1:
#data_df = os.path.join(data_dir, filename),engine=None
return self._create_examples(data, "train")
else:
data_df = pd.read_csv(os.path.join(data_dir, filename))
return self._create_examples(data_df.sample(size), "train")
def get_dev_examples(self, dev, size=-1):
"""See base class."""
#filename = 'test.csv'
if size == -1:
#data_df = os.path.join(data_dir, filename)
return self._create_examples(dev, "dev")
else:
data_df = pd.read_csv(os.path.join(data_dir, filename))
return self._create_examples(data_df.sample(size), "dev")
def get_test_examples(self, data_dir, data_file_name, size=-1):
data_df = pd.read_csv(os.path.join(data_dir, data_file_name))
if size == -1:
return self._create_examples(data_df, "test")
else:
return self._create_examples(data_df.sample(size), "test")
def get_labels(self):
# Enter the number of labels
a = [x for x in range()]
return a
def _create_examples(self, data, set_type, labels_available=True):
"""Creates examples for the training and dev sets."""
guid = data['text_id']
text = (data['text'])
text_a = text
labels = int(data['label'])
examples = (InputExample(guid=guid, text_a=text_a, labels=labels))
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 convert_examples_to_features(label_list, max_seq_length, tokenizer, train_examples):
"""Loads a data file into a list of `InputBatch`s."""
example = train_examples
label_map = {label : i for i, label in enumerate(label_list)}
id = example.guid
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 = ["[CLS]"] + tokens_a + ["[SEP]"]
segment_ids = [0] * len(tokens)
if tokens_b:
tokens += tokens_b + ["[SEP]"]
segment_ids += [1] * (len(tokens_b) + 1)
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] * len(input_ids)
# Zero-pad up to the sequence length.
padding = [0] * (max_seq_length - len(input_ids))
input_ids += padding
input_mask += padding
segment_ids += padding
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
label_ids = label_map[example.labels]
features = (
InputFeatures(input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
label_ids=label_ids,
ids = id))
return features
processors = {
"news_cat_label": LabelTextProcessor
}
# Setup GPU parameters
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")
n_gpu = torch.cuda.device_count()
n_gpu = 1
random.seed(args['seed'])
np.random.seed(args['seed'])
torch.manual_seed(args['seed'])
if n_gpu > 0:
torch.cuda.manual_seed_all(args['seed'])
task_name = args['task_name'].lower()
if task_name not in processors:
raise ValueError("Task not found: %s" % (task_name))
filedate = datetime.now().strftime('%Y_%m_%d_%H_%M_%S')
setup_logger('DummyLoggerName', os.path.join(logFolder,'CV_'+modelType+'_'+filedate+'_'+'.log'))
logger = logging.getLogger('')
logger.info("Model Type: {}".format(modelType))
import pandas as pd
# Load the merged df (both train and test, we'll split later)
df = pd.read_csv("PATH")
index = [x for x in range(len(df))]
index = list(index)
# Label the text column and label column (label-coarse and label-fine for TREC)
sentences, labels = list(df['Text']), list(df['label'])
l = [len(word.split()) for word in sentences]
len(sentences)
# MR dataset preprocessing
processor = processors[task_name](args['data_dir'])
label_list = processor.get_labels()
num_labels = len(label_list)
data = []
test_data = []
i = 0
# The replace number of training samples in the merged dataframe
num_training_samples = ###
for line, label, id in zip(sentences, labels,index):
if i < num_training_samples:
data.append({})
data[-1]['text_id'] = i
data[-1]['text'] = line.strip()
data[-1]['label'] = label
data[-1]['text_id'] = id
i +=1
else:
test_data.append({})
test_data[-1]['text_id'] = i
test_data[-1]['text'] = line.strip()
test_data[-1]['label'] = label
test_data[-1]['text_id'] = id
i +=1
logger.info("--- Pre-processing training data ---")
shuffle(data)
shuffle(test_data)
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True)
train_examples = None
num_train_steps = None
processes = []
pool = Pool(10)
train_examples = pool.map(processor.get_train_examples, data)
eval_examples = pool.map(processor.get_dev_examples, test_data)
pool.close()
pool.join()
pool = Pool(20)
func = partial(convert_examples_to_features, label_list, args['max_seq_length'], tokenizer)
train_features = pool.map(func, train_examples)
pool.close()
pool.join()
pool = Pool(20)
func = partial(convert_examples_to_features, label_list, args['max_seq_length'], tokenizer)
eval_features = pool.map(func, eval_examples)
pool.close()
pool.join()
print(len(train_features))
print(len(eval_features))
print("Features generated --", len(train_features))
logger.info("Training Model")
logger.info("Learning Rate: {}".format(lr))
logger.info("***** Running training *****")
logger.info(" Num examples = %d", len(train_examples))
logger.info(" Batch size = %d", args['train_batch_size'])
all_input_ids = torch.tensor([f.input_ids for f in train_features], dtype=torch.long)
all_input_mask = torch.tensor([f.input_mask for f in train_features], dtype=torch.long)
all_ids = torch.tensor([f.ids for f in train_features], dtype=torch.long)
all_segment_ids = torch.tensor([f.segment_ids for f in train_features], dtype=torch.long)
all_label_ids = torch.tensor([f.label_ids for f in train_features], dtype=torch.long)
train_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids,all_ids)
train_dataloader = DataLoader(train_data, batch_size=args['train_batch_size'], shuffle=True)
logger.info("***** Building Eval DataLoader *****")
logger.info(" Num examples = %d", len(eval_examples))
logger.info(" Batch size = %d", args['eval_batch_size'])
all_input_ids = torch.tensor([f.input_ids for f in eval_features], dtype=torch.long)
all_input_mask = torch.tensor([f.input_mask for f in eval_features], dtype=torch.long)
all_ids = torch.tensor([f.ids for f in eval_features], dtype=torch.long)
all_segment_ids = torch.tensor([f.segment_ids for f in eval_features], dtype=torch.long)
all_label_ids = torch.tensor([f.label_ids for f in eval_features], dtype=torch.long)
eval_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids,all_ids)
# Run prediction for full data
eval_dataloader = DataLoader(eval_data, batch_size=args['eval_batch_size'])
def get_cosine_sentence(i,perc,common,a):
num = np.amax(a[i])
p = num*perc
args = np.argwhere(a[i]>p.item())
try:
rand = np.random.randint(0,len(args),1)
except:
print("Some Issue")
rand = 0
rand = rand[0]
a = args[rand]
return a
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True)
master_ids = np.array([f.ids for f in train_features])
master_input_ids = [f.input_ids for f in train_features]
master_input_mask = [f.input_mask for f in train_features]
master_segment_ids = [f.segment_ids for f in train_features]
master_label_ids = [f.label_ids for f in train_features]
def get_second_example(ids,common,a):
array = []
idx = []
# Change the Threshold value as required.
percentage = 0.70
for i in range(len(a)):
a[i] = common[i].item()*a[i]
for i in range(len(ids)):
ex = ids[i]
exs = ex.item()
idx.append(exs)
sel = get_cosine_sentence(ex,percentage,common,a)
array.append(common[ids[i]]*(torch.tensor(a[ids[i]][sel].astype(np.float32),device="cuda")))
all_input_ids = []
all_input_mask = []
all_segment_ids = []
all_label_ids = []
for i in range(len(idx)):
num = idx[i]
pos = np.argwhere(master_ids == num).item()
all_input_ids.append(master_input_ids[pos])
all_input_mask.append(master_input_mask[pos])
all_segment_ids.append(master_segment_ids[pos])
all_label_ids.append(master_label_ids[pos])
all_input_ids = torch.tensor(all_input_ids, dtype=torch.long)
all_input_mask = torch.tensor(all_input_mask, dtype=torch.long)
all_segment_ids = torch.tensor(all_segment_ids, dtype=torch.long)
all_label_ids = torch.tensor(all_label_ids, dtype=torch.long)
train_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids)
train_dataloader = DataLoader(train_data, batch_size=args['train_batch_size'])
return train_dataloader,array
"""
Utilities for working with the local dataset cache.
This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp
Copyright by the AllenNLP authors.
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
import sys
import json
import logging
import os
import six
import shutil
import tempfile
import fnmatch
from functools import wraps
from hashlib import sha256
from io import open
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError
import requests
from tqdm import tqdm
try:
from torch.hub import _get_torch_home
torch_cache_home = _get_torch_home()
except ImportError:
torch_cache_home = os.path.expanduser(
os.getenv('TORCH_HOME', os.path.join(
os.getenv('XDG_CACHE_HOME', '~/.cache'), 'torch')))
default_cache_path = os.path.join(torch_cache_home, 'pytorch_transformers')
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
try:
from pathlib import Path
PYTORCH_PRETRAINED_BERT_CACHE = Path(
os.getenv('PYTORCH_TRANSFORMERS_CACHE', os.getenv('PYTORCH_PRETRAINED_BERT_CACHE', default_cache_path)))
except (AttributeError, ImportError):
PYTORCH_PRETRAINED_BERT_CACHE = os.getenv('PYTORCH_TRANSFORMERS_CACHE',
os.getenv('PYTORCH_PRETRAINED_BERT_CACHE',
default_cache_path))
PYTORCH_TRANSFORMERS_CACHE = PYTORCH_PRETRAINED_BERT_CACHE # Kept for backward compatibility
WEIGHTS_NAME = "pytorch_model.bin"
TF_WEIGHTS_NAME = 'model.ckpt'
CONFIG_NAME = "config.json"
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
if not six.PY2:
def add_start_docstrings(*docstr):
def docstring_decorator(fn):
fn.__doc__ = ''.join(docstr) + fn.__doc__
return fn
return docstring_decorator
def add_end_docstrings(*docstr):
def docstring_decorator(fn):
fn.__doc__ = fn.__doc__ + ''.join(docstr)
return fn
return docstring_decorator
else:
# Not possible to update class docstrings on python2
def add_start_docstrings(*docstr):
def docstring_decorator(fn):
return fn
return docstring_decorator
def add_end_docstrings(*docstr):
def docstring_decorator(fn):
return fn
return docstring_decorator
def url_to_filename(url, etag=None):
"""
Convert `url` into a hashed filename in a repeatable way.
If `etag` is specified, append its hash to the url's, delimited
by a period.
"""
url_bytes = url.encode('utf-8')
url_hash = sha256(url_bytes)
filename = url_hash.hexdigest()
if etag:
etag_bytes = etag.encode('utf-8')
etag_hash = sha256(etag_bytes)
filename += '.' + etag_hash.hexdigest()
return filename
def filename_to_url(filename, cache_dir=None):
"""
Return the url and etag (which may be ``None``) stored for `filename`.
Raise ``EnvironmentError`` if `filename` or its stored metadata do not exist.
"""
if cache_dir is None:
cache_dir = PYTORCH_TRANSFORMERS_CACHE
if sys.version_info[0] == 3 and isinstance(cache_dir, Path):
cache_dir = str(cache_dir)
cache_path = os.path.join(cache_dir, filename)
if not os.path.exists(cache_path):
raise EnvironmentError("file {} not found".format(cache_path))
meta_path = cache_path + '.json'
if not os.path.exists(meta_path):
raise EnvironmentError("file {} not found".format(meta_path))
with open(meta_path, encoding="utf-8") as meta_file:
metadata = json.load(meta_file)
url = metadata['url']
etag = metadata['etag']
return url, etag
def cached_path(url_or_filename, cache_dir=None, force_download=False, proxies=None):
"""
Given something that might be a URL (or might be a local path),
determine which. If it's a URL, download the file and cache it, and
return the path to the cached file. If it's already a local path,
make sure the file exists and then return the path.
Args:
cache_dir: specify a cache directory to save the file to (overwrite the default cache dir).
force_download: if True, re-dowload the file even if it's already cached in the cache dir.
"""
if cache_dir is None:
cache_dir = PYTORCH_TRANSFORMERS_CACHE
if sys.version_info[0] == 3 and isinstance(url_or_filename, Path):
url_or_filename = str(url_or_filename)
if sys.version_info[0] == 3 and isinstance(cache_dir, Path):
cache_dir = str(cache_dir)
parsed = urlparse(url_or_filename)
if parsed.scheme in ('http', 'https', 's3'):
# URL, so get it from the cache (downloading if necessary)
return get_from_cache(url_or_filename, cache_dir=cache_dir, force_download=force_download, proxies=proxies)
elif os.path.exists(url_or_filename):
# File, and it exists.
return url_or_filename
elif parsed.scheme == '':
# File, but it doesn't exist.
raise EnvironmentError("file {} not found".format(url_or_filename))
else:
# Something unknown
raise ValueError("unable to parse {} as a URL or as a local path".format(url_or_filename))
def split_s3_path(url):
"""Split a full s3 path into the bucket name and path."""
parsed = urlparse(url)
if not parsed.netloc or not parsed.path:
raise ValueError("bad s3 path {}".format(url))
bucket_name = parsed.netloc
s3_path = parsed.path
# Remove '/' at beginning of path.
if s3_path.startswith("/"):
s3_path = s3_path[1:]
return bucket_name, s3_path
def s3_request(func):
"""
Wrapper function for s3 requests in order to create more helpful error
messages.
"""
@wraps(func)
def wrapper(url, *args, **kwargs):
try:
return func(url, *args, **kwargs)
except ClientError as exc:
if int(exc.response["Error"]["Code"]) == 404:
raise EnvironmentError("file {} not found".format(url))
else:
raise
return wrapper
@s3_request
def s3_etag(url, proxies=None):
"""Check ETag on S3 object."""
s3_resource = boto3.resource("s3", config=Config(proxies=proxies))
bucket_name, s3_path = split_s3_path(url)
s3_object = s3_resource.Object(bucket_name, s3_path)
return s3_object.e_tag
@s3_request
def s3_get(url, temp_file, proxies=None):
"""Pull a file directly from S3."""
s3_resource = boto3.resource("s3", config=Config(proxies=proxies))
bucket_name, s3_path = split_s3_path(url)
s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)
def http_get(url, temp_file, proxies=None):
req = requests.get(url, stream=True, proxies=proxies)
content_length = req.headers.get('Content-Length')
total = int(content_length) if content_length is not None else None
progress = tqdm(unit="B", total=total)
for chunk in req.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
progress.update(len(chunk))
temp_file.write(chunk)
progress.close()
def get_from_cache(url, cache_dir=None, force_download=False, proxies=None):
"""
Given a URL, look for the corresponding dataset in the local cache.
If it's not there, download it. Then return the path to the cached file.
"""
if cache_dir is None:
cache_dir = PYTORCH_TRANSFORMERS_CACHE
if sys.version_info[0] == 3 and isinstance(cache_dir, Path):
cache_dir = str(cache_dir)
if sys.version_info[0] == 2 and not isinstance(cache_dir, str):
cache_dir = str(cache_dir)
if not os.path.exists(cache_dir):
os.makedirs(cache_dir)
# Get eTag to add to filename, if it exists.
if url.startswith("s3://"):
etag = s3_etag(url, proxies=proxies)
else:
try:
response = requests.head(url, allow_redirects=True, proxies=proxies)
if response.status_code != 200:
etag = None
else:
etag = response.headers.get("ETag")
except EnvironmentError:
etag = None
if sys.version_info[0] == 2 and etag is not None:
etag = etag.decode('utf-8')
filename = url_to_filename(url, etag)
# get cache path to put the file
cache_path = os.path.join(cache_dir, filename)
# If we don't have a connection (etag is None) and can't identify the file
# try to get the last downloaded one
if not os.path.exists(cache_path) and etag is None:
matching_files = fnmatch.filter(os.listdir(cache_dir), filename + '.*')
matching_files = list(filter(lambda s: not s.endswith('.json'), matching_files))
if matching_files:
cache_path = os.path.join(cache_dir, matching_files[-1])
if not os.path.exists(cache_path) or force_download:
# Download to temporary file, then copy to cache dir once finished.
# Otherwise you get corrupt cache entries if the download gets interrupted.
with tempfile.NamedTemporaryFile() as temp_file:
logger.info("%s not found in cache or force_download set to True, downloading to %s", url, temp_file.name)
# GET file object
if url.startswith("s3://"):
s3_get(url, temp_file, proxies=proxies)
else:
http_get(url, temp_file, proxies=proxies)
# we are copying the file before closing it, so flush to avoid truncation
temp_file.flush()
# shutil.copyfileobj() starts at the current position, so go to the start
temp_file.seek(0)
logger.info("copying %s to cache at %s", temp_file.name, cache_path)
with open(cache_path, 'wb') as cache_file:
shutil.copyfileobj(temp_file, cache_file)
logger.info("creating metadata file for %s", cache_path)
meta = {'url': url, 'etag': etag}
meta_path = cache_path + '.json'
with open(meta_path, 'w') as meta_file:
output_string = json.dumps(meta)
if sys.version_info[0] == 2 and isinstance(output_string, str):
output_string = unicode(output_string, 'utf-8') # The beauty of python 2
meta_file.write(output_string)
logger.info("removing temp file %s", temp_file.name)
return cache_path
import tempfile
import tarfile
import json
import shutil
PRETRAINED_MODEL_ARCHIVE_MAP = {
'bert-base-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased.tar.gz",
'bert-large-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased.tar.gz",
'bert-base-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased.tar.gz",
'bert-large-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased.tar.gz",
'bert-base-multilingual-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased.tar.gz",
'bert-base-multilingual-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased.tar.gz",
'bert-base-chinese': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese.tar.gz",
}
BERT_CONFIG_NAME = 'bert_config.json'
TF_WEIGHTS_NAME = 'model.ckpt'
class BertPreTrainedModel(nn.Module):
""" An abstract class to handle weights initialization and
a simple interface for dowloading and loading pretrained models.
"""
def __init__(self, config, *inputs, **kwargs):
super(BertPreTrainedModel, self).__init__()
if not isinstance(config, BertConfig):
raise ValueError(
"Parameter config in `{}(config)` should be an instance of class `BertConfig`. "
"To create a model from a Google pretrained model use "
"`model = {}.from_pretrained(PRETRAINED_MODEL_NAME)`".format(
self.__class__.__name__, self.__class__.__name__
))
self.config = config
def init_bert_weights(self, module):
""" Initialize the weights.
"""
if isinstance(module, (nn.Linear, nn.Embedding)):
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
elif isinstance(module, BertLayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0)
if isinstance(module, nn.Linear) and module.bias is not None:
module.bias.data.zero_()
@classmethod
def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs):
"""
Instantiate a BertPreTrainedModel from a pre-trained model file or a pytorch state dict.
Download and cache the pre-trained model file if needed.
Params:
pretrained_model_name_or_path: either:
- a str with the name of a pre-trained model to load selected in the list of:
. `bert-base-uncased`
. `bert-large-uncased`
. `bert-base-cased`
. `bert-large-cased`
. `bert-base-multilingual-uncased`
. `bert-base-multilingual-cased`
. `bert-base-chinese`
- a path or url to a pretrained model archive containing:
. `bert_config.json` a configuration file for the model
. `pytorch_model.bin` a PyTorch dump of a BertForPreTraining instance
- a path or url to a pretrained model archive containing:
. `bert_config.json` a configuration file for the model
. `model.chkpt` a TensorFlow checkpoint
from_tf: should we load the weights from a locally saved TensorFlow checkpoint
cache_dir: an optional path to a folder in which the pre-trained models will be cached.
state_dict: an optional state dictionnary (collections.OrderedDict object) to use instead of Google pre-trained models
*inputs, **kwargs: additional input for the specific Bert class
(ex: num_labels for BertForSequenceClassification)
"""
state_dict = kwargs.get('state_dict', None)
kwargs.pop('state_dict', None)
cache_dir = kwargs.get('cache_dir', None)
kwargs.pop('cache_dir', None)
from_tf = kwargs.get('from_tf', False)
kwargs.pop('from_tf', None)
if pretrained_model_name_or_path in PRETRAINED_MODEL_ARCHIVE_MAP:
archive_file = PRETRAINED_MODEL_ARCHIVE_MAP[pretrained_model_name_or_path]
else:
archive_file = pretrained_model_name_or_path
# redirect to the cache, if necessary
try:
resolved_archive_file = cached_path(archive_file, cache_dir=cache_dir)
except EnvironmentError:
logger.error(
"Model name '{}' was not found in model name list ({}). "
"We assumed '{}' was a path or url but couldn't find any file "
"associated to this path or url.".format(
pretrained_model_name_or_path,
', '.join(PRETRAINED_MODEL_ARCHIVE_MAP.keys()),
archive_file))
return None
if resolved_archive_file == archive_file:
logger.info("loading archive file {}".format(archive_file))
else:
logger.info("loading archive file {} from cache at {}".format(
archive_file, resolved_archive_file))
tempdir = None
if os.path.isdir(resolved_archive_file) or from_tf:
serialization_dir = resolved_archive_file
else:
# Extract archive to temp dir
tempdir = tempfile.mkdtemp()
logger.info("extracting archive file {} to temp dir {}".format(
resolved_archive_file, tempdir))
with tarfile.open(resolved_archive_file, 'r:gz') as archive:
archive.extractall(tempdir)
serialization_dir = tempdir
# Load config
config_file = os.path.join(serialization_dir, CONFIG_NAME)
if not os.path.exists(config_file):
# Backward compatibility with old naming format
config_file = os.path.join(serialization_dir, BERT_CONFIG_NAME)
config = BertConfig.from_json_file(config_file)
logger.info("Model config {}".format(config))
# Instantiate model.
model = cls(config, *inputs, **kwargs)
if state_dict is None and not from_tf:
weights_path = os.path.join(serialization_dir, WEIGHTS_NAME)
state_dict = torch.load(weights_path, map_location='cpu')
if tempdir:
# Clean up temp dir
shutil.rmtree(tempdir)
if from_tf:
# Directly load from a TensorFlow checkpoint
weights_path = os.path.join(serialization_dir, TF_WEIGHTS_NAME)
return load_tf_weights_in_bert(model, weights_path)
# Load from a PyTorch state_dict
old_keys = []
new_keys = []
for key in state_dict.keys():