forked from thunlp/PL-Marker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun_levitatedpair.py
1150 lines (913 loc) · 49 KB
/
run_levitatedpair.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
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# 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.
""" Finetuning the library models for sequence classification on GLUE (Bert, XLM, XLNet, RoBERTa)."""
from __future__ import absolute_import, division, print_function
import argparse
import glob
import logging
import os
import random
from collections import defaultdict
import re
import shutil
import numpy as np
import torch
from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler,
TensorDataset)
from torch.utils.data.distributed import DistributedSampler
from tensorboardX import SummaryWriter
from tqdm import tqdm, trange
import time
from transformers import (WEIGHTS_NAME, BertConfig,
BertTokenizer,
RobertaConfig,
RobertaTokenizer,
get_linear_schedule_with_warmup,
AdamW,
AlbertForACEBothSub,
AlbertConfig,
AlbertTokenizer,
BertForACEBothOneDropoutLeviPair,
)
from transformers import AutoTokenizer
from torch.utils.data import TensorDataset, Dataset
import json
import pickle
import numpy as np
import unicodedata
import itertools
import timeit
from tqdm import tqdm
logger = logging.getLogger(__name__)
ALL_MODELS = sum((tuple(conf.pretrained_config_archive_map.keys()) for conf in (BertConfig, AlbertConfig)), ())
MODEL_CLASSES = {
'bert': (BertConfig, BertForACEBothOneDropoutLeviPair, BertTokenizer),
}
task_ner_labels = {
'ace04': ['FAC', 'WEA', 'LOC', 'VEH', 'GPE', 'ORG', 'PER'],
'ace05': ['FAC', 'WEA', 'LOC', 'VEH', 'GPE', 'ORG', 'PER'],
'scierc': ['Method', 'OtherScientificTerm', 'Task', 'Generic', 'Material', 'Metric'],
}
task_rel_labels = {
'ace04': ['PER-SOC', 'OTHER-AFF', 'ART', 'GPE-AFF', 'EMP-ORG', 'PHYS'],
'ace05': ['PER-SOC', 'ART', 'ORG-AFF', 'GEN-AFF', 'PHYS', 'PART-WHOLE'],
'scierc': ['PART-OF', 'USED-FOR', 'FEATURE-OF', 'CONJUNCTION', 'EVALUATE-FOR', 'HYPONYM-OF', 'COMPARE'],
}
class ACEDataset(Dataset):
def __init__(self, tokenizer, args=None, evaluate=False, do_test=False, max_pair_length=None):
if not evaluate:
file_path = os.path.join(args.data_dir, args.train_file)
else:
if do_test:
if args.test_file.find('models')==-1:
file_path = os.path.join(args.data_dir, args.test_file)
else:
file_path = args.test_file
else:
if args.dev_file.find('models')==-1:
file_path = os.path.join(args.data_dir, args.dev_file)
else:
file_path = args.dev_file
assert os.path.isfile(file_path)
self.file_path = file_path
self.tokenizer = tokenizer
self.max_seq_length = args.max_seq_length
self.max_pair_length = max_pair_length
self.max_entity_length = self.max_pair_length*4
self.evaluate = evaluate
self.use_typemarker = args.use_typemarker
self.local_rank = args.local_rank
self.args = args
self.model_type = args.model_type
self.no_sym = args.no_sym
if args.data_dir.find('ace05')!=-1:
self.ner_label_list = ['NIL', 'FAC', 'WEA', 'LOC', 'VEH', 'GPE', 'ORG', 'PER']
if args.no_sym:
label_list = ['PER-SOC', 'ART', 'ORG-AFF', 'GEN-AFF', 'PHYS', 'PART-WHOLE']
self.sym_labels = ['NIL']
self.label_list = self.sym_labels + label_list
else:
label_list = ['ART', 'ORG-AFF', 'GEN-AFF', 'PHYS', 'PART-WHOLE']
self.sym_labels = ['NIL', 'PER-SOC']
self.label_list = self.sym_labels + label_list
elif args.data_dir.find('ace04')!=-1:
self.ner_label_list = ['NIL', 'FAC', 'WEA', 'LOC', 'VEH', 'GPE', 'ORG', 'PER']
if args.no_sym:
label_list = ['PER-SOC', 'OTHER-AFF', 'ART', 'GPE-AFF', 'EMP-ORG', 'PHYS']
self.sym_labels = ['NIL']
self.label_list = self.sym_labels + label_list
else:
label_list = ['OTHER-AFF', 'ART', 'GPE-AFF', 'EMP-ORG', 'PHYS']
self.sym_labels = ['NIL', 'PER-SOC']
self.label_list = self.sym_labels + label_list
elif args.data_dir.find('scierc')!=-1:
self.ner_label_list = ['NIL', 'Method', 'OtherScientificTerm', 'Task', 'Generic', 'Material', 'Metric']
if args.no_sym:
label_list = ['CONJUNCTION', 'COMPARE', 'PART-OF', 'USED-FOR', 'FEATURE-OF', 'EVALUATE-FOR', 'HYPONYM-OF']
self.sym_labels = ['NIL']
self.label_list = self.sym_labels + label_list
else:
label_list = ['PART-OF', 'USED-FOR', 'FEATURE-OF', 'EVALUATE-FOR', 'HYPONYM-OF']
self.sym_labels = ['NIL', 'CONJUNCTION', 'COMPARE']
self.label_list = self.sym_labels + label_list
else:
assert (False)
self.global_predicted_ners = {}
self.initialize()
def initialize(self):
tokenizer = self.tokenizer
vocab_size = tokenizer.vocab_size
max_num_subwords = self.max_seq_length - 2
label_map = {label: i for i, label in enumerate(self.label_list)}
ner_label_map = {label: i for i, label in enumerate(self.ner_label_list)}
def tokenize_word(text):
if (
isinstance(tokenizer, RobertaTokenizer)
and (text[0] != "'")
and (len(text) != 1 or not self.is_punctuation(text))
):
return tokenizer.tokenize(text, add_prefix_space=True)
return tokenizer.tokenize(text)
f = open(self.file_path, "r", encoding='utf-8')
self.ner_tot_recall = 0
self.tot_recall = 0
self.data = []
self.ner_golden_labels = set([])
self.golden_labels = set([])
self.golden_labels_withner = set([])
maxR = 0
maxL = 0
for l_idx, line in enumerate(f):
data = json.loads(line)
if self.args.output_dir.find('test')!=-1:
if len(self.data) > 100:
break
# if len(self.data) > 100:
# break
sentences = data['sentences']
if 'predicted_ner' in data: # e2e predict
ners = data['predicted_ner']
else:
ners = data['ner']
std_ners = data['ner']
relations = data['relations']
for sentence_relation in relations:
for x in sentence_relation:
if x[4] in self.sym_labels[1:]:
self.tot_recall += 2
else:
self.tot_recall += 1
sentence_boundaries = [0]
words = []
L = 0
for i in range(len(sentences)):
L += len(sentences[i])
sentence_boundaries.append(L)
words += sentences[i]
tokens = [tokenize_word(w) for w in words]
subwords = [w for li in tokens for w in li]
maxL = max(maxL, len(subwords))
subword2token = list(itertools.chain(*[[i] * len(li) for i, li in enumerate(tokens)]))
token2subword = [0] + list(itertools.accumulate(len(li) for li in tokens))
subword_start_positions = frozenset(token2subword)
subword_sentence_boundaries = [sum(len(li) for li in tokens[:p]) for p in sentence_boundaries]
for n in range(len(subword_sentence_boundaries) - 1):
sentence_ners = ners[n]
sentence_relations = relations[n]
std_ner = std_ners[n]
std_entity_labels = {}
self.ner_tot_recall += len(std_ner)
for start, end, label in std_ner:
std_entity_labels[(start, end)] = label
self.ner_golden_labels.add( ((l_idx, n), (start, end), label) )
self.global_predicted_ners[(l_idx, n)] = list(sentence_ners)
doc_sent_start, doc_sent_end = subword_sentence_boundaries[n : n + 2]
left_length = doc_sent_start
right_length = len(subwords) - doc_sent_end
sentence_length = doc_sent_end - doc_sent_start
half_context_length = int((max_num_subwords - sentence_length) / 2)
if sentence_length < max_num_subwords:
if left_length < right_length:
left_context_length = min(left_length, half_context_length)
right_context_length = min(right_length, max_num_subwords - left_context_length - sentence_length)
else:
right_context_length = min(right_length, half_context_length)
left_context_length = min(left_length, max_num_subwords - right_context_length - sentence_length)
doc_offset = doc_sent_start - left_context_length
target_tokens = subwords[doc_offset : doc_sent_end + right_context_length]
target_tokens = [tokenizer.cls_token] + target_tokens[ : self.max_seq_length - 2] + [tokenizer.sep_token]
assert(len(target_tokens) <= self.max_seq_length )
pos2label = {}
for x in sentence_relations:
pos2label[(x[0],x[1],x[2],x[3])] = label_map[x[4]]
self.golden_labels.add(((l_idx, n), (x[0],x[1]), (x[2],x[3]), x[4]))
self.golden_labels_withner.add(((l_idx, n), (x[0],x[1], std_entity_labels[(x[0], x[1])]), (x[2],x[3], std_entity_labels[(x[2], x[3])]), x[4]))
if x[4] in self.sym_labels[1:]:
self.golden_labels.add(((l_idx, n), (x[2],x[3]), (x[0],x[1]), x[4]))
self.golden_labels_withner.add(((l_idx, n), (x[2],x[3], std_entity_labels[(x[2], x[3])]), (x[0],x[1], std_entity_labels[(x[0], x[1])]), x[4]))
entities = list(sentence_ners)
# for x in sentence_relations:
# w = (x[2],x[3],x[0],x[1])
# if w not in pos2label:
# if x[4] in self.sym_labels[1:]:
# pos2label[w] = label_map[x[4]]
# else:
# pos2label[w] = label_map[x[4]] + len(label_map) - len(self.sym_labels)
cur_ins = []
for sub_start, sub_end, sub_label in entities:
sub = (sub_start, sub_end)
doc_entity_start = token2subword[sub_start]
doc_entity_end = token2subword[sub_end+1]
sub_left = doc_entity_start - doc_offset + 1
sub_right = doc_entity_end - doc_offset
for start, end, obj_label in sentence_ners:
# if start==sub_start and end==sub_end:
# continue
doc_entity_start = token2subword[start]
doc_entity_end = token2subword[end+1]
left = doc_entity_start - doc_offset + 1
right = doc_entity_end - doc_offset
obj = (start, end)
label = pos2label.get((sub[0], sub[1], obj[0], obj[1]), 0)
cur_ins.append(((sub_left, sub_right, ner_label_map[sub_label]), (left, right, ner_label_map[obj_label]), label, (sub, obj)))
maxR = max(maxR, len(cur_ins))
dL = self.max_pair_length
if self.args.shuffle:
np.random.shuffle(cur_ins)
for i in range(0, len(cur_ins), dL):
examples = cur_ins[i : i + dL]
item = {
'index': (l_idx, n),
'sentence': target_tokens,
'examples': examples,
}
self.data.append(item)
logger.info('maxR: %s', maxR)
logger.info('maxL: %s', maxL)
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
entry = self.data[idx]
input_ids = self.tokenizer.convert_tokens_to_ids(entry['sentence'])
L = len(input_ids)
input_ids += [self.tokenizer.pad_token_id] * (self.max_seq_length - len(input_ids))
attention_mask = torch.zeros((self.max_entity_length+self.max_seq_length, self.max_entity_length+self.max_seq_length), dtype=torch.int64)
attention_mask[:L, :L] = 1
if self.model_type.startswith('albert'):
assert(False) # Not implement
input_ids = input_ids + [30002] * (len(entry['examples'])) + [self.tokenizer.pad_token_id] * (self.max_pair_length - len(entry['examples']))
input_ids = input_ids + [30003] * (len(entry['examples'])) + [self.tokenizer.pad_token_id] * (self.max_pair_length - len(entry['examples']))
else:
input_ids = input_ids + [1] * (len(entry['examples'])) + [self.tokenizer.pad_token_id] * (self.max_pair_length - len(entry['examples']))
input_ids = input_ids + [2] * (len(entry['examples'])) + [self.tokenizer.pad_token_id] * (self.max_pair_length - len(entry['examples']))
input_ids = input_ids + [3] * (len(entry['examples'])) + [self.tokenizer.pad_token_id] * (self.max_pair_length - len(entry['examples']))
input_ids = input_ids + [4] * (len(entry['examples'])) + [self.tokenizer.pad_token_id] * (self.max_pair_length - len(entry['examples']))
labels = []
m1_ner_labels = []
m2_ner_labels = []
mention_2 = []
position_ids = list(range(self.max_seq_length)) + [0] * self.max_entity_length
num_pair = self.max_pair_length
for x_idx, item in enumerate(entry['examples']):
m1 = item[0]
m2 = item[1]
label = item[2]
mention_2.append(item[3])
w1 = x_idx
w2 = w1 + num_pair
w3 = w2 + num_pair
w4 = w3 + num_pair
w1 += self.max_seq_length
w2 += self.max_seq_length
w3 += self.max_seq_length
w4 += self.max_seq_length
position_ids[w1] = m1[0]
position_ids[w2] = m1[1]
position_ids[w3] = m2[0]
position_ids[w4] = m2[1]
for xx in [w1, w2, w3, w4]:
for yy in [w1, w2, w3, w4]:
attention_mask[xx, yy] = 1
attention_mask[xx, :L] = 1
labels.append(label)
m1_ner_labels.append(m1[2])
m2_ner_labels.append(m2[2])
pair_L = len(entry['examples'])
labels += [-1] * (num_pair - len(labels))
m1_ner_labels += [-1] * (num_pair - len(m1_ner_labels))
m2_ner_labels += [-1] * (num_pair - len(m2_ner_labels))
item = [torch.tensor(input_ids),
attention_mask,
torch.tensor(position_ids),
torch.tensor(labels, dtype=torch.int64),
torch.tensor(m1_ner_labels, dtype=torch.int64),
torch.tensor(m2_ner_labels, dtype=torch.int64),
]
if self.evaluate:
item.append(entry['index'])
item.append(mention_2)
return item
@staticmethod
def collate_fn(batch):
fields = [x for x in zip(*batch)]
num_metadata_fields = 2
stacked_fields = [torch.stack(field) for field in fields[:-num_metadata_fields]] # don't stack metadata fields
stacked_fields.extend(fields[-num_metadata_fields:]) # add them as lists not torch tensors
return stacked_fields
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 _rotate_checkpoints(args, checkpoint_prefix, use_mtime=False):
if not args.save_total_limit:
return
if args.save_total_limit <= 0:
return
# Check if we should delete older checkpoint(s)
glob_checkpoints = glob.glob(os.path.join(args.output_dir, '{}-*'.format(checkpoint_prefix)))
if len(glob_checkpoints) <= args.save_total_limit:
return
ordering_and_checkpoint_path = []
for path in glob_checkpoints:
if use_mtime:
ordering_and_checkpoint_path.append((os.path.getmtime(path), path))
else:
regex_match = re.match('.*{}-([0-9]+)'.format(checkpoint_prefix), path)
if regex_match and regex_match.groups():
ordering_and_checkpoint_path.append((int(regex_match.groups()[0]), path))
checkpoints_sorted = sorted(ordering_and_checkpoint_path)
checkpoints_sorted = [checkpoint[1] for checkpoint in checkpoints_sorted]
number_of_checkpoints_to_delete = max(0, len(checkpoints_sorted) - args.save_total_limit)
checkpoints_to_be_deleted = checkpoints_sorted[:number_of_checkpoints_to_delete]
for checkpoint in checkpoints_to_be_deleted:
logger.info("Deleting older checkpoint [{}] due to args.save_total_limit".format(checkpoint))
shutil.rmtree(checkpoint)
def train(args, model, tokenizer):
""" Train the model """
if args.local_rank in [-1, 0]:
tb_writer = SummaryWriter("logs/"+args.data_dir[max(args.data_dir.rfind('/'),0):]+"_re_logs/"+args.output_dir[args.output_dir.rfind('/'):])
args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu)
train_dataset = ACEDataset(tokenizer=tokenizer, args=args, max_pair_length=args.max_pair_length)
train_sampler = RandomSampler(train_dataset) if args.local_rank == -1 else DistributedSampler(train_dataset)
train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.train_batch_size, num_workers=4*int(args.output_dir.find('test')==-1))
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
else:
t_total = len(train_dataloader) // 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)
if args.warmup_steps==-1:
scheduler = get_linear_schedule_with_warmup(
optimizer, num_warmup_steps=int(0.1*t_total), num_training_steps=t_total
)
else:
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, optimizer, opt_level=args.fp16_opt_level)
# ori_model = model
# multi-gpu training (should be after apex fp16 initialization)
if args.n_gpu > 1:
model = torch.nn.DataParallel(model)
# Distributed training (should be after apex fp16 initialization)
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)
# Train!
logger.info("***** Running training *****")
logger.info(" Num examples = %d", len(train_dataset))
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
tr_ner_loss, logging_ner_loss = 0.0, 0.0
tr_re_loss, logging_re_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)
best_f1 = -1
for _ in train_iterator:
# if args.shuffle and _ > 0:
# train_dataset.initialize()
epoch_iterator = tqdm(train_dataloader, desc="Iteration", disable=args.local_rank not in [-1, 0])
for step, batch in enumerate(epoch_iterator):
model.train()
batch = tuple(t.to(args.device) for t in batch)
inputs = {'input_ids': batch[0],
'attention_mask': batch[1],
'position_ids': batch[2],
'labels': batch[3],
'm1_ner_labels': batch[4],
'm2_ner_labels': batch[5],
}
outputs = model(**inputs)
loss = outputs[0] # model outputs are always tuple in pytorch-transformers (see doc)
re_loss = outputs[1]
ner_loss = outputs[2]
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
re_loss = re_loss / args.gradient_accumulation_steps
ner_loss = ner_loss / args.gradient_accumulation_steps
if args.fp16:
with amp.scale_loss(loss, optimizer) as scaled_loss:
scaled_loss.backward()
else:
loss.backward()
tr_loss += loss.item()
if re_loss > 0:
tr_re_loss += re_loss.item()
if ner_loss > 0:
tr_ner_loss += ner_loss.item()
if (step + 1) % args.gradient_accumulation_steps == 0:
if args.max_grad_norm > 0:
if args.fp16:
torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args.max_grad_norm)
else:
torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)
optimizer.step()
scheduler.step() # Update learning rate schedule
model.zero_grad()
global_step += 1
# if args.model_type.endswith('rel') :
# ori_model.bert.encoder.layer[args.add_coref_layer].attention.self.relative_attention_bias.weight.data[0].zero_() # 可以手动乘个mask
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
tb_writer.add_scalar('RE_loss', (tr_re_loss - logging_re_loss)/args.logging_steps, global_step)
logging_re_loss = tr_re_loss
tb_writer.add_scalar('NER_loss', (tr_ner_loss - logging_ner_loss)/args.logging_steps, global_step)
logging_ner_loss = tr_ner_loss
if args.local_rank in [-1, 0] and args.save_steps > 0 and global_step % args.save_steps == 0: # valid for bert/spanbert
update = True
# Save model checkpoint
if args.evaluate_during_training: # Only evaluate when single GPU otherwise metrics may not average well
results = evaluate(args, model, tokenizer)
f1 = results['f1_with_ner']
tb_writer.add_scalar('f1_with_ner', f1, global_step)
if f1 > best_f1:
best_f1 = f1
print ('Best F1', best_f1)
else:
update = False
if update:
checkpoint_prefix = 'checkpoint'
output_dir = os.path.join(args.output_dir, '{}-{}'.format(checkpoint_prefix, 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)
_rotate_checkpoints(args, checkpoint_prefix)
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, best_f1
def to_list(tensor):
return tensor.detach().cpu().tolist()
def evaluate(args, model, tokenizer, prefix="", do_test=False):
eval_output_dir = args.output_dir
eval_dataset = ACEDataset(tokenizer=tokenizer, args=args, evaluate=True, do_test=do_test, max_pair_length=args.max_pair_length)
golden_labels = set(eval_dataset.golden_labels)
golden_labels_withner = set(eval_dataset.golden_labels_withner)
label_list = list(eval_dataset.label_list)
sym_labels = list(eval_dataset.sym_labels)
tot_recall = eval_dataset.tot_recall
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)
# scores = defaultdict(dict)
# ner_pred = not args.model_type.endswith('noner')
# example_subs = set([])
num_label = len(label_list)
tot_preds = {}
logger.info("***** Running evaluation {} *****".format(prefix))
logger.info(" Batch size = %d", args.eval_batch_size)
model.eval()
eval_sampler = SequentialSampler(eval_dataset)
eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size, collate_fn=ACEDataset.collate_fn, num_workers=4*int(args.output_dir.find('test')==-1))
# Eval!
logger.info(" Num examples = %d", len(eval_dataset))
start_time = timeit.default_timer()
for batch in tqdm(eval_dataloader, desc="Evaluating"):
indexs = batch[-2]
batch_mentions = batch[-1]
batch = tuple(t.to(args.device) for t in batch[:-2])
with torch.no_grad():
inputs = {'input_ids': batch[0],
'attention_mask': batch[1],
'position_ids': batch[2],
# 'labels': batch[3],
# 'm1_ner_labels': batch[4],
# 'm2_ner_labels': batch[5],
}
outputs = model(**inputs)
logits = outputs[0]
preds = torch.argmax(logits, dim=-1)
m1_ner_preds = torch.argmax(outputs[1], dim=-1)
m2_ner_preds = torch.argmax(outputs[2], dim=-1)
preds = preds.cpu().numpy()
m1_ner_preds = m1_ner_preds.cpu().numpy()
m2_ner_preds = m2_ner_preds.cpu().numpy()
for i in range(len(indexs)):
index = indexs[i]
mentions = batch_mentions[i]
tot_preds[index] = []
for j in range(len(mentions)):
pred = preds[i,j]
if pred > 0:
sub, obj = mentions[j]
m1_ner_label = eval_dataset.ner_label_list[m1_ner_preds[i,j]]
m2_ner_label = eval_dataset.ner_label_list[m2_ner_preds[i,j]]
re_label = eval_dataset.label_list[pred]
tot_preds[index].append((float(logits[i,j, pred]), sub, obj, re_label, m1_ner_label, m2_ner_label))
cor = 0
tot_pred = 0
cor_with_ner = 0
global_predicted_ners = eval_dataset.global_predicted_ners
ner_golden_labels = eval_dataset.ner_golden_labels
ner_cor = 0
ner_tot_pred = 0
ner_ori_cor = 0
tot_output_results = defaultdict(list)
for example_index, sentence_results in sorted(tot_preds.items(), key=lambda x:x[0]):
sentence_results.sort(key=lambda x: -x[0])
no_overlap = []
def is_overlap(m1, m2):
if m2[0]<=m1[0] and m1[0]<=m2[1]:
return True
if m1[0]<=m2[0] and m2[0]<=m1[1]:
return True
return False
output_preds = []
for item in sentence_results:
m1 = item[1]
m2 = item[2]
overlap = False
for x in no_overlap:
_m1 = x[1]
_m2 = x[2]
# same relation type & overlap subject & overlap object --> delete
if item[3]==x[3] and (is_overlap(m1, _m1) and is_overlap(m2, _m2)):
overlap = True
break
pred_label = item[3]
if not overlap:
no_overlap.append(item)
pos2ner = {}
for item in no_overlap:
m1 = item[1]
m2 = item[2]
pred_label = item[3]
tot_pred += 1
if pred_label in sym_labels:
if (example_index, m1, m2, pred_label) in golden_labels or (example_index, m2, m1, pred_label) in golden_labels:
cor += 1
else:
if (example_index, m1, m2, pred_label) in golden_labels:
cor += 1
if m1 not in pos2ner:
pos2ner[m1] = item[4]
if m2 not in pos2ner:
pos2ner[m2] = item[5]
output_preds.append((m1, m2, pred_label))
if pred_label in sym_labels:
if (example_index, (m1[0], m1[1], pos2ner[m1]), (m2[0], m2[1], pos2ner[m2]), pred_label) in golden_labels_withner \
or (example_index, (m2[0], m2[1], pos2ner[m2]), (m1[0], m1[1], pos2ner[m1]), pred_label) in golden_labels_withner:
cor_with_ner += 1
else:
if (example_index, (m1[0], m1[1], pos2ner[m1]), (m2[0], m2[1], pos2ner[m2]), pred_label) in golden_labels_withner:
cor_with_ner += 1
if do_test:
#output_w.write(json.dumps(output_preds) + '\n')
tot_output_results[example_index[0]].append((example_index[1], output_preds))
# refine NER results
ner_results = list(global_predicted_ners[example_index])
for i in range(len(ner_results)):
start, end, label = ner_results[i]
if (example_index, (start, end), label) in ner_golden_labels:
ner_ori_cor += 1
if (start, end) in pos2ner:
label = pos2ner[(start, end)]
if (example_index, (start, end), label) in ner_golden_labels:
ner_cor += 1
ner_tot_pred += 1
evalTime = timeit.default_timer() - start_time
logger.info(" Evaluation done in total %f secs (%f example per second)", evalTime, len(global_predicted_ners) / evalTime)
if do_test:
output_w = open(os.path.join(args.output_dir, 'pred_results.json'), 'w')
json.dump(tot_output_results, output_w)
ner_p = ner_cor / ner_tot_pred if ner_tot_pred > 0 else 0
ner_r = ner_cor / len(ner_golden_labels)
ner_f1 = 2 * (ner_p * ner_r) / (ner_p + ner_r) if ner_cor > 0 else 0.0
p = cor / tot_pred if tot_pred > 0 else 0
r = cor / tot_recall
f1 = 2 * (p * r) / (p + r) if cor > 0 else 0.0
assert(tot_recall==len(golden_labels))
p_with_ner = cor_with_ner / tot_pred if tot_pred > 0 else 0
r_with_ner = cor_with_ner / tot_recall
assert(tot_recall==len(golden_labels_withner))
f1_with_ner = 2 * (p_with_ner * r_with_ner) / (p_with_ner + r_with_ner) if cor_with_ner > 0 else 0.0
results = {'f1': f1, 'f1_with_ner': f1_with_ner, 'ner_f1': ner_f1}
logger.info("Result: %s", json.dumps(results))
return results
def main():
parser = argparse.ArgumentParser()
## Required parameters
parser.add_argument("--data_dir", default='ace_data', type=str, required=True,
help="The input data dir. Should contain the .tsv files (or other data files) for the task.")
parser.add_argument("--model_type", default=None, type=str, required=True,
help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys()))
parser.add_argument("--model_name_or_path", default=None, type=str, required=True,
help="Path to pre-trained model or shortcut name selected in the list: " + ", ".join(ALL_MODELS))
parser.add_argument("--output_dir", default=None, type=str, required=True,
help="The output directory where the model predictions and checkpoints will be written.")
## Other parameters
parser.add_argument("--config_name", default="", type=str,
help="Pretrained config name or path if not the same as model_name")
parser.add_argument("--tokenizer_name", default="", type=str,
help="Pretrained tokenizer name or path if not the same as model_name")
parser.add_argument("--cache_dir", default="", type=str,
help="Where do you want to store the pre-trained models downloaded from s3")
parser.add_argument("--max_seq_length", default=384, type=int,
help="The maximum total input sequence length after tokenization. Sequences longer "
"than this will be truncated, sequences shorter will be padded.")
parser.add_argument("--do_train", action='store_true',
help="Whether to run training.")
parser.add_argument("--do_eval", action='store_true',
help="Whether to run eval on the dev set.")
parser.add_argument("--evaluate_during_training", action='store_true',
help="Rul evaluation during training at each logging step.")
parser.add_argument("--do_lower_case", action='store_true',
help="Set this flag if you are using an uncased model.")
parser.add_argument("--per_gpu_train_batch_size", default=8, type=int,
help="Batch size per GPU/CPU for training.")
parser.add_argument("--per_gpu_eval_batch_size", default=8, type=int,
help="Batch size per GPU/CPU for evaluation.")
parser.add_argument('--gradient_accumulation_steps', type=int, default=1,
help="Number of updates steps to accumulate before performing a backward/update pass.")
parser.add_argument("--learning_rate", default=2e-5, type=float,
help="The initial learning rate for Adam.")
parser.add_argument("--weight_decay", default=0.0, type=float,
help="Weight deay if we apply some.")
parser.add_argument("--adam_epsilon", default=1e-8, type=float,
help="Epsilon for Adam optimizer.")
parser.add_argument("--max_grad_norm", default=1.0, type=float,
help="Max gradient norm.")
parser.add_argument("--num_train_epochs", default=30.0, type=float,
help="Total number of training epochs to perform.")
parser.add_argument("--max_steps", default=-1, type=int,
help="If > 0: set total number of training steps to perform. Override num_train_epochs.")
parser.add_argument("--warmup_steps", default=-1, type=int,
help="Linear warmup over warmup_steps.")
parser.add_argument('--logging_steps', type=int, default=5,
help="Log every X updates steps.")
parser.add_argument('--save_steps', type=int, default=1000,
help="Save checkpoint every X updates steps.")
parser.add_argument("--eval_all_checkpoints", action='store_true',
help="Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number")
parser.add_argument("--no_cuda", action='store_true',
help="Avoid using CUDA when available")
parser.add_argument('--overwrite_output_dir', action='store_true',
help="Overwrite the content of the output directory")
parser.add_argument('--overwrite_cache', action='store_true',
help="Overwrite the cached training and evaluation sets")
parser.add_argument('--seed', type=int, default=42,
help="random seed for initialization")
parser.add_argument('--fp16', action='store_true',
help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit")
parser.add_argument('--fp16_opt_level', type=str, default='O1',
help="For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']."
"See details at https://nvidia.github.io/apex/amp.html")
parser.add_argument("--local_rank", type=int, default=-1,
help="For distributed training: local_rank")
parser.add_argument('--server_ip', type=str, default='', help="For distant debugging.")
parser.add_argument('--server_port', type=str, default='', help="For distant debugging.")
parser.add_argument('--save_total_limit', type=int, default=1,
help='Limit the total amount of checkpoints, delete the older checkpoints in the output_dir, does not delete by default')
parser.add_argument("--train_file", default="train.json", type=str)
parser.add_argument("--dev_file", default="dev.json", type=str)
parser.add_argument("--test_file", default="test.json", type=str)
parser.add_argument('--max_pair_length', type=int, default=64, help="")
parser.add_argument("--alpha", default=1.0, type=float)
parser.add_argument('--save_results', action='store_true')
parser.add_argument('--no_test', action='store_true')
parser.add_argument('--eval_logsoftmax', action='store_true')
parser.add_argument('--eval_softmax', action='store_true')
parser.add_argument('--shuffle', action='store_true')
parser.add_argument('--lminit', action='store_true')
parser.add_argument('--no_sym', action='store_true')
parser.add_argument('--att_left', action='store_true')
parser.add_argument('--att_right', action='store_true')
parser.add_argument('--use_ner_results', action='store_true')
parser.add_argument('--use_typemarker', action='store_true')
parser.add_argument('--eval_unidirect', action='store_true')
args = parser.parse_args()
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))
def create_exp_dir(path, scripts_to_save=None):
if args.output_dir.endswith("test"):
return
if not os.path.exists(path):
os.mkdir(path)
print('Experiment dir : {}'.format(path))
if scripts_to_save is not None:
if not os.path.exists(os.path.join(path, 'scripts')):
os.mkdir(os.path.join(path, 'scripts'))
for script in scripts_to_save:
dst_file = os.path.join(path, 'scripts', os.path.basename(script))
shutil.copyfile(script, dst_file)
if args.do_train and args.local_rank in [-1, 0] and args.output_dir.find('test')==-1:
create_exp_dir(args.output_dir, scripts_to_save=['run_re.py', 'transformers/src/transformers/modeling_bert.py', 'transformers/src/transformers/modeling_albert.py'])
# Setup distant debugging if needed
if args.server_ip and args.server_port:
# Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
import ptvsd
print("Waiting for debugger attach")
ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=True)
ptvsd.wait_for_attach()
# 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)
if args.data_dir.find('ace')!=-1:
num_ner_labels = 8
num_labels = 7
# if args.no_sym:
# num_labels = 7 + 7 - 1
# else:
# num_labels = 7 + 7 - 2
elif args.data_dir.find('scierc')!=-1:
num_ner_labels = 7
num_labels = 8
# if args.no_sym:
# num_labels = 8 + 8 - 1
# else:
# num_labels = 8 + 8 - 3
else: