-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain-AMEX.py
2000 lines (1645 loc) · 95.1 KB
/
main-AMEX.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
#
# SPDX-FileCopyrightText: 2020 SAP SE or an SAP affiliate company
#
# SPDX-License-Identifier: Apache-2.0
#
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team., 2019 Intelligent Systems Lab, University of Oxford, SAP SE
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""BERT finetuning runner."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import os
sys.path.append(os.getcwd())
sys.path.append("/home/ubuntu/CommonsenseTransformer/transformers/src/")
from rapidfuzz import fuzz
from rapidfuzz import process
from data_reader import InputExample, DataProcessor
import wandb
from scorer import scorer
from torch import nn, optim
from transformers import PYTORCH_PRETRAINED_BERT_CACHE
from transformers import AdamW, get_linear_schedule_with_warmup
from transformers.modeling_electra import ElectraForMaskedLM, ElectraGeneratorPredictions
from transformers import ElectraTokenizer, ElectraModel, ElectraConfig, ElectraPreTrainedModel
from transformers.modeling_roberta import RobertaLMHead
from transformers import RobertaTokenizer, RobertaModel, RobertaConfig
from transformers.modeling_bert import BertOnlyMLMHead
from transformers import BertPreTrainedModel, BertModel
from transformers import BertTokenizer
from torch.nn import functional as F
from torch.utils.data.distributed import DistributedSampler
from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
from torch.nn import CrossEntropyLoss
import torch
import numpy as np
import re
from tqdm import tqdm, trange
import pickle
import random
import argparse
import logging
import copy
import json
import csv
import random
#from transformers.modeling_bert import RobertaOnlyMLMHead
#from transformers import BertAdam
wandb.init(project="AMEx-MultiTask")
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%m/%d/%Y %H:%M:%S',
level=logging.INFO)
logger = logging.getLogger(__name__)
ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP = {
'roberta-base': "https://s3.amazonaws.com/models.huggingface.co/bert/roberta-base-pytorch_model.bin",
'roberta-large': "https://s3.amazonaws.com/models.huggingface.co/bert/roberta-large-pytorch_model.bin",
'roberta-large-mnli': "https://s3.amazonaws.com/models.huggingface.co/bert/roberta-large-mnli-pytorch_model.bin",
'distilroberta-base': "https://s3.amazonaws.com/models.huggingface.co/bert/distilroberta-base-pytorch_model.bin",
'roberta-base-openai-detector': "https://s3.amazonaws.com/models.huggingface.co/bert/roberta-base-openai-detector-pytorch_model.bin",
'roberta-large-openai-detector': "https://s3.amazonaws.com/models.huggingface.co/bert/roberta-large-openai-detector-pytorch_model.bin",
}
ELECTRA_PRETRAINED_MODEL_ARCHIVE_MAP = {
"google/electra-small-generator": "https://cdn.huggingface.co/google/electra-small-generator/pytorch_model.bin",
"google/electra-base-generator": "https://cdn.huggingface.co/google/electra-base-generator/pytorch_model.bin",
"google/electra-large-generator": "https://cdn.huggingface.co/google/electra-large-generator/pytorch_model.bin",
"google/electra-small-discriminator": "https://cdn.huggingface.co/google/electra-small-discriminator/pytorch_model.bin",
"google/electra-base-discriminator": "https://cdn.huggingface.co/google/electra-base-discriminator/pytorch_model.bin",
"google/electra-large-discriminator": "https://cdn.huggingface.co/google/electra-large-discriminator/pytorch_model.bin",
}
class EntropyLoss(nn.Module):
''' Module to compute entropy loss '''
def __init__(self, normalize):
super(EntropyLoss, self).__init__()
self.normalize = normalize
def forward(self, x):
eps = 0.00001
b = F.softmax(x, dim=1) * torch.log2(F.softmax(x, dim=1)+eps)
b = b.sum(-1)
#if any(b.detach().cpu().numpy > 1.0):
# print(b)
if self.normalize:
b = torch.div(b, np.log2(x.shape[1]))
#print(b.mean())
b = -1.0 * b.mean()
return b
entropy_loss = EntropyLoss(normalize=True)
def entroppy(x):
b = F.softmax(x, dim=1) * F.log_softmax(x, dim=1)
b = -1.0 * b.sum(-1).mean()
return b
#class BertForMaskedLM(PreTrainedBertModel):
# """BERT model with the masked language modeling head.
#
# The code is taken from pytorch_pretrain_bert/modeling.py, but the loss function has been changed to return
# loss for each example separately.
# """
# def __init__(self, config):
# super(BertForMaskedLM, self).__init__(config)
# self.bert = BertModel(config)
# self.cls = BertOnlyMLMHead(config, self.bert.embeddings.word_embeddings.weight)
# self.apply(self.init_bert_weights)
#
# def forward(self, input_ids, token_type_ids=None, attention_mask=None, masked_lm_labels=None):
# sequence_output, _,attention = self.bert(input_ids, token_type_ids, attention_mask,
# output_all_encoded_layers=False)
# prediction_scores = self.cls(sequence_output)
#
# if masked_lm_labels is not None:
# loss_fct = CrossEntropyLoss(ignore_index=-1,reduction='none')
# masked_lm_loss = loss_fct(prediction_scores.permute(0,2,1), masked_lm_labels)
# return torch.mean(masked_lm_loss,1), attention
# else:
# return prediction_scores
class BertForMaskedLM(BertPreTrainedModel):
r"""
**masked_lm_labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:
Labels for computing the masked language modeling loss.
Indices should be in ``[-1, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring)
Tokens with indices set to ``-1`` are ignored (masked), the loss is only computed for the tokens with labels
in ``[0, ..., config.vocab_size]``
**lm_labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:
Labels for computing the left-to-right language modeling loss (next word prediction).
Indices should be in ``[-1, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring)
Tokens with indices set to ``-1`` are ignored (masked), the loss is only computed for the tokens with labels
in ``[0, ..., config.vocab_size]``
Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:
**masked_lm_loss**: (`optional`, returned when ``masked_lm_labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:
Masked language modeling loss.
**ltr_lm_loss**: (`optional`, returned when ``lm_labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:
Next token prediction loss.
**prediction_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, config.vocab_size)``
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
**hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)
list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)
of shape ``(batch_size, sequence_length, hidden_size)``:
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
**attentions**: (`optional`, returned when ``config.output_attentions=True``)
list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
Examples::
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertForMaskedLM.from_pretrained('bert-base-uncased')
input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1
outputs = model(input_ids, masked_lm_labels=input_ids)
loss, prediction_scores = outputs[:2]
"""
def __init__(self, config):
super(BertForMaskedLM, self).__init__(config)
self.bert = BertModel(config)
self.cls = BertOnlyMLMHead(config)
self.init_weights()
def get_output_embeddings(self):
return self.cls.predictions.decoder
def forward(self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None,
masked_lm_labels=None, encoder_hidden_states=None, encoder_attention_mask=None, lm_labels=None, ):
outputs = self.bert(input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask)
sequence_output = outputs[0]
prediction_scores = self.cls(sequence_output)
# Add hidden states and attention if they are here
outputs = (prediction_scores,) + outputs[2:]
# Although this may seem awkward, BertForMaskedLM supports two scenarios:
# 1. If a tensor that contains the indices of masked labels is provided,
# the cross-entropy is the MLM cross-entropy that measures the likelihood
# of predictions for masked words.
# 2. If `lm_labels` is provided we are in a causal scenario where we
# try to predict the next token for each input in the decoder.
if masked_lm_labels is not None:
# -1 index = padding token
loss_fct = CrossEntropyLoss(ignore_index=-1, reduction='none')
#logger.info(prediction_scores.permute(0,2,1).shape)
#logger.info(masked_lm_labels.shape)
masked_lm_loss = loss_fct(
prediction_scores.permute(0, 2, 1), masked_lm_labels)
#print((masked_lm_labels > -1).sum(dim=1))
#print(torch.mean(masked_lm_loss,1).shape)
#print(torch.div(torch.mean(masked_lm_loss,1),(masked_lm_labels > -1).sum(dim=1,dtype=torch.float32)).shape)
#logger.info(masked_lm_loss.shape)
#outputs = (torch.mean(masked_lm_loss,1),) + outputs
masked_lm_loss_normalized = torch.div(torch.mean(
masked_lm_loss, 1), (masked_lm_labels > -1).sum(dim=1, dtype=torch.float32))
masked_lm_loss_normalized[torch.isnan(
masked_lm_loss_normalized)] = 0.0
outputs = (masked_lm_loss_normalized,) + outputs
if lm_labels is not None:
# we are doing next-token prediction; shift prediction scores and input ids by one
prediction_scores = prediction_scores[:, :-1, :].contiguous()
lm_labels = lm_labels[:, 1:].contiguous()
loss_fct = CrossEntropyLoss(ignore_index=-1)
ltr_lm_loss = loss_fct(
prediction_scores.view(-1, self.config.vocab_size), lm_labels.view(-1))
outputs = (ltr_lm_loss,) + outputs
# (masked_lm_loss), (ltr_lm_loss), prediction_scores, (hidden_states), (attentions)
return outputs
class ElectraForMaskedLM(ElectraPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.electra = ElectraModel(config)
self.generator_predictions = ElectraGeneratorPredictions(config)
self.generator_lm_head = nn.Linear(
config.embedding_size, config.vocab_size)
self.init_weights()
def get_output_embeddings(self):
return self.generator_lm_head
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
masked_lm_labels=None,
):
r"""
masked_lm_labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
Labels for computing the masked language modeling loss.
Indices should be in ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring)
Tokens with indices set to ``-100`` are ignored (masked), the loss is only computed for the tokens with labels
in ``[0, ..., config.vocab_size]``
Returns:
:obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.ElectraConfig`) and inputs:
masked_lm_loss (`optional`, returned when ``masked_lm_labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:
Masked language modeling loss.
prediction_scores (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, config.vocab_size)`)
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``):
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``):
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
Examples::
from transformers import ElectraTokenizer, ElectraForMaskedLM
import torch
tokenizer = ElectraTokenizer.from_pretrained('google/electra-small-generator')
model = ElectraForMaskedLM.from_pretrained('google/electra-small-generator')
input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1
outputs = model(input_ids, masked_lm_labels=input_ids)
loss, prediction_scores = outputs[:2]
"""
generator_hidden_states = self.electra(
input_ids, attention_mask, token_type_ids, position_ids, head_mask, inputs_embeds
)
generator_sequence_output = generator_hidden_states[0]
prediction_scores = self.generator_predictions(
generator_sequence_output)
prediction_scores = self.generator_lm_head(prediction_scores)
output = (prediction_scores,)
# Masked language modeling softmax layer
if masked_lm_labels is not None:
#loss_fct = nn.CrossEntropyLoss() # -100 index = padding token
#loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1))
# -1 index = padding token
loss_fct = CrossEntropyLoss(ignore_index=-1, reduction='none')
masked_lm_loss = loss_fct(
prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1))
masked_lm_loss = loss_fct(
prediction_scores.permute(0, 2, 1), masked_lm_labels)
masked_lm_loss_normalized = torch.div(torch.mean(
masked_lm_loss, 1), (masked_lm_labels > -1).sum(dim=1, dtype=torch.float32))
masked_lm_loss_normalized[torch.isnan(
masked_lm_loss_normalized)] = 0.0
output = (masked_lm_loss_normalized,) + output
#output = (loss,) + output
output += generator_hidden_states[1:]
return output
class RobertaForMaskedLM(BertPreTrainedModel):
r"""
**masked_lm_labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:
Labels for computing the masked language modeling loss.
Indices should be in ``[-1, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring)
Tokens with indices set to ``-1`` are ignored (masked), the loss is only computed for the tokens with labels
in ``[0, ..., config.vocab_size]``
Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:
**loss**: (`optional`, returned when ``masked_lm_labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:
Masked language modeling loss.
**prediction_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, config.vocab_size)``
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
**hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)
list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)
of shape ``(batch_size, sequence_length, hidden_size)``:
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
**attentions**: (`optional`, returned when ``config.output_attentions=True``)
list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
Examples::
tokenizer = RobertaTokenizer.from_pretrained('roberta-base')
model = RobertaForMaskedLM.from_pretrained('roberta-base')
input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1
outputs = model(input_ids, masked_lm_labels=input_ids)
loss, prediction_scores = outputs[:2]
"""
config_class = RobertaConfig
pretrained_model_archive_map = ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP
base_model_prefix = "roberta"
def __init__(self, config):
super(RobertaForMaskedLM, self).__init__(config)
self.roberta = RobertaModel(config)
self.lm_head = RobertaLMHead(config)
self.init_weights()
def get_output_embeddings(self):
return self.lm_head.decoder
def forward(self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None,
masked_lm_labels=None):
outputs = self.roberta(input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds)
sequence_output = outputs[0]
prediction_scores = self.lm_head(sequence_output)
# Add hidden states and attention if they are here
outputs = (prediction_scores,) + outputs[2:]
if masked_lm_labels is not None:
#loss_fct = CrossEntropyLoss(ignore_index=-1)
# -1 index = padding token
loss_fct = CrossEntropyLoss(ignore_index=-1, reduction='none')
masked_lm_loss = loss_fct(
prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1))
masked_lm_loss = loss_fct(
prediction_scores.permute(0, 2, 1), masked_lm_labels)
masked_lm_loss_normalized = torch.div(torch.mean(
masked_lm_loss, 1), (masked_lm_labels > -1).sum(dim=1, dtype=torch.float32))
masked_lm_loss_normalized[torch.isnan(
masked_lm_loss_normalized)] = 0.0
outputs = (masked_lm_loss_normalized,) + outputs
# (masked_lm_loss), prediction_scores, (hidden_states), (attentions)
return outputs
def find_sub_list(sl, l):
results = []
sll = len(sl)
for ind in (i for i, e in enumerate(l) if e == sl[0]):
if l[ind:ind+sll] == sl:
results.append((ind, ind+sll-1))
return results
class InputFeatures(object):
"""A single set of features of data."""
def __init__(self, input_ids_1, input_ids_2, attention_mask_1, attention_mask_2, type_1, type_2, masked_lm_1, masked_lm_2, start, end_1, end_2, source_start_token_1, source_end_token_1, source_start_token_2, source_end_token_2, a1_found, a1_start, a1_len, b1_start, b1_len, a2_found, a2_start, a2_len, b2_start, b2_len, mex, label):
self.input_ids_1 = input_ids_1
self.attention_mask_1 = attention_mask_1
self.type_1 = type_1
self.masked_lm_1 = masked_lm_1
#These are only used for train examples
self.input_ids_2 = input_ids_2
self.attention_mask_2 = attention_mask_2
self.type_2 = type_2
self.masked_lm_2 = masked_lm_2
self.start = start
self.end_1 = end_1
self.end_2 = end_2
self.source_start_token_1 = source_start_token_1
self.source_end_token_1 = source_end_token_1
self.source_start_token_2 = source_start_token_2
self.source_end_token_2 = source_end_token_2
self.a1_found = a1_found
self.a1_start = a1_start
self.a1_len = a1_len
self.b1_start = b1_start
self.b1_len = b1_len
self.a2_found = a2_found
self.a2_start = a2_start
self.a2_len = a2_len
self.b2_start = b2_start
self.b2_len = b2_len
self.mex = mex
self.label = label
def convert_examples_to_features_train(examples, max_seq_len, tokenizer, mode='oxford'):
"""Loads a data file into a list of `InputBatch`s."""
features = []
count = [0, 0]
for (ex_index, example) in enumerate(examples):
try:
# noisy annotation fix
# Hypen in candidates needs separate handling with insertion of dummy
remove_dummy = False
if example.candidate_a.find("'") > -1:
remove_dummy = True
example.text_a = example.text_a.replace(example.candidate_a, example.candidate_a.replace("'","###"))
if example.candidate_b.find("'") > -1:
remove_dummy = True
example.text_a = example.text_a.replace(example.candidate_b, example.candidate_b.replace("'","###"))
if ex_index == 26638: # ex_index == 10130 or ex_index == 6228 or ex_index == 1008: # 296
tmp = 1
# remove punction without dashand then split
word_list = example.text_a.lower().replace("'", " ").replace(",", "").replace(";", "").replace(".", "").replace("?", "").replace("!", "").replace(".", "").split()
if remove_dummy:
word_list = [x.replace("###","'") for x in word_list]
example.text_a = example.text_a.replace("###", "'")
if len(example.candidate_a.split())>1:
candidate_split = find_sub_list(example.candidate_a.lower().split(), word_list)
start_index = candidate_split[0][0]
end_index = candidate_split[0][1]+1
word_list[start_index:end_index] = [' '.join(word_list[start_index:end_index])]
if len(example.candidate_b.split())>1:
candidate_split = find_sub_list(example.candidate_b.lower().split(), word_list)
start_index = candidate_split[0][0]
end_index = candidate_split[0][1]+1
word_list[start_index:end_index] = [' '.join(word_list[start_index:end_index])]
# check if the first candidate is in the word list
if not example.candidate_a.lower() in word_list:
example.candidate_a = process.extract(example.candidate_a, word_list, limit=1)[0][0]
if not example.candidate_b.lower() in word_list:
example.candidate_b = process.extract(example.candidate_b, word_list, limit=1)[0][0]
tokens_sent = tokenizer.tokenize(
example.text_a.lower(), add_prefix_space=True)
tokens_a = tokenizer.tokenize(
example.candidate_a.lower(), add_prefix_space=True)
tokens_b = tokenizer.tokenize(
example.candidate_b.lower(), add_prefix_space=True)
if len(tokens_a) == len(tokens_b):
count[0] = count[0]+1
else:
count[1] = count[1]+1
tokens_1, type_1, attention_mask_1, masked_lm_1 = [], [], [], []
tokens_2, type_2, attention_mask_2, masked_lm_2 = [], [], [], []
tokens_1.append("<s>")
tokens_2.append("<s>")
for token in tokens_sent:
if token.find("_") > -1:
start = len(tokens_1)
if mode == 'oxford':
tokens_1.extend(
["<mask>" for _ in range(len(tokens_a))])
tokens_2.extend(
["<mask>" for _ in range(len(tokens_b))])
else:
tokens_1.append("<mask>")
tokens_2.append("<mask>")
end_1 = len(tokens_1)
end_2 = len(tokens_2)
else:
tokens_1.append(token)
tokens_2.append(token)
except:
logger.info("Issue with item "+str(ex_index)+"...")
continue
token_idx_1 = []
token_idx_2 = []
token_counter_1 = 0
token_counter_2 = 0
find_tokens_a = True
find_tokens_b = True
for idx, token in enumerate(tokens_a):
if (find_tokens_a and token.lower() == tokens_a[token_counter_1].lower()):
token_idx_1.append(idx)
token_counter_1 += 1
if (len(token_idx_1) >= len(tokens_a)):
find_tokens_a = False
elif find_tokens_a:
token_idx_1 = []
token_counter_1 = 0
for idx, token in enumerate(tokens_b):
if (find_tokens_b and token.lower() == tokens_b[token_counter_2].lower()):
token_idx_2.append(idx)
token_counter_2 += 1
if (len(token_idx_2) >= len(tokens_b)):
find_tokens_b = False
elif find_tokens_b:
token_idx_2 = []
token_counter_2 = 0
tokens_1 = tokens_1[:max_seq_len-1] # -1 because of [SEP]
tokens_2 = tokens_2[:max_seq_len-1]
if tokens_1[-1] != "</s>":
tokens_1.append("</s>")
if tokens_2[-1] != "</s>":
tokens_2.append("</s>")
type_1 = max_seq_len*[0] # We do not do any inference.
type_2 = max_seq_len*[0] # These embeddings can thus be ignored
attention_mask_1 = (len(tokens_1)*[1]) + \
((max_seq_len-len(tokens_1))*[0])
attention_mask_2 = (len(tokens_2)*[1]) + \
((max_seq_len-len(tokens_2))*[0])
#sentences
input_ids_1 = tokenizer.convert_tokens_to_ids(tokens_1)
input_ids_2 = tokenizer.convert_tokens_to_ids(tokens_2)
#replacements
input_ids_a = tokenizer.convert_tokens_to_ids(tokens_a)
input_ids_b = tokenizer.convert_tokens_to_ids(tokens_b)
# max two findings
a1_found = []
a1_loc = [-1, -1]
a1_len = [-1, -1]
b1_loc = [-1, -1]
b1_len = [-1, -1]
a2_found = []
a2_loc = [-1, -1]
a2_len = [-1, -1]
b2_loc = [-1, -1]
b2_len = [-1, -1]
# skip first and last token for matching
#try:
ls = find_sub_list([i.encode('ascii', 'ignore') for i in tokens_a], [
i.encode('ascii', 'ignore') for i in tokens_1])
# remove prefix matches if there are any
if example.candidate_b.startswith(example.candidate_a):
support_ls = find_sub_list([i.encode('ascii', 'ignore') for i in tokens_b], [
i.encode('ascii', 'ignore') for i in tokens_1])
start_support_ls = [x[0] for x in support_ls]
ls = [x for x in ls if x[0] not in start_support_ls]
a1_found.append(len(ls))
for idx, src in enumerate(ls):
if idx < 2:
a1_loc[idx] = src[0]
a1_len[idx] = src[1]+1
ls = find_sub_list([i.encode('ascii', 'ignore') for i in tokens_b], [
i.encode('ascii', 'ignore') for i in tokens_1])
# remove prefix matches if there are any
if example.candidate_a.startswith(example.candidate_b):
support_ls = find_sub_list([i.encode('ascii', 'ignore') for i in tokens_a], [
i.encode('ascii', 'ignore') for i in tokens_1])
start_support_ls = [x[0] for x in support_ls]
ls = [x for x in ls if x[0] not in start_support_ls]
if len(ls) == 0:
continue
a1_found.append(len(ls))
for idx, src in enumerate(ls):
try:
if idx < 2:
b1_loc[idx] = src[0]
b1_len[idx] = src[1]+1
except:
tmp = 1
if len(ls) == 0:
print([i.encode('ascii', 'ignore') for i in tokens_b])
print([i.encode('ascii', 'ignore') for i in tokens_1])
continue
ls = find_sub_list([i.encode('ascii', 'ignore') for i in tokens_a], [
i.encode('ascii', 'ignore') for i in tokens_2])
# remove prefix matches if there are any
if example.candidate_b.startswith(example.candidate_a):
support_ls = find_sub_list([i.encode('ascii', 'ignore') for i in tokens_b], [
i.encode('ascii', 'ignore') for i in tokens_2])
start_support_ls = [x[0] for x in support_ls]
ls = [x for x in ls if x[0] not in start_support_ls]
if len(ls) == 0:
continue
a2_found.append(len(ls))
for idx, src in enumerate(ls):
if idx < 2:
a2_loc[idx] = src[0]
a2_len[idx] = src[1]+1
ls = find_sub_list([i.encode('ascii', 'ignore') for i in tokens_b], [
i.encode('ascii', 'ignore') for i in tokens_2])
# remove prefix matches if there are any
if example.candidate_a.startswith(example.candidate_b):
support_ls = find_sub_list([i.encode('ascii', 'ignore') for i in tokens_a], [
i.encode('ascii', 'ignore') for i in tokens_2])
start_support_ls = [x[0] for x in support_ls]
ls = [x for x in ls if x[0] not in start_support_ls]
if len(ls) == 0:
continue
a2_found.append(len(ls))
for idx, src in enumerate(ls):
if idx < 2:
b2_loc[idx] = src[0]
b2_len[idx] = src[1]+1
for token in tokens_1:
if token == "<mask>":
if len(input_ids_a) <= 0:
continue # broken case
masked_lm_1.append(input_ids_a[0])
input_ids_a = input_ids_a[1:]
else:
masked_lm_1.append(-1)
while len(masked_lm_1) < max_seq_len:
masked_lm_1.append(-1)
for token in tokens_2:
if token == "<mask>":
if len(input_ids_b) <= 0:
continue # broken case
masked_lm_2.append(input_ids_b[0])
input_ids_b = input_ids_b[1:]
else:
masked_lm_2.append(-1)
while len(masked_lm_2) < max_seq_len:
masked_lm_2.append(-1)
# Zero-pad up to the sequence length.
while len(input_ids_1) < max_seq_len:
input_ids_1.append(0)
while len(input_ids_2) < max_seq_len:
input_ids_2.append(0)
assert len(input_ids_1) == max_seq_len
assert len(input_ids_2) == max_seq_len
assert len(attention_mask_1) == max_seq_len
assert len(attention_mask_2) == max_seq_len
assert len(type_1) == max_seq_len
assert len(type_2) == max_seq_len
assert len(masked_lm_1) == max_seq_len
assert len(masked_lm_2) == max_seq_len
#if len(tokens_a) == len(tokens_b):
#if example.text_a.lower().find("the monsters at the haunted house") > -1:
# tmp = 1
if input_ids_1[1] == 145 and input_ids_1[2] == 10 and input_ids_1[3] == 3254 and input_ids_1[4] == 16:
tmp = 1
features.append(
InputFeatures(input_ids_1=input_ids_1,
input_ids_2=input_ids_2,
attention_mask_1=attention_mask_1,
attention_mask_2=attention_mask_2,
type_1=type_1,
type_2=type_2,
masked_lm_1=masked_lm_1,
masked_lm_2=masked_lm_2, start=start, end_1=end_1, end_2=end_2, source_start_token_1=token_idx_1[0], source_end_token_1=token_idx_1[-1], source_start_token_2=token_idx_2[0], source_end_token_2=token_idx_2[-1], a1_found=a1_found, a1_start=a1_loc, a1_len=a1_len, b1_start=b1_loc, b1_len=b1_len, a2_found=a2_found, a2_start=a2_loc, a2_len=a2_len, b2_start=b2_loc, b2_len=b2_len, mex=example.mex, label=example.label))
logger.info('Ratio: '+str(count[0]/(count[0]+count[1])))
return features
def convert_examples_to_features_evaluate(examples, max_seq_len, tokenizer):
"""Loads a data file into a list of `InputBatch`s."""
features = []
for (ex_index, example) in enumerate(examples):
# , add_prefix_space=True)
tokens_a = tokenizer.tokenize(example.candidate_a)
tokens_sent = tokenizer.tokenize(
example.text_a) # , add_prefix_space=True)
tokens_1, type_1, attention_mask_1, masked_lm_1 = [], [], [], []
tokens_1.append("<s>")
for token in tokens_sent:
if token.find("_") > -1:
tokens_1.extend(["<mask>" for _ in range(len(tokens_a))])
else:
tokens_1.append(token)
tokens_1 = tokens_1[:max_seq_len-1] # -1 because of [SEP]
if tokens_1[-1] != "</s>":
tokens_1.append("</s>")
type_1 = max_seq_len*[0]
attention_mask_1 = (len(tokens_1)*[1]) + \
((max_seq_len-len(tokens_1))*[0])
#sentences
input_ids_1 = tokenizer.convert_tokens_to_ids(tokens_1)
#replacements
input_ids_a = tokenizer.convert_tokens_to_ids(tokens_a)
for token in tokens_1:
if token == "<mask>":
if len(input_ids_a) <= 0:
continue # broken case
masked_lm_1.append(input_ids_a[0])
input_ids_a = input_ids_a[1:]
else:
masked_lm_1.append(-1)
while len(masked_lm_1) < max_seq_len:
masked_lm_1.append(-1)
# Zero-pad up to the sequence length.
while len(input_ids_1) < max_seq_len:
input_ids_1.append(0)
assert len(input_ids_1) == max_seq_len
assert len(attention_mask_1) == max_seq_len
assert len(type_1) == max_seq_len
assert len(masked_lm_1) == max_seq_len
features.append(
InputFeatures(input_ids_1=input_ids_1,
input_ids_2=None,
attention_mask_1=attention_mask_1,
attention_mask_2=None,
type_1=type_1,
type_2=None,
masked_lm_1=masked_lm_1,
masked_lm_2=None, start=None, end_1=None, end_2=None, source_start_token_1=None, source_end_token_1=None, source_start_token_2=None, source_end_token_2=None, a1_found=None, a1_start=None, a1_len=None, b1_start=None, b1_len=None, a2_found=None, a2_start=None, a2_len=None, b2_start=None, b2_len=None, mex=None, label=example.label))
return features
def convert_examples_to_features_train_bert(examples, max_seq_len, tokenizer, mode='oxford'):
"""Loads a data file into a list of `InputBatch`s."""
features = []
count = [0, 0]
for (ex_index, example) in enumerate(examples):
tokens_sent = tokenizer.tokenize(example.text_a)
tokens_a = tokenizer.tokenize(example.candidate_a)
tokens_b = tokenizer.tokenize(example.candidate_b)
if len(tokens_a) == len(tokens_b):
count[0] = count[0]+1
else:
count[1] = count[1]+1
tokens_1, type_1, attention_mask_1, masked_lm_1 = [], [], [], []
tokens_2, type_2, attention_mask_2, masked_lm_2 = [], [], [], []
tokens_1.append("[CLS]")
tokens_2.append("[CLS]")
for token in tokens_sent:
if token == '_': # .find("_")>=-1:
start = len(tokens_1)
if mode == 'oxford':
tokens_1.extend(["[MASK]" for _ in range(len(tokens_a))])
tokens_2.extend(["[MASK]" for _ in range(len(tokens_b))])
else:
tokens_1.append("[MASK]")
tokens_2.append("[MASK]")
end_1 = len(tokens_1)
end_2 = len(tokens_2)
else:
tokens_1.append(token)
tokens_2.append(token)
token_idx_1 = []
token_idx_2 = []
token_counter_1 = 0
token_counter_2 = 0
find_tokens_a = True
find_tokens_b = True
for idx, token in enumerate(tokens_a):
if (find_tokens_a and token.lower() == tokens_a[token_counter_1].lower()):
token_idx_1.append(idx)
token_counter_1 += 1
if (len(token_idx_1) >= len(tokens_a)):
find_tokens_a = False
elif find_tokens_a:
token_idx_1 = []
token_counter_1 = 0
for idx, token in enumerate(tokens_b):
if (find_tokens_b and token.lower() == tokens_b[token_counter_2].lower()):
token_idx_2.append(idx)
token_counter_2 += 1
if (len(token_idx_2) >= len(tokens_b)):
find_tokens_b = False
elif find_tokens_b:
token_idx_2 = []
token_counter_2 = 0
tokens_1 = tokens_1[:max_seq_len-1] # -1 because of [SEP]
tokens_2 = tokens_2[:max_seq_len-1]
if tokens_1[-1] != "[SEP]":
tokens_1.append("[SEP]")
if tokens_2[-1] != "[SEP]":
tokens_2.append("[SEP]")
type_1 = max_seq_len*[0] # We do not do any inference.
type_2 = max_seq_len*[0] # These embeddings can thus be ignored
attention_mask_1 = (len(tokens_1)*[1]) + \
((max_seq_len-len(tokens_1))*[0])
attention_mask_2 = (len(tokens_2)*[1]) + \
((max_seq_len-len(tokens_2))*[0])
#sentences
input_ids_1 = tokenizer.convert_tokens_to_ids(tokens_1)
input_ids_2 = tokenizer.convert_tokens_to_ids(tokens_2)
#replacements
input_ids_a = tokenizer.convert_tokens_to_ids(tokens_a)
input_ids_b = tokenizer.convert_tokens_to_ids(tokens_b)
for token in tokens_1:
if token == "[MASK]":
if len(input_ids_a) <= 0:
continue # broken case
masked_lm_1.append(input_ids_a[0])
input_ids_a = input_ids_a[1:]
else:
masked_lm_1.append(-1)
while len(masked_lm_1) < max_seq_len:
masked_lm_1.append(-1)
for token in tokens_2:
if token == "[MASK]":
if len(input_ids_b) <= 0:
continue # broken case
masked_lm_2.append(input_ids_b[0])
input_ids_b = input_ids_b[1:]
else:
masked_lm_2.append(-1)
while len(masked_lm_2) < max_seq_len:
masked_lm_2.append(-1)
# Zero-pad up to the sequence length.
while len(input_ids_1) < max_seq_len:
input_ids_1.append(0)
while len(input_ids_2) < max_seq_len:
input_ids_2.append(0)
assert len(input_ids_1) == max_seq_len
assert len(input_ids_2) == max_seq_len
assert len(attention_mask_1) == max_seq_len
assert len(attention_mask_2) == max_seq_len
assert len(type_1) == max_seq_len
assert len(type_2) == max_seq_len
assert len(masked_lm_1) == max_seq_len
assert len(masked_lm_2) == max_seq_len
#if len(tokens_a) == len(tokens_b):
features.append(
InputFeatures(input_ids_1=input_ids_1,
input_ids_2=input_ids_2,
attention_mask_1=attention_mask_1,
attention_mask_2=attention_mask_2,
type_1=type_1,
type_2=type_2,
masked_lm_1=masked_lm_1,
masked_lm_2=masked_lm_2, start=start, end_1=end_1, end_2=end_2, source_start_token_1=token_idx_1[0], source_end_token_1=token_idx_1[-1], source_start_token_2=token_idx_2[0], source_end_token_2=token_idx_2[-1]))
logger.info('Ratio: '+str(count[0]/(count[0]+count[1])))
return features
def convert_examples_to_features_evaluate_bert(examples, max_seq_len, tokenizer):
"""Loads a data file into a list of `InputBatch`s."""
features = []
for (ex_index, example) in enumerate(examples):
tokens_a = tokenizer.tokenize(example.candidate_a)
tokens_sent = tokenizer.tokenize(example.text_a)
tokens_1, type_1, attention_mask_1, masked_lm_1 = [], [], [], []
tokens_1.append("[CLS]")
for token in tokens_sent:
if token == "_":
tokens_1.extend(["[MASK]" for _ in range(len(tokens_a))])
else:
tokens_1.append(token)
tokens_1 = tokens_1[:max_seq_len-1] # -1 because of [SEP]
if tokens_1[-1] != "[SEP]":
tokens_1.append("[SEP]")