-
Notifications
You must be signed in to change notification settings - Fork 35
/
run_re_unidirect.py
1198 lines (952 loc) · 50.5 KB
/
run_re_unidirect.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,
BertForACEBothOneDropoutSub,
AlbertForACEBothSub,
AlbertConfig,
AlbertTokenizer,
AlbertForACEBothOneDropoutSub,
BertForACEBothOneDropoutSubNoNer,
)
from transformers import AutoTokenizer
from torch.utils.data import TensorDataset, Dataset
import json
import pickle
import numpy as np
import unicodedata
import itertools
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 = {
'bertsub': (BertConfig, BertForACEBothOneDropoutSub, 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*2
self.max_mention_length = args.max_mention_length
self.evaluate = evaluate
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.eval_pred_ent = args.eval_pred_ent
self.global_predicted_ners = {}
self.initialize()
def initialize(self, eval_cands=None):
tokenizer = self.tokenizer
vocab_size = tokenizer.vocab_size
max_num_subwords = self.max_seq_length - 4 # for two marker
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
sentences = data['sentences']
if 'predicted_ner' in data:
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]
# entity_labels = {}
# for start, end, label in sentence_ners:
# entity_labels[(token2subword[start], token2subword[end+1])] = ner_label_map[label]
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 - 4] + [tokenizer.sep_token]
assert(len(target_tokens) <= self.max_seq_length - 2)
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]))
if eval_cands:
if (l_idx, n) in eval_cands:
entities = eval_cands[(l_idx, n)]
else:
continue
else:
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]]
if not self.evaluate:
entities.append((10000, 10000, 'NIL')) # only for NER
for sub in entities:
cur_ins = []
if sub[0] < 10000:
sub_s = token2subword[sub[0]] - doc_offset + 1
sub_e = token2subword[sub[1]+1] - doc_offset
l_m = '[unused0]'
r_m = '[unused1]'
sub_tokens = target_tokens[:sub_s] + [l_m] + target_tokens[sub_s:sub_e+1] + [r_m] + target_tokens[sub_e+1: ]
sub_e += 2
sub_label = ner_label_map[sub[2]]
else:
sub_s = len(target_tokens)
sub_e = len(target_tokens)+1
sub_tokens = target_tokens + ['[unused0]', '[unused1]']
sub_label = -1
if sub_e >= self.max_seq_length-1:
continue
for start, end, obj_label in sentence_ners:
if self.model_type.endswith('nersub'):
if start==sub[0] and end==sub[1]:
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)
if obj[0] >= sub[0]:
left += 1
if obj[0] > sub[1]:
left += 1
if obj[1] >= sub[0]:
right += 1
if obj[1] > sub[1]:
right += 1
label = pos2label.get((sub[0], sub[1], obj[0], obj[1]), 0)
if right >= self.max_seq_length-1:
continue
cur_ins.append(((left, right, ner_label_map[obj_label]), label, 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': sub_tokens,
'examples': examples,
'sub': (sub, (sub_s, sub_e), sub_label), #(sub[0], sub[1], sub_label),
}
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]
sub, sub_position, sub_label = entry['sub']
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'):
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'])) # for debug
else:
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'])) # for debug
labels = []
ner_labels = []
mention_pos = []
mention_2 = []
position_ids = list(range(self.max_seq_length)) + [0] * self.max_entity_length
num_pair = self.max_pair_length
for x_idx, obj in enumerate(entry['examples']):
m2 = obj[0]
label = obj[1]
mention_pos.append((m2[0], m2[1]))
mention_2.append(obj[2])
w1 = x_idx
w2 = w1 + num_pair
w1 += self.max_seq_length
w2 += self.max_seq_length
position_ids[w1] = m2[0]
position_ids[w2] = m2[1]
for xx in [w1, w2]:
for yy in [w1, w2]:
attention_mask[xx, yy] = 1
attention_mask[xx, :L] = 1
labels.append(label)
ner_labels.append(m2[2])
pair_L = len(entry['examples'])
if self.args.att_left:
attention_mask[self.max_seq_length : self.max_seq_length+pair_L, self.max_seq_length : self.max_seq_length+pair_L] = 1
if self.args.att_right:
attention_mask[self.max_seq_length+num_pair : self.max_seq_length+num_pair+pair_L, self.max_seq_length+num_pair : self.max_seq_length+num_pair+pair_L] = 1
mention_pos += [(0, 0)] * (num_pair - len(mention_pos))
labels += [-1] * (num_pair - len(labels))
ner_labels += [-1] * (num_pair - len(ner_labels))
item = [torch.tensor(input_ids),
attention_mask,
torch.tensor(position_ids),
torch.tensor(sub_position),
torch.tensor(mention_pos),
torch.tensor(labels, dtype=torch.int64),
torch.tensor(ner_labels, dtype=torch.int64),
torch.tensor(sub_label, dtype=torch.int64)
]
if self.evaluate:
item.append(entry['index'])
item.append(sub)
item.append(mention_2)
return item
@staticmethod
def collate_fn(batch):
fields = [x for x in zip(*batch)]
num_metadata_fields = 3
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[5],
'ner_labels': batch[6],
}
# if args.model_type.endswith('sub'):
inputs['sub_positions'] = batch[3]
if args.model_type.find('span')!=-1:
inputs['mention_pos'] = batch[4]
if args.model_type.endswith('nersub'):
inputs['sub_ner_labels'] = batch[7]
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)
# f1 = results['f1']
# tb_writer.add_scalar('f1', 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)
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))
for batch in tqdm(eval_dataloader, desc="Evaluating"):
indexs = batch[-3]
subs = batch[-2]
batch_m2s = batch[-1]
ner_labels = batch[6]
batch = tuple(t.to(args.device) for t in batch[:-3])
with torch.no_grad():
inputs = {'input_ids': batch[0],
'attention_mask': batch[1],
'position_ids': batch[2],
# 'labels': batch[4],
# 'ner_labels': batch[5],
}
# if args.model_type.endswith('sub'):
inputs['sub_positions'] = batch[3]
if args.model_type.find('span')!=-1:
inputs['mention_pos'] = batch[4]
outputs = model(**inputs)
logits = outputs[0]
if args.eval_logsoftmax: # perform a bit better
logits = torch.nn.functional.log_softmax(logits, dim=-1)
elif args.eval_softmax:
logits = torch.nn.functional.softmax(logits, dim=-1)
if args.use_ner_results:
ner_preds = ner_labels
else:
ner_preds = torch.argmax(outputs[1], dim=-1)
logits = logits.cpu().numpy()
ner_preds = ner_preds.cpu().numpy()
for i in range(len(indexs)):
index = indexs[i]
sub = subs[i]
m2s = batch_m2s[i]
example_subs.add(((index[0], index[1]), (sub[0], sub[1])))
for j in range(len(m2s)):
obj = m2s[j]
ner_label = eval_dataset.ner_label_list[ner_preds[i,j]]
scores[(index[0], index[1])][( (sub[0], sub[1]), (obj[0], obj[1]))] = (logits[i, j].tolist(), 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
for example_index, pair_dict in sorted(scores.items(), key=lambda x:x[0]):
sentence_results = []
for k1, (v1, v2_ner_label) in pair_dict.items():
if v2_ner_label=='NIL':
continue
v1 = list(v1)
m1 = k1[0]
m2 = k1[1]
if m1 == m2:
continue
pred_label = np.argmax(v1)
if pred_label>0:
pred_score = v1[pred_label]
sentence_results.append( (pred_score, m1, m2, pred_label, None, v2_ner_label) )
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]
if item[3]==x[3] and (is_overlap(m1, _m1) and is_overlap(m2, _m2)):
overlap = True
break
pred_label = label_list[item[3]]
output_preds.append((m1, m2, pred_label))
if not overlap:
no_overlap.append(item)
pos2ner = {}
predpos2ner = {}
ner_results = list(global_predicted_ners[example_index])
for start, end, label in ner_results:
predpos2ner[(start, end)] = label
for item in no_overlap:
m1 = item[1]
m2 = item[2]
pred_label = label_list[item[3]]
tot_pred += 1
if (example_index, m1, m2, pred_label) in golden_labels:
cor += 1
if m1 not in pos2ner:
pos2ner[m1] = predpos2ner[m1]#item[4]
if m2 not in pos2ner:
pos2ner[m2] = item[5]
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
# 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
ner_ori_p = ner_ori_cor / ner_tot_pred if ner_tot_pred > 0 else 0
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=10.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="ent_pred_test.json", type=str)
parser.add_argument('--max_pair_length', type=int, default=128, help="")
parser.add_argument("--eval_pred_ent", action='store_true', help="")
parser.add_argument('--max_mention_length', type=int, default=12, 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')
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)