-
Notifications
You must be signed in to change notification settings - Fork 1
/
model.py
3391 lines (2946 loc) · 178 KB
/
model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import time
from graph import Graph
from transformers import BertModel, AutoModel,AlbertModel,RobertaModel
from global_feature import generate_global_feature_vector, generate_global_feature_maps
from util import normalize_score
from opt_einsum import contract
import os
from config import Config
from collections import Counter, namedtuple, defaultdict
from data import Batch, Instance
from torch.nn.parameter import Parameter
from sparsemax import Sparsemax
cur_dir = os.path.dirname(os.path.realpath(__file__))
def log_sum_exp(tensor, dim=0, keepdim: bool = False):
"""LogSumExp operation used by CRF."""
m, _ = tensor.max(dim, keepdim=keepdim)
if keepdim:
stable_vec = tensor - m
else:
stable_vec = tensor - m.unsqueeze(dim)
return m + (stable_vec.exp().sum(dim, keepdim=keepdim)).log()
def sequence_mask(lens, max_len=None):
"""Generate a sequence mask tensor from sequence lengths, used by CRF."""
batch_size = lens.size(0)
if max_len is None:
max_len = lens.max().item()
ranges = torch.arange(0, max_len, device=lens.device).long()
ranges = ranges.unsqueeze(0).expand(batch_size, max_len)
lens_exp = lens.unsqueeze(1).expand_as(ranges)
mask = ranges < lens_exp
return mask
def token_lens_to_offsets(token_lens):
"""Map token lengths to first word piece indices, used by the sentence
encoder.
:param token_lens (list): token lengths (word piece numbers)
:return (list): first word piece indices (offsets)
"""
max_token_num = max([len(x) for x in token_lens])
offsets = []
for seq_token_lens in token_lens:
seq_offsets = [0]
for l in seq_token_lens[:-1]:
seq_offsets.append(seq_offsets[-1] + l)
offsets.append(seq_offsets + [-1] * (max_token_num - len(seq_offsets)))
return offsets
def token_lens_to_idxs(token_lens):
"""Map token lengths to a word piece index matrix (for torch.gather) and a
mask tensor.
For example (only show a sequence instead of a batch):
token lengths: [1,1,1,3,1]
=>
indices: [[0,0,0], [1,0,0], [2,0,0], [3,4,5], [6,0,0]]
masks: [[1.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.0, 0.0],
[0.33, 0.33, 0.33], [1.0, 0.0, 0.0]]
Next, we use torch.gather() to select vectors of word pieces for each token,
and average them as follows (incomplete code):
outputs = torch.gather(bert_outputs, 1, indices) * masks
outputs = bert_outputs.view(batch_size, seq_len, -1, self.bert_dim)
outputs = bert_outputs.sum(2)
:param token_lens (list): token lengths.
:return: a index matrix and a mask tensor.
"""
max_token_num = max([len(x) for x in token_lens])
max_token_len = max([max(x) for x in token_lens])
idxs, masks = [], []
for seq_token_lens in token_lens:
seq_idxs, seq_masks = [], []
offset = 0
for token_len in seq_token_lens:
seq_idxs.extend([i + offset for i in range(token_len)]
+ [-1] * (max_token_len - token_len))
seq_masks.extend([1.0 / token_len] * token_len
+ [0.0] * (max_token_len - token_len))
offset += token_len
seq_idxs.extend([-1] * max_token_len * (max_token_num - len(seq_token_lens)))
seq_masks.extend([0.0] * max_token_len * (max_token_num - len(seq_token_lens)))
idxs.append(seq_idxs)
masks.append(seq_masks)
return idxs, masks, max_token_num, max_token_len
def graphs_to_node_idxs(graphs):
"""
:param graphs (list): A list of Graph objects.
:return: entity/trigger index matrix, mask tensor, max number, and max length
"""
entity_idxs, entity_masks = [], []
trigger_idxs, trigger_masks = [], []
#
max_entity_num = max(max(graph.entity_num for graph in graphs), 1)
max_trigger_num = max(max(graph.trigger_num for graph in graphs), 1)
max_entity_len = max(max([e[1] - e[0] for e in graph.entities] + [1])
for graph in graphs)
max_trigger_len = max(max([t[1] - t[0] for t in graph.triggers] + [1])
for graph in graphs)
for graph in graphs:
seq_entity_idxs, seq_entity_masks = [], []
seq_trigger_idxs, seq_trigger_masks = [], []
for entity in graph.entities:
entity_len = entity[1] - entity[0]
seq_entity_idxs.extend([i for i in range(entity[0], entity[1])])
seq_entity_idxs.extend([0] * (max_entity_len - entity_len))
seq_entity_masks.extend([1.0 / entity_len] * entity_len)
seq_entity_masks.extend([0.0] * (max_entity_len - entity_len))
seq_entity_idxs.extend([0] * max_entity_len * (max_entity_num - graph.entity_num))
seq_entity_masks.extend([0.0] * max_entity_len * (max_entity_num - graph.entity_num))
entity_idxs.append(seq_entity_idxs)
entity_masks.append(seq_entity_masks)
for trigger in graph.triggers:
trigger_len = trigger[1] - trigger[0]
seq_trigger_idxs.extend([i for i in range(trigger[0], trigger[1])])
seq_trigger_idxs.extend([0] * (max_trigger_len - trigger_len))
seq_trigger_masks.extend([1.0 / trigger_len] * trigger_len)
seq_trigger_masks.extend([0.0] * (max_trigger_len - trigger_len))
seq_trigger_idxs.extend([0] * max_trigger_len * (max_trigger_num - graph.trigger_num))
seq_trigger_masks.extend([0.0] * max_trigger_len * (max_trigger_num - graph.trigger_num))
trigger_idxs.append(seq_trigger_idxs)
trigger_masks.append(seq_trigger_masks)
return (
entity_idxs, entity_masks, max_entity_num, max_entity_len,
trigger_idxs, trigger_masks, max_trigger_num, max_trigger_len,
)
def graphs_to_label_idxs(graphs, max_entity_num=-1, max_trigger_num=-1,
relation_directional=False,
symmetric_relation_idxs=None):
"""Convert a list of graphs to label index and mask matrices
:param graphs (list): A list of Graph objects.
:param max_entity_num (int) Max entity number (default = -1).
:param max_trigger_num (int) Max trigger number (default = -1).
"""
if max_entity_num == -1:
max_entity_num = max(max([g.entity_num for g in graphs]), 1)
if max_trigger_num == -1:
max_trigger_num = max(max([g.trigger_num for g in graphs]), 1)
(
batch_entity_idxs, batch_entity_mask,
batch_trigger_idxs, batch_trigger_mask,
batch_relation_idxs, batch_relation_mask,
batch_role_idxs, batch_role_mask
) = [[] for _ in range(8)]
for graph in graphs:
(
entity_idxs, entity_mask, trigger_idxs, trigger_mask,
relation_idxs, relation_mask, role_idxs, role_mask,
) = graph.to_label_idxs(max_entity_num, max_trigger_num,
relation_directional=relation_directional,
symmetric_relation_idxs=symmetric_relation_idxs)
batch_entity_idxs.append(entity_idxs)
batch_entity_mask.append(entity_mask)
batch_trigger_idxs.append(trigger_idxs)
batch_trigger_mask.append(trigger_mask)
batch_relation_idxs.append(relation_idxs)
batch_relation_mask.append(relation_mask)
batch_role_idxs.append(role_idxs)
batch_role_mask.append(role_mask)
return (
batch_entity_idxs, batch_entity_mask,
batch_trigger_idxs, batch_trigger_mask,
batch_relation_idxs, batch_relation_mask,
batch_role_idxs, batch_role_mask
)
def generate_pairwise_idxs(num1, num2):
"""Generate all pairwise combinations among entity mentions (relation) or
event triggers and entity mentions (argument role).
For example, if there are 2 triggers and 3 mentions in a sentence, num1 = 2,
and num2 = 3. We generate the following vector:
idxs = [0, 2, 0, 3, 0, 4, 1, 2, 1, 3, 1, 4]
Suppose `trigger_reprs` and `entity_reprs` are trigger/entity representation
tensors. We concatenate them using:
te_reprs = torch.cat([entity_reprs, entity_reprs], dim=1)
After that we select vectors from `te_reprs` using (incomplete code) to obtain
pairwise combinations of all trigger and entity vectors.
te_reprs = torch.gather(te_reprs, 1, idxs)
te_reprs = te_reprs.view(batch_size, -1, 2 * bert_dim)
:param num1: trigger number (argument role) or entity number (relation)
:param num2: entity number (relation)
:return (list): a list of indices
"""
idxs = []
for i in range(num1):
for j in range(num2):
idxs.append(i)
idxs.append(j + num1)
return idxs
def tag_paths_to_spans(paths, token_nums, vocab):
"""Convert predicted tag paths to a list of spans (entity mentions or event
triggers).
:param paths: predicted tag paths.
:return (list): a list (batch) of lists (sequence) of spans.
"""
batch_mentions = []
itos = {i: s for s, i in vocab.items()}
for i, path in enumerate(paths):
mentions = []
cur_mention = None
path = path.tolist()[:token_nums[i].item()]
for j, tag in enumerate(path):
tag = itos[tag]
if tag == 'O':
prefix = tag = 'O'
else:
prefix, tag = tag.split('-', 1)
if prefix == 'B':
if cur_mention:
mentions.append(cur_mention)
cur_mention = [j, j + 1, tag]
elif prefix == 'I':
if cur_mention is None:
# treat it as B-*
cur_mention = [j, j + 1, tag]
elif cur_mention[-1] == tag:
cur_mention[1] = j + 1
else:
# treat it as B-*
mentions.append(cur_mention)
cur_mention = [j, j + 1, tag]
else:
if cur_mention:
mentions.append(cur_mention)
cur_mention = None
if cur_mention:
mentions.append(cur_mention)
batch_mentions.append(mentions)
return batch_mentions
def remove_overlap_entities(gold_entities, wrong_entities):
"""There are a few overlapping entities in the data set. We only keep the
first one and map others to it.
:param entities (list): a list of entity mentions.
:return: processed entity mentions and a table of mapped IDs.
"""
tokens = [None] * 1000
entities_ = []
for entity in gold_entities:
start, end = entity[0], entity[1]
# for i in range(start, end):
# if tokens[i]:
# continue
# entities_.append(entity)
for i in range(start, end):
#
tokens[i] = 1
for wrong_entity in wrong_entities:
start, end = wrong_entity[0], wrong_entity[1]
overlap = False
for i in range(start, end):
if tokens[i]:
overlap = True
break
if not overlap:
entities_.append(wrong_entity)
return entities_
class High_Linears(nn.Module):
"""Multiple linear layers with Dropout."""
def __init__(self, dimensions, dropout_prob=0.0, bias=True):
super().__init__()
assert len(dimensions) > 1
self.layers = nn.ModuleList([nn.Linear(dimensions[i], dimensions[i + 1], bias=bias)
for i in range(len(dimensions) - 1)])
# self.activation = getattr(torch, activation)
self.dropout = nn.Dropout(dropout_prob)
def forward(self, inputs):
for i, layer in enumerate(self.layers):
if i > 0:
# inputs = self.activation(inputs)
inputs = self.dropout(inputs)
inputs = layer(inputs)
return inputs
#==============================================================================
class Guide_Linears(nn.Module):
"""Multiple linear layers with Dropout."""
def __init__(self, dimensions, activation='relu', dropout_prob=0.0, bias=True):
super().__init__()
assert len(dimensions) > 1
self.layers = nn.ModuleList([nn.Linear(dimensions[i], dimensions[i + 1], bias=bias)
for i in range(len(dimensions) - 1)])
self.activation = getattr(torch, activation)
self.dropout = nn.Dropout(dropout_prob)
def forward(self, inputs):
for i, layer in enumerate(self.layers):
inputs = layer(inputs)
inputs = self.activation(inputs)
inputs = self.dropout(inputs)
return inputs
#==============================================================================
class Linears(nn.Module):
"""Multiple linear layers with Dropout."""
def __init__(self, dimensions, activation='relu', dropout_prob=0.0, bias=True):
super().__init__()
assert len(dimensions) > 1
self.layers = nn.ModuleList([nn.Linear(dimensions[i], dimensions[i + 1], bias=bias)
for i in range(len(dimensions) - 1)])
if activation == "":
self.activation = None
elif activation == "GELU":
self.activation = nn.GELU()
else:
self.activation = getattr(torch, activation)
# self.activation = nn.LeakyReLU(0.1)
self.dropout = nn.Dropout(dropout_prob)
def forward(self, inputs):
# breakpoint()
for i, layer in enumerate(self.layers):
if i > 0:
if self.activation:
inputs = self.activation(inputs)
inputs = self.dropout(inputs)
inputs = layer(inputs)
return inputs
class CRF(nn.Module):
def __init__(self, label_vocab, bioes=False):
super(CRF, self).__init__()
self.label_vocab = label_vocab
self.label_size = len(label_vocab) + 2
# self.same_type = self.map_same_types()
self.bioes = bioes
self.start = self.label_size - 2
self.end = self.label_size - 1
transition = torch.randn(self.label_size, self.label_size)
self.transition = nn.Parameter(transition)
self.initialize()
def initialize(self):
self.transition.data[:, self.end] = -100.0
self.transition.data[self.start, :] = -100.0
for label, label_idx in self.label_vocab.items():
if label.startswith('I-') or label.startswith('E-'):
self.transition.data[label_idx, self.start] = -100.0
if label.startswith('B-') or label.startswith('I-'):
self.transition.data[self.end, label_idx] = -100.0
for label_from, label_from_idx in self.label_vocab.items():
if label_from == 'O':
label_from_prefix, label_from_type = 'O', 'O'
else:
label_from_prefix, label_from_type = label_from.split('-', 1)
for label_to, label_to_idx in self.label_vocab.items():
if label_to == 'O':
label_to_prefix, label_to_type = 'O', 'O'
else:
label_to_prefix, label_to_type = label_to.split('-', 1)
if self.bioes:
is_allowed = any(
[
label_from_prefix in ['O', 'E', 'S']
and label_to_prefix in ['O', 'B', 'S'],
label_from_prefix in ['B', 'I']
and label_to_prefix in ['I', 'E']
and label_from_type == label_to_type
]
)
else:
is_allowed = any(
[
label_to_prefix in ['B', 'O'],
label_from_prefix in ['B', 'I']
and label_to_prefix == 'I'
and label_from_type == label_to_type
]
)
if not is_allowed:
self.transition.data[
label_to_idx, label_from_idx] = -100.0
def pad_logits(self, logits):
"""Pad the linear layer output with <SOS> and <EOS> scores.
:param logits: Linear layer output (no non-linear function).
"""
batch_size, seq_len, _ = logits.size()
pads = logits.new_full((batch_size, seq_len, 2), -100.0,
requires_grad=False)
logits = torch.cat([logits, pads], dim=2)
return logits
def calc_binary_score(self, labels, lens):
batch_size, seq_len = labels.size()
# A tensor of size batch_size * (seq_len + 2)
labels_ext = labels.new_empty((batch_size, seq_len + 2))
labels_ext[:, 0] = self.start
labels_ext[:, 1:-1] = labels
mask = sequence_mask(lens + 1, max_len=(seq_len + 2)).long()
pad_stop = labels.new_full((1,), self.end, requires_grad=False)
pad_stop = pad_stop.unsqueeze(-1).expand(batch_size, seq_len + 2)
labels_ext = (1 - mask) * pad_stop + mask * labels_ext
labels = labels_ext
trn = self.transition
trn_exp = trn.unsqueeze(0).expand(batch_size, self.label_size,
self.label_size)
lbl_r = labels[:, 1:]
lbl_rexp = lbl_r.unsqueeze(-1).expand(*lbl_r.size(), self.label_size)
# score of jumping to a tag
trn_row = torch.gather(trn_exp, 1, lbl_rexp)
lbl_lexp = labels[:, :-1].unsqueeze(-1)
trn_scr = torch.gather(trn_row, 2, lbl_lexp)
trn_scr = trn_scr.squeeze(-1)
mask = sequence_mask(lens + 1).float()
trn_scr = trn_scr * mask
score = trn_scr
return score
def calc_unary_score(self, logits, labels, lens):
"""Checked"""
labels_exp = labels.unsqueeze(-1)
scores = torch.gather(logits, 2, labels_exp).squeeze(-1)
mask = sequence_mask(lens).float()
scores = scores * mask
return scores
def calc_gold_score(self, logits, labels, lens):
"""Checked"""
# start = torch.cuda.Event(enable_timing=True)
# end = torch.cuda.Event(enable_timing=True)
# start.record()
unary_score = self.calc_unary_score(logits, labels, lens).sum(
1).squeeze(-1)
binary_score = self.calc_binary_score(labels, lens).sum(1).squeeze(-1)
# end.record()
# torch.cuda.synchronize()
# print(start.elapsed_time(end))
#
return unary_score + binary_score
def calc_norm_score(self, logits, lens):
# start = torch.cuda.Event(enable_timing=True)
# end = torch.cuda.Event(enable_timing=True)
# start.record()
batch_size, _, _ = logits.size()
alpha = logits.new_full((batch_size, self.label_size), -100.0)
alpha[:, self.start] = 0
lens_ = lens.clone()
logits_t = logits.transpose(1, 0)
for logit in logits_t:
logit_exp = logit.unsqueeze(-1).expand(batch_size,
self.label_size,
self.label_size)
alpha_exp = alpha.unsqueeze(1).expand(batch_size,
self.label_size,
self.label_size)
trans_exp = self.transition.unsqueeze(0).expand_as(alpha_exp)
mat = logit_exp + alpha_exp + trans_exp
alpha_nxt = log_sum_exp(mat, 2).squeeze(-1)
mask = (lens_ > 0).float().unsqueeze(-1).expand_as(alpha)
alpha = mask * alpha_nxt + (1 - mask) * alpha
lens_ = lens_ - 1
alpha = alpha + self.transition[self.end].unsqueeze(0).expand_as(alpha)
norm = log_sum_exp(alpha, 1).squeeze(-1)
# end.record()
# torch.cuda.synchronize()
# print(start.elapsed_time(end))
#
return norm
def loglik(self, logits, labels, lens):
norm_score = self.calc_norm_score(logits, lens)
gold_score = self.calc_gold_score(logits, labels, lens)
return gold_score - norm_score
def viterbi_decode(self, logits, lens):
"""Borrowed from pytorch tutorial
Arguments:
logits: [batch_size, seq_len, n_labels] FloatTensor
lens: [batch_size] LongTensor
"""
batch_size, _, n_labels = logits.size()
vit = logits.new_full((batch_size, self.label_size), -100.0)
vit[:, self.start] = 0
c_lens = lens.clone()
logits_t = logits.transpose(1, 0)
pointers = []
for logit in logits_t:
vit_exp = vit.unsqueeze(1).expand(batch_size, n_labels, n_labels)
trn_exp = self.transition.unsqueeze(0).expand_as(vit_exp)
vit_trn_sum = vit_exp + trn_exp
vt_max, vt_argmax = vit_trn_sum.max(2)
vt_max = vt_max.squeeze(-1)
vit_nxt = vt_max + logit
pointers.append(vt_argmax.squeeze(-1).unsqueeze(0))
mask = (c_lens > 0).float().unsqueeze(-1).expand_as(vit_nxt)
vit = mask * vit_nxt + (1 - mask) * vit
mask = (c_lens == 1).float().unsqueeze(-1).expand_as(vit_nxt)
vit += mask * self.transition[self.end].unsqueeze(
0).expand_as(vit_nxt)
c_lens = c_lens - 1
pointers = torch.cat(pointers)
scores, idx = vit.max(1)
paths = [idx.unsqueeze(1)]
for argmax in reversed(pointers):
idx_exp = idx.unsqueeze(-1)
idx = torch.gather(argmax, 1, idx_exp)
idx = idx.squeeze(-1)
paths.insert(0, idx.unsqueeze(1))
paths = torch.cat(paths[1:], 1)
scores = scores.squeeze(-1)
return scores, paths
def calc_conf_score_(self, logits, labels):
batch_size, _, _ = logits.size()
logits_t = logits.transpose(1, 0)
scores = [[] for _ in range(batch_size)]
pre_labels = [self.start] * batch_size
for i, logit in enumerate(logits_t):
logit_exp = logit.unsqueeze(-1).expand(batch_size,
self.label_size,
self.label_size)
trans_exp = self.transition.unsqueeze(0).expand(batch_size,
self.label_size,
self.label_size)
score = logit_exp + trans_exp
score = score.view(-1, self.label_size * self.label_size) \
.softmax(1)
for j in range(batch_size):
cur_label = labels[j][i]
cur_score = score[j][cur_label * self.label_size + pre_labels[j]]
scores[j].append(cur_score)
pre_labels[j] = cur_label
return scores
class OneIE(nn.Module):
def __init__(self,
config,
vocabs,
valid_patterns=None, guidelines = None,):
super().__init__()
self.test_potential = []
# jointly training identification and classification or splitly training
self.split_train = config.split_train
# vocabularies
self.config = config
self.vocabs = vocabs
self.entity_label_stoi = vocabs['entity_label']
self.trigger_label_stoi = vocabs['trigger_label']
self.mention_type_stoi = vocabs['mention_type']
self.entity_type_stoi = vocabs['entity_type']
self.event_type_stoi = vocabs['event_type']
self.relation_type_stoi = vocabs['relation_type']
self.role_type_stoi = vocabs['role_type']
self.entity_label_itos = {i:s for s, i in self.entity_label_stoi.items()}
self.trigger_label_itos = {i:s for s, i in self.trigger_label_stoi.items()}
self.entity_type_itos = {i: s for s, i in self.entity_type_stoi.items()}
self.event_type_itos = {i: s for s, i in self.event_type_stoi.items()}
self.relation_type_itos = {i: s for s, i in self.relation_type_stoi.items()}
self.role_type_itos = {i: s for s, i in self.role_type_stoi.items()}
self.entity_label_num = len(self.entity_label_stoi)
self.trigger_label_num = len(self.trigger_label_stoi)
self.mention_type_num = len(self.mention_type_stoi)
self.entity_type_num = len(self.entity_type_stoi)
self.event_type_num = len(self.event_type_stoi)
self.relation_type_num = len(self.relation_type_stoi)
self.role_type_num = len(self.role_type_stoi)
self.valid_relation_entity = set()
self.valid_event_role = set()
self.valid_role_entity = set()
if valid_patterns:
self.valid_event_role = valid_patterns['event_role']
self.valid_relation_entity = valid_patterns['relation_entity']
self.valid_role_entity = valid_patterns['role_entity']
try:
self.valid_relation_start_entity = valid_patterns['relation_start_entity']
self.valid_relation_end_entity = valid_patterns['relation_end_entity']
except:
pass
# ------------------------------------------------------------------------------
# if config.use_high_order_tre:
# self.tre_valid_pattern_mask = self.event_role_entity_factor_mask()
#
# ------------------------------------------------------------------------------
self.relation_directional = config.relation_directional
self.symmetric_relations = config.symmetric_relations
self.symmetric_relation_idxs = {self.relation_type_stoi[r]
for r in self.symmetric_relations}
# BERT encoder
bert_config = config.bert_config
bert_config.output_hidden_states = True
self.bert_dim = bert_config.hidden_size
self.extra_bert = config.extra_bert
self.use_extra_bert = config.use_extra_bert
if self.use_extra_bert:
self.bert_dim *= 2
if 'albert' in config.bert_model_name:
self.bert = AlbertModel(bert_config)
elif 'roberta' in config.bert_model_name:
self.bert = RobertaModel(bert_config)
elif 'scibert' in config.bert_model_name:
self.bert = BertModel(bert_config)
else:
self.bert = BertModel(bert_config)
# self.bert = BertModel(bert_config)
# breakpoint()
self.bert_dropout = nn.Dropout(p=config.bert_dropout)
self.multi_piece = config.multi_piece_strategy
# local classifiers
self.use_entity_type = config.use_entity_type
self.binary_dim = self.bert_dim * 2
linear_bias = config.linear_bias
linear_dropout = config.linear_dropout
entity_hidden_num = config.entity_hidden_num
mention_hidden_num = config.mention_hidden_num
event_hidden_num = config.event_hidden_num
relation_hidden_num = config.relation_hidden_num
role_hidden_num = config.role_hidden_num
role_input_dim = self.binary_dim + (self.entity_type_num if self.use_entity_type else 0)
# self.entity_layer_norm = nn.LayerNorm(self.bert_dim)
self.entity_label_ffn = nn.Linear(self.bert_dim, self.entity_label_num,
bias=linear_bias)
self.trigger_label_ffn = nn.Linear(self.bert_dim, self.trigger_label_num,
bias=linear_bias)
try:
self.entity_hidden_size = config.entity_hidden_size
except:
self.entity_hidden_size = self.bert_dim
if self.config.new_score:
self.unary_entity_type_reps = Parameter(torch.empty(self.entity_type_num, entity_hidden_num))
torch.nn.init.kaiming_uniform_(self.unary_entity_type_reps, a=math.sqrt(5))
self.entity_type_ffn = nn.Linear(self.bert_dim, entity_hidden_num)
self.linear_entity_dropout = nn.Dropout(p=config.linear_dropout)
else:
self.entity_type_ffn = Linears([self.bert_dim, entity_hidden_num,
self.entity_type_num],
dropout_prob=linear_dropout,
bias=linear_bias,
activation=config.linear_activation)
self.mention_type_ffn = Linears([self.bert_dim, mention_hidden_num,
self.mention_type_num],
dropout_prob=linear_dropout,
bias=linear_bias,
activation=config.linear_activation)
#===============================================================================================
if self.config.new_score:
self.unary_trigger_type_reps = Parameter(torch.empty(self.event_type_num, event_hidden_num))
torch.nn.init.kaiming_uniform_(self.unary_trigger_type_reps, a=math.sqrt(5))
self.event_type_ffn = nn.Linear(self.bert_dim, event_hidden_num)
self.linear_trigger_dropout = nn.Dropout(p=config.linear_dropout)
else:
self.event_type_ffn = Linears([self.bert_dim, event_hidden_num,
self.event_type_num],
dropout_prob=linear_dropout,
bias=linear_bias,
activation=config.linear_activation)
#===============================================================================================
self.start_entity_ffn = nn.Linear(self.bert_dim, self.entity_hidden_size)
self.end_entity_ffn = nn.Linear(self.bert_dim, self.entity_hidden_size)
if config.split_rel_ident:
self.start_entity_ident_ffn = nn.Linear(self.bert_dim, self.bert_dim)
self.end_entity_ident_ffn = nn.Linear(self.bert_dim, self.bert_dim)
self.relation_ident_ffn = Linears([self.binary_dim, relation_hidden_num,2],
dropout_prob=linear_dropout,
bias=linear_bias,
activation=config.linear_activation)
if self.config.new_score:
self.unary_relation_type_reps = Parameter(torch.empty(self.relation_type_num, self.entity_hidden_size))
torch.nn.init.kaiming_uniform_(self.unary_relation_type_reps, a=math.sqrt(5))
self.linear_start_dropout = nn.Dropout(p=config.linear_dropout)
self.linear_end_dropout = nn.Dropout(p=config.linear_dropout)
else:
self.relation_type_ffn = Linears([self.binary_dim, relation_hidden_num,
self.relation_type_num],
dropout_prob=linear_dropout,
bias=linear_bias,
activation=config.linear_activation)
#===============================================================================
self.use_guideliens = config.use_guideliens
self.relation_type_reprs = None
if config.use_guideliens:
self.guideline_piexs = torch.tensor(guidelines['piece_idx'])
self.guideline_attn_masks = torch.tensor(guidelines['attn_mask'])
self.entity_ffn = Guide_Linears([self.binary_dim, relation_hidden_num],
dropout_prob=linear_dropout,
bias=linear_bias,
activation=config.linear_activation)
self.relation_ffn = Guide_Linears([self.bert_dim, relation_hidden_num],
dropout_prob=linear_dropout,
bias=linear_bias,
activation=config.linear_activation)
#===============================================================================
if self.config.new_score:
self.unary_role_type_reps = Parameter(torch.empty(self.role_type_num, role_hidden_num))
torch.nn.init.kaiming_uniform_(self.unary_role_type_reps, a=math.sqrt(5))
self.unary_trigger_ffn = nn.Linear(self.bert_dim, role_hidden_num)
argument_dim = self.bert_dim + (self.entity_type_num if self.use_entity_type else 0)
self.unary_argument_ffn = nn.Linear(argument_dim, role_hidden_num)
self.unary_trigger_dropout = nn.Dropout(p=config.linear_dropout)
self.unary_argument_dropout = nn.Dropout(p=config.linear_dropout)
else:
self.role_type_ffn = Linears([role_input_dim, role_hidden_num,
self.role_type_num],
dropout_prob=linear_dropout,
bias=linear_bias,
activation=config.linear_activation)
# global features
self.use_global_features = config.use_global_features
#------------------------------------------------------------------------------
if self.use_global_features:
self.global_features = config.global_features
self.global_feature_maps = generate_global_feature_maps(vocabs, valid_patterns)
self.global_feature_num = sum(len(m) for k, m in self.global_feature_maps.items()
if k in self.global_features or
not self.global_features)
#
self.global_feature_weights = nn.Parameter(
torch.zeros(self.global_feature_num).fill_(-0.0001))
#------------------------------------------------------------------------------
# decoder
self.beam_size = config.beam_size
self.beta_v = config.beta_v
self.beta_e = config.beta_e
# loss functions
self.entity_criteria = torch.nn.CrossEntropyLoss()
self.event_criteria = torch.nn.CrossEntropyLoss()
self.mention_criteria = torch.nn.CrossEntropyLoss()
self.relation_criteria = torch.nn.CrossEntropyLoss()
self.role_criteria = torch.nn.CrossEntropyLoss()
if config.split_rel_ident:
self.relation_ident_criteria = torch.nn.CrossEntropyLoss()
# others
self.entity_crf = CRF(self.entity_label_stoi, bioes=False)
self.trigger_crf = CRF(self.trigger_label_stoi, bioes=False)
self.pad_vector = nn.Parameter(torch.randn(1, 1, self.bert_dim))
# -------------------------------------------------------------------------------
# high-order
# self.use_high_order = config.use_high_order
self.use_high_order_tl = config.use_high_order_tl
self.use_high_order_le = config.use_high_order_le
self.use_high_order_tre = config.use_high_order_tre
self.use_high_order_sibling = config.use_high_order_sibling
self.use_high_order_coparent = config.use_high_order_coparent
self.use_high_order_ere = config.use_high_order_ere
self.use_high_order_er = config.use_high_order_er
self.use_high_order_re_sibling = config.use_high_order_re_sibling
self.use_high_order_re_coparent = config.use_high_order_re_coparent
self.use_high_order_re_grandparent = config.use_high_order_re_grandparent
self.use_high_order_rr_coparent = config.use_high_order_rr_coparent
self.use_high_order_rr_grandparent = config.use_high_order_rr_grandparent
self.decomp_size = config.decomp_size
self.tre_decomp_size = config.tre_decomp_size
if self.use_high_order_tl:
self.trigger_tl_W = High_Linears([self.bert_dim, event_hidden_num,
self.decomp_size],dropout_prob=linear_dropout,
bias=linear_bias)
self.entity_tl_W = High_Linears([self.bert_dim, event_hidden_num,
self.decomp_size],dropout_prob=linear_dropout,
bias=linear_bias)
# self.trigger_tl_W = nn.Linear(self.bert_dim, self.decomp_size,bias=False)
# self.entity_tl_W = nn.Linear(self.bert_dim, self.decomp_size, bias=False)
self.event_type_tl_W = Parameter(torch.empty(self.event_type_num, self.decomp_size))
self.role_type_tl_W = Parameter(torch.empty(self.role_type_num, self.decomp_size))
torch.nn.init.kaiming_uniform_(self.event_type_tl_W, a=math.sqrt(5))
torch.nn.init.kaiming_uniform_(self.role_type_tl_W, a=math.sqrt(5))
if self.use_high_order_le:
if self.config.new_potential:
self.role_entity_potential = Parameter(torch.empty(self.role_type_num, self.entity_type_num))
# torch.nn.init.uniform_(self.role_entity_potential, a=0,b=1)
torch.nn.init.kaiming_uniform_(self.role_entity_potential, a=math.sqrt(5))
else:
self.trigger_le_W = High_Linears([self.bert_dim, event_hidden_num,
self.decomp_size],dropout_prob=linear_dropout,
bias=linear_bias)
self.entity_le_W = High_Linears([self.bert_dim, event_hidden_num,
self.decomp_size],dropout_prob=linear_dropout,
bias=linear_bias)
# self.trigger_le_W = nn.Linear(self.bert_dim, self.decomp_size,bias=False)
# self.entity_le_W = nn.Linear(self.bert_dim, self.decomp_size, bias=False)
self.role_type_le_W = Parameter(torch.empty(self.role_type_num, self.decomp_size))
self.entity_type_le_W = Parameter(torch.empty(self.entity_type_num, self.decomp_size))
torch.nn.init.kaiming_uniform_(self.role_type_le_W, a=math.sqrt(5))
torch.nn.init.kaiming_uniform_(self.entity_type_le_W, a=math.sqrt(5))
if self.use_high_order_tre:
if self.config.new_potential:
self.event_role_entity_potential = Parameter(torch.empty(self.event_type_num, self.role_type_num, self.entity_type_num))
# torch.nn.init.uniform_(self.event_role_entity_potential, a=0,b=1)
torch.nn.init.kaiming_uniform_(self.event_role_entity_potential, a=math.sqrt(5))
else:
self.trigger_tre_W = nn.Linear(self.bert_dim, self.tre_decomp_size,bias=True)
self.trigger_tre_dropout = nn.Dropout(p=config.linear_dropout)
self.entity_tre_W = nn.Linear(self.bert_dim, self.tre_decomp_size,bias=True)
self.entity_tre_dropout = nn.Dropout(p=config.linear_dropout)
self.event_type_W = Parameter(torch.empty(self.event_type_num-1, self.tre_decomp_size))
self.role_type_W = Parameter(torch.empty(self.role_type_num, self.tre_decomp_size))
self.entity_type_W = Parameter(torch.empty(self.entity_type_num-1, self.tre_decomp_size))
torch.nn.init.kaiming_uniform_(self.event_type_W, a=math.sqrt(5))
torch.nn.init.kaiming_uniform_(self.role_type_W, a=math.sqrt(5))
torch.nn.init.kaiming_uniform_(self.entity_type_W, a=math.sqrt(5))
if self.use_high_order_sibling:
self.trigger_sib_W = nn.Linear(self.bert_dim, self.decomp_size,bias=True)
self.trigger_sib_dropout = nn.Dropout(p=config.linear_dropout)
self.entity_sib_W = nn.Linear(self.bert_dim, self.decomp_size,bias=True)
self.entity_sib_dropout = nn.Dropout(p=config.linear_dropout)
self.role_type_sib_W = Parameter(torch.empty(self.role_type_num, self.decomp_size))
torch.nn.init.kaiming_uniform_(self.role_type_sib_W, a=math.sqrt(5))
if self.use_high_order_coparent:
self.trigger_cop_W = nn.Linear(self.bert_dim, self.decomp_size,bias=True)
self.trigger_cop_dropout = nn.Dropout(p=config.linear_dropout)
self.entity_cop_W = nn.Linear(self.bert_dim, self.decomp_size,bias=True)
self.entity_cop_dropout = nn.Dropout(p=config.linear_dropout)
self.role_type_cop_W = Parameter(torch.empty(self.role_type_num, self.decomp_size))
torch.nn.init.kaiming_uniform_(self.role_type_cop_W, a=math.sqrt(5))
if self.use_high_order_ere:
if self.config.new_potential:
if self.config.share_relation_type_reps:
self.relation_type_ere_W = nn.Linear(self.entity_hidden_size, self.decomp_size, bias=True)
self.entity_type_ere_W = nn.Linear(entity_hidden_num, self.decomp_size, bias=True)
else:
self.entity_type_ere_W = Parameter(torch.empty(self.entity_type_num-1, self.decomp_size))
self.relation_type_ere_W = Parameter(torch.empty(self.relation_type_num, self.decomp_size))
torch.nn.init.kaiming_uniform_(self.entity_type_ere_W, a=math.sqrt(5))
torch.nn.init.kaiming_uniform_(self.relation_type_ere_W, a=math.sqrt(5))
else:
self.entity_start_ere_W = nn.Linear(self.bert_dim, self.decomp_size,bias=True)
self.entity_end_ere_W = nn.Linear(self.bert_dim, self.decomp_size,bias=True)
self.ere_start_dropout = nn.Dropout(p=config.linear_dropout)
self.ere_end_dropout = nn.Dropout(p=config.linear_dropout)
if self.config.share_relation_type_reps:
self.relation_type_ere_W = nn.Linear(self.entity_hidden_size, self.decomp_size, bias=True)
self.entity_type_ere_W = nn.Linear(entity_hidden_num, self.decomp_size, bias=True)
else:
self.entity_type_ere_W = Parameter(torch.empty(self.entity_type_num-1, self.decomp_size))
self.relation_type_ere_W = Parameter(torch.empty(self.relation_type_num, self.decomp_size))
torch.nn.init.kaiming_uniform_(self.entity_type_ere_W, a=math.sqrt(5))
torch.nn.init.kaiming_uniform_(self.relation_type_ere_W, a=math.sqrt(5))
if self.use_high_order_er:
if self.config.new_potential:
self.entity_relation_potential = Parameter(torch.empty(self.entity_type_num-1, self.relation_type_num))
self.relation_entity_potential = Parameter(torch.empty(self.relation_type_num, self.entity_type_num-1))
torch.nn.init.kaiming_uniform_(self.entity_relation_potential, a=math.sqrt(5))
torch.nn.init.kaiming_uniform_(self.relation_entity_potential, a=math.sqrt(5))
else:
self.start_entity_er_W = nn.Linear(self.bert_dim, self.decomp_size,bias=True)
self.end_entity_er_W = nn.Linear(self.bert_dim, self.decomp_size,bias=True)
self.er_start_dropout = nn.Dropout(p=config.linear_dropout)
self.er_end_dropout = nn.Dropout(p=config.linear_dropout)
self.entity_type_er_W = Parameter(torch.empty(self.entity_type_num-1, self.decomp_size))
if self.config.share_relation_type_reps:
self.relation_type_er_W = nn.Linear(self.entity_hidden_size, self.decomp_size, bias=True)
else:
self.relation_type_er_W = Parameter(torch.empty(self.relation_type_num, self.decomp_size))
# self.er_rel_type_dropout = nn.Dropout(p=config.linear_dropout)
torch.nn.init.kaiming_uniform_(self.relation_type_er_W, a=math.sqrt(5))
torch.nn.init.kaiming_uniform_(self.entity_type_er_W, a=math.sqrt(5))
if self.use_high_order_re_sibling:
if self.config.decomp:
self.entity_start_re_sib_W = nn.Linear(self.bert_dim, self.config.entity_hidden_size,bias=True)
self.entity_end_re_sib_W = nn.Linear(self.bert_dim, self.entity_hidden_size,bias=True)
self.sib_start_dropout = nn.Dropout(p=config.linear_dropout)
self.sib_end_dropout = nn.Dropout(p=config.linear_dropout)
self.entity_start_re_sib_decomp_ffn = nn.Linear(self.config.entity_hidden_size,self.config.decomp_size,bias=False)
self.entity_end_re_sib_decomp_ffn = nn.Linear(self.config.entity_hidden_size,self.config.decomp_size,bias=False)
else:
self.entity_start_re_sib_W = nn.Linear(self.bert_dim, self.config.decomp_size,bias=True)
self.entity_end_re_sib_W = nn.Linear(self.bert_dim, self.config.decomp_size,bias=True)
self.sib_start_dropout = nn.Dropout(p=config.linear_dropout)
self.sib_end_dropout = nn.Dropout(p=config.linear_dropout)
if self.config.share_relation_type_reps:
self.relation_type_re_sib_W = nn.Linear(self.entity_hidden_size, self.decomp_size, bias=False)
else:
self.relation_type_re_sib_W = Parameter(torch.empty(self.relation_type_num, self.decomp_size))
torch.nn.init.kaiming_uniform_(self.relation_type_re_sib_W, a=math.sqrt(5))
#---------------------------------------------------------------------------
# self.relation_type_sib_dropout = nn.Dropout(p=config.linear_dropout)
#---------------------------------------------------------------------------
if self.use_high_order_re_coparent:
if self.config.decomp:
self.entity_start_re_cop_W = nn.Linear(self.bert_dim, self.entity_hidden_size,bias=True)
self.entity_end_re_cop_W = nn.Linear(self.bert_dim, self.entity_hidden_size,bias=True)
self.cop_start_dropout = nn.Dropout(p=config.linear_dropout)
self.cop_end_dropout = nn.Dropout(p=config.linear_dropout)
self.entity_start_re_cop_decomp_ffn = nn.Linear(self.config.entity_hidden_size,self.config.decomp_size,bias=False)
self.entity_end_re_cop_decomp_ffn = nn.Linear(self.config.entity_hidden_size,self.config.decomp_size,bias=False)
else:
self.entity_start_re_cop_W = nn.Linear(self.bert_dim, self.config.decomp_size,bias=True)
self.entity_end_re_cop_W = nn.Linear(self.bert_dim, self.config.decomp_size,bias=True)
self.cop_start_dropout = nn.Dropout(p=config.linear_dropout)
self.cop_end_dropout = nn.Dropout(p=config.linear_dropout)
if self.config.share_relation_type_reps:
self.relation_type_re_cop_W = nn.Linear(self.entity_hidden_size, self.decomp_size, bias=False)
else:
self.relation_type_re_cop_W = Parameter(torch.empty(self.relation_type_num, self.decomp_size))
torch.nn.init.kaiming_uniform_(self.relation_type_re_cop_W, a=math.sqrt(5))
if self.use_high_order_re_grandparent:
if self.config.decomp:
self.entity_start_re_gp_W = nn.Linear(self.bert_dim, self.entity_hidden_size,bias=True)
self.entity_mid_re_gp_W = nn.Linear(self.bert_dim, self.entity_hidden_size,bias=True)
self.entity_end_re_gp_W = nn.Linear(self.bert_dim, self.entity_hidden_size,bias=True)
self.gp_start_dropout = nn.Dropout(p=config.linear_dropout)
self.gp_mid_dropout = nn.Dropout(p=config.linear_dropout)
self.gp_end_dropout = nn.Dropout(p=config.linear_dropout)
self.entity_start_re_gp_decomp_ffn = nn.Linear(self.config.entity_hidden_size,self.config.decomp_size,bias=False)
self.entity_mid_re_gp_decomp_ffn = nn.Linear(self.config.entity_hidden_size,self.config.decomp_size,bias=False)
self.entity_end_re_gp_decomp_ffn = nn.Linear(self.config.entity_hidden_size,self.config.decomp_size,bias=False)
else:
self.entity_start_re_gp_W = nn.Linear(self.bert_dim, self.config.decomp_size,bias=True)
self.entity_mid_re_gp_W = nn.Linear(self.bert_dim, self.config.decomp_size,bias=True)
self.entity_end_re_gp_W = nn.Linear(self.bert_dim, self.config.decomp_size,bias=True)
self.gp_start_dropout = nn.Dropout(p=config.linear_dropout)
self.gp_mid_dropout = nn.Dropout(p=config.linear_dropout)
self.gp_end_dropout = nn.Dropout(p=config.linear_dropout)