-
Notifications
You must be signed in to change notification settings - Fork 24
/
KM_parser.py
executable file
·1994 lines (1673 loc) · 83.5 KB
/
KM_parser.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 functools
import numpy as np
import sys
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.init as init
import transformers
use_cuda = torch.cuda.is_available()
if use_cuda:
torch_t = torch.cuda
def from_numpy(ndarray):
if float(sys.version[:3]) <= 3.6:
return eval('torch.from_numpy(ndarray).pin_memory().cuda(async=True)')
else:
return torch.from_numpy(ndarray).pin_memory().cuda(non_blocking=True)
else:
print("Not using CUDA!")
torch_t = torch
from torch import from_numpy
import pyximport
pyximport.install(setup_args={"include_dirs": np.get_include()})
#import src_dep_const_test.chart_helper as chart_helper
import hpsg_decoder
import const_decoder
import makehp
import utils
import trees
START = "<START>"
STOP = "<STOP>"
UNK = "<UNK>"
ROOT = "<START>"
Sub_Head = "<H>"
No_Head = "<N>"
DTYPE = torch.uint8 if float(sys.version[:3]) < 3.7 else torch.bool
TAG_UNK = "UNK"
ROOT_TYPE = "<ROOT_TYPE>"
# Assumes that these control characters are not present in treebank text
CHAR_UNK = "\0"
CHAR_START_SENTENCE = "\1"
CHAR_START_WORD = "\2"
CHAR_STOP_WORD = "\3"
CHAR_STOP_SENTENCE = "\4"
CHAR_PAD = "\5"
BERT_TOKEN_MAPPING = {
"-LRB-": "(",
"-RRB-": ")",
"-LCB-": "{",
"-RCB-": "}",
"-LSB-": "[",
"-RSB-": "]",
"``": '"',
"''": '"',
"`": "'",
'«': '"',
'»': '"',
'‘': "'",
'’': "'",
'“': '"',
'”': '"',
'„': '"',
'‹': "'",
'›': "'",
"\u2013": "--", # en dash
"\u2014": "--", # em dash
}
class BatchIndices:
"""
Batch indices container class (used to implement packed batches)
"""
def __init__(self, batch_idxs_np):
self.batch_idxs_np = batch_idxs_np
self.batch_idxs_torch = from_numpy(batch_idxs_np)
self.batch_size = int(1 + np.max(batch_idxs_np))
batch_idxs_np_extra = np.concatenate([[-1], batch_idxs_np, [-1]])
self.boundaries_np = np.nonzero(batch_idxs_np_extra[1:] != batch_idxs_np_extra[:-1])[0]
self.seq_lens_np = self.boundaries_np[1:] - self.boundaries_np[:-1]
assert len(self.seq_lens_np) == self.batch_size
self.max_len = int(np.max(self.boundaries_np[1:] - self.boundaries_np[:-1]))
#
class FeatureDropoutFunction(torch.autograd.function.InplaceFunction):
@classmethod
def forward(cls, ctx, input, batch_idxs, p=0.5, train=False, inplace=False):
if p < 0 or p > 1:
raise ValueError("dropout probability has to be between 0 and 1, "
"but got {}".format(p))
ctx.p = p
ctx.train = train
ctx.inplace = inplace
if ctx.inplace:
ctx.mark_dirty(input)
output = input
else:
output = input.clone()
if ctx.p > 0 and ctx.train:
ctx.noise = input.new().resize_(batch_idxs.batch_size, input.size(1))
if ctx.p == 1:
ctx.noise.fill_(0)
else:
ctx.noise.bernoulli_(1 - ctx.p).div_(1 - ctx.p)
ctx.noise = ctx.noise[batch_idxs.batch_idxs_torch, :]
output.mul_(ctx.noise)
return output
@staticmethod
def backward(ctx, grad_output):
if ctx.p > 0 and ctx.train:
return grad_output.mul(ctx.noise), None, None, None, None
else:
return grad_output, None, None, None, None
#
class FeatureDropout(nn.Module):
"""
Feature-level dropout: takes an input of size len x num_features and drops
each feature with probabibility p. A feature is dropped across the full
portion of the input that corresponds to a single batch element.
"""
def __init__(self, p=0.5, inplace=False):
super().__init__()
if p < 0 or p > 1:
raise ValueError("dropout probability has to be between 0 and 1, "
"but got {}".format(p))
self.p = p
self.inplace = inplace
def forward(self, input, batch_idxs):
return FeatureDropoutFunction.apply(input, batch_idxs, self.p, self.training, self.inplace)
#
class LayerNormalization(nn.Module):
def __init__(self, d_hid, eps=1e-3, affine=True):
super(LayerNormalization, self).__init__()
self.eps = eps
self.affine = affine
if self.affine:
self.a_2 = nn.Parameter(torch.ones(d_hid), requires_grad=True)
self.b_2 = nn.Parameter(torch.zeros(d_hid), requires_grad=True)
def forward(self, z):
if z.size(-1) == 1:
return z
mu = torch.mean(z, keepdim=True, dim=-1)
sigma = torch.std(z, keepdim=True, dim=-1)
ln_out = (z - mu.expand_as(z)) / (sigma.expand_as(z) + self.eps)
if self.affine:
ln_out = ln_out * self.a_2.expand_as(ln_out) + self.b_2.expand_as(ln_out)
return ln_out
#
class ScaledAttention(nn.Module):
def __init__(self, hparams, attention_dropout=0.1):
super(ScaledAttention, self).__init__()
self.hparams = hparams
self.temper = hparams.d_model ** 0.5
self.dropout = nn.Dropout(attention_dropout)
self.softmax = nn.Softmax(dim=1)
def forward(self, q, k, v, attn_mask=None):
# q: [batch, slot, feat]
# k: [batch, slot, feat]
# v: [batch, slot, feat]
attn = torch.bmm(q, k.transpose(1, 2)) / self.temper
if attn_mask is not None:
assert attn_mask.size() == attn.size(), \
'Attention mask shape {} mismatch ' \
'with Attention logit tensor shape ' \
'{}.'.format(attn_mask.size(), attn.size())
attn.data.masked_fill_(attn_mask, -float('inf'))
attn = self.softmax(attn.transpose(1, 2)).transpose(1, 2)
attn = self.dropout(attn)
output = torch.bmm(attn, v)
return output, attn
# %%
class ScaledDotProductAttention(nn.Module):
def __init__(self, d_model, attention_dropout=0.1):
super(ScaledDotProductAttention, self).__init__()
self.temper = d_model ** 0.5
self.dropout = nn.Dropout(attention_dropout)
self.softmax = nn.Softmax(dim=-1)
def forward(self, q, k, v, attn_mask=None):
# q: [batch, slot, feat] or (batch * d_l) x max_len x d_k
# k: [batch, slot, feat] or (batch * d_l) x max_len x d_k
# v: [batch, slot, feat] or (batch * d_l) x max_len x d_v
# q in LAL is (batch * d_l) x 1 x d_k
attn = torch.bmm(q, k.transpose(1, 2)) / self.temper # (batch * d_l) x max_len x max_len
# in LAL, gives: (batch * d_l) x 1 x max_len
# attention weights from each word to each word, for each label
# in best model (repeated q): attention weights from label (as vector weights) to each word
if attn_mask is not None:
assert attn_mask.size() == attn.size(), \
'Attention mask shape {} mismatch ' \
'with Attention logit tensor shape ' \
'{}.'.format(attn_mask.size(), attn.size())
attn.data.masked_fill_(attn_mask, -float('inf'))
attn = self.softmax(attn)
# Note that this makes the distribution not sum to 1. At some point it
# may be worth researching whether this is the right way to apply
# dropout to the attention.
# Note that the t2t code also applies dropout in this manner
attn = self.dropout(attn)
output = torch.bmm(attn, v) # (batch * d_l) x max_len x d_v
# in LAL, gives: (batch * d_l) x 1 x d_v
return output, attn
#
class MultiHeadAttention(nn.Module):
"""
Multi-head attention module
"""
def __init__(self, hparams, n_head, d_model, d_k, d_v, residual_dropout=0.1, attention_dropout=0.1, d_positional=None):
super(MultiHeadAttention, self).__init__()
self.n_head = n_head
self.d_k = d_k
self.d_v = d_v
self.hparams = hparams
if d_positional is None:
self.partitioned = False
else:
self.partitioned = True
if self.partitioned:
self.d_content = d_model - d_positional
self.d_positional = d_positional
self.w_qs1 = nn.Parameter(torch_t.FloatTensor(n_head, self.d_content, d_k // 2))
self.w_ks1 = nn.Parameter(torch_t.FloatTensor(n_head, self.d_content, d_k // 2))
self.w_vs1 = nn.Parameter(torch_t.FloatTensor(n_head, self.d_content, d_v // 2))
self.w_qs2 = nn.Parameter(torch_t.FloatTensor(n_head, self.d_positional, d_k // 2))
self.w_ks2 = nn.Parameter(torch_t.FloatTensor(n_head, self.d_positional, d_k // 2))
self.w_vs2 = nn.Parameter(torch_t.FloatTensor(n_head, self.d_positional, d_v // 2))
init.xavier_normal_(self.w_qs1)
init.xavier_normal_(self.w_ks1)
init.xavier_normal_(self.w_vs1)
init.xavier_normal_(self.w_qs2)
init.xavier_normal_(self.w_ks2)
init.xavier_normal_(self.w_vs2)
else:
self.w_qs = nn.Parameter(torch_t.FloatTensor(n_head, d_model, d_k))
self.w_ks = nn.Parameter(torch_t.FloatTensor(n_head, d_model, d_k))
self.w_vs = nn.Parameter(torch_t.FloatTensor(n_head, d_model, d_v))
init.xavier_normal_(self.w_qs)
init.xavier_normal_(self.w_ks)
init.xavier_normal_(self.w_vs)
self.attention = ScaledDotProductAttention(d_model, attention_dropout=attention_dropout)
self.layer_norm = LayerNormalization(d_model)
if not self.partitioned:
# The lack of a bias term here is consistent with the t2t code, though
# in my experiments I have never observed this making a difference.
self.proj = nn.Linear(n_head*d_v, d_model, bias=False)
else:
self.proj1 = nn.Linear(n_head*(d_v//2), self.d_content, bias=False)
self.proj2 = nn.Linear(n_head*(d_v//2), self.d_positional, bias=False)
self.residual_dropout = FeatureDropout(residual_dropout)
def split_qkv_packed(self, inp, qk_inp=None):
v_inp_repeated = inp.repeat(self.n_head, 1).view(self.n_head, -1, inp.size(-1)) # n_head x len_inp x d_model
if qk_inp is None:
qk_inp_repeated = v_inp_repeated
else:
qk_inp_repeated = qk_inp.repeat(self.n_head, 1).view(self.n_head, -1, qk_inp.size(-1))
if not self.partitioned:
q_s = torch.bmm(qk_inp_repeated, self.w_qs) # n_head x len_inp x d_k
k_s = torch.bmm(qk_inp_repeated, self.w_ks) # n_head x len_inp x d_k
v_s = torch.bmm(v_inp_repeated, self.w_vs) # n_head x len_inp x d_v
else:
q_s = torch.cat([
torch.bmm(qk_inp_repeated[:,:,:self.d_content], self.w_qs1),
torch.bmm(qk_inp_repeated[:,:,self.d_content:], self.w_qs2),
], -1)
k_s = torch.cat([
torch.bmm(qk_inp_repeated[:,:,:self.d_content], self.w_ks1),
torch.bmm(qk_inp_repeated[:,:,self.d_content:], self.w_ks2),
], -1)
v_s = torch.cat([
torch.bmm(v_inp_repeated[:,:,:self.d_content], self.w_vs1),
torch.bmm(v_inp_repeated[:,:,self.d_content:], self.w_vs2),
], -1)
return q_s, k_s, v_s
def pad_and_rearrange(self, q_s, k_s, v_s, batch_idxs):
# Input is padded representation: n_head x len_inp x d
# Output is packed representation: (n_head * mb_size) x len_padded x d
# (along with masks for the attention and output)
n_head = self.n_head
d_k, d_v = self.d_k, self.d_v
len_padded = batch_idxs.max_len
mb_size = batch_idxs.batch_size
q_padded = q_s.new_zeros((n_head, mb_size, len_padded, d_k))
k_padded = k_s.new_zeros((n_head, mb_size, len_padded, d_k))
v_padded = v_s.new_zeros((n_head, mb_size, len_padded, d_v))
invalid_mask = q_s.new_ones((mb_size, len_padded), dtype=DTYPE)
for i, (start, end) in enumerate(zip(batch_idxs.boundaries_np[:-1], batch_idxs.boundaries_np[1:])):
q_padded[:,i,:end-start,:] = q_s[:,start:end,:]
k_padded[:,i,:end-start,:] = k_s[:,start:end,:]
v_padded[:,i,:end-start,:] = v_s[:,start:end,:]
invalid_mask[i, :end-start].fill_(False)
return(
q_padded.view(-1, len_padded, d_k),
k_padded.view(-1, len_padded, d_k),
v_padded.view(-1, len_padded, d_v),
invalid_mask.unsqueeze(1).expand(mb_size, len_padded, len_padded).repeat(n_head, 1, 1),
(~invalid_mask).repeat(n_head, 1),
)
def combine_v(self, outputs):
# Combine attention information from the different heads
n_head = self.n_head
outputs = outputs.view(n_head, -1, self.d_v) # n_head x len_inp x d_kv
if not self.partitioned:
# Switch from n_head x len_inp x d_v to len_inp x (n_head * d_v)
outputs = torch.transpose(outputs, 0, 1).contiguous().view(-1, n_head * self.d_v)
# Project back to residual size
outputs = self.proj(outputs)
else:
d_v1 = self.d_v // 2
outputs1 = outputs[:,:,:d_v1]
outputs2 = outputs[:,:,d_v1:]
outputs1 = torch.transpose(outputs1, 0, 1).contiguous().view(-1, n_head * d_v1)
outputs2 = torch.transpose(outputs2, 0, 1).contiguous().view(-1, n_head * d_v1)
outputs = torch.cat([
self.proj1(outputs1),
self.proj2(outputs2),
], -1)
return outputs
def forward(self, inp, batch_idxs, qk_inp=None):
residual = inp
# While still using a packed representation, project to obtain the
# query/key/value for each head
q_s, k_s, v_s = self.split_qkv_packed(inp, qk_inp=qk_inp)
# n_head x len_inp x d_kv
# Switch to padded representation, perform attention, then switch back
q_padded, k_padded, v_padded, attn_mask, output_mask = self.pad_and_rearrange(q_s, k_s, v_s, batch_idxs)
# (n_head * batch) x len_padded x d_kv
outputs_padded, attns_padded = self.attention(
q_padded, k_padded, v_padded,
attn_mask=attn_mask,
)
outputs = outputs_padded[output_mask]
# (n_head * len_inp) x d_kv
outputs = self.combine_v(outputs)
# len_inp x d_model
outputs = self.residual_dropout(outputs, batch_idxs)
return self.layer_norm(outputs + residual), attns_padded
#
class PositionwiseFeedForward(nn.Module):
"""
A position-wise feed forward module.
Projects to a higher-dimensional space before applying ReLU, then projects
back.
"""
def __init__(self, d_hid, d_ff, relu_dropout=0.1, residual_dropout=0.1):
super(PositionwiseFeedForward, self).__init__()
self.w_1 = nn.Linear(d_hid, d_ff)
self.w_2 = nn.Linear(d_ff, d_hid)
self.layer_norm = LayerNormalization(d_hid)
self.relu_dropout = FeatureDropout(relu_dropout)
self.residual_dropout = FeatureDropout(residual_dropout)
self.relu = nn.ReLU()
def forward(self, x, batch_idxs):
residual = x
output = self.w_1(x)
output = self.relu_dropout(self.relu(output), batch_idxs)
output = self.w_2(output)
output = self.residual_dropout(output, batch_idxs)
return self.layer_norm(output + residual)
#
class PartitionedPositionwiseFeedForward(nn.Module):
def __init__(self, d_hid, d_ff, d_positional, relu_dropout=0.1, residual_dropout=0.1):
super().__init__()
self.d_content = d_hid - d_positional
self.w_1c = nn.Linear(self.d_content, d_ff//2)
self.w_1p = nn.Linear(d_positional, d_ff//2)
self.w_2c = nn.Linear(d_ff//2, self.d_content)
self.w_2p = nn.Linear(d_ff//2, d_positional)
self.layer_norm = LayerNormalization(d_hid)
self.relu_dropout = FeatureDropout(relu_dropout)
self.residual_dropout = FeatureDropout(residual_dropout)
self.relu = nn.ReLU()
def forward(self, x, batch_idxs):
residual = x
xc = x[:, :self.d_content]
xp = x[:, self.d_content:]
outputc = self.w_1c(xc)
outputc = self.relu_dropout(self.relu(outputc), batch_idxs)
outputc = self.w_2c(outputc)
outputp = self.w_1p(xp)
outputp = self.relu_dropout(self.relu(outputp), batch_idxs)
outputp = self.w_2p(outputp)
output = torch.cat([outputc, outputp], -1)
output = self.residual_dropout(output, batch_idxs)
return self.layer_norm(output + residual)
#
class MultiLevelEmbedding(nn.Module):
def __init__(self,
num_embeddings_list,
d_embedding,
hparams,
d_positional=None,
max_len=300,
normalize=True,
dropout=0.1,
timing_dropout=0.0,
emb_dropouts_list=None,
extra_content_dropout=None,
word_table_np = None,
**kwargs):
super().__init__()
self.d_embedding = d_embedding
self.partitioned = d_positional is not None
self.hparams = hparams
if self.partitioned:
self.d_positional = d_positional
self.d_content = self.d_embedding - self.d_positional
else:
self.d_positional = self.d_embedding
self.d_content = self.d_embedding
if emb_dropouts_list is None:
emb_dropouts_list = [0.0] * len(num_embeddings_list)
assert len(emb_dropouts_list) == len(num_embeddings_list)
if word_table_np is not None:
self.pretrain_dim = word_table_np.shape[1]
else:
self.pretrain_dim = 0
embs = []
emb_dropouts = []
cun = len(num_embeddings_list)*2
for i, (num_embeddings, emb_dropout) in enumerate(zip(num_embeddings_list, emb_dropouts_list)):
if hparams.use_cat:
if i == len(num_embeddings_list) - 1:
#last is word
emb = nn.Embedding(num_embeddings, self.d_content//cun - self.pretrain_dim, **kwargs)
else :
emb = nn.Embedding(num_embeddings, self.d_content//cun, **kwargs)
else :
emb = nn.Embedding(num_embeddings, self.d_content - self.pretrain_dim, **kwargs)
embs.append(emb)
emb_dropout = FeatureDropout(emb_dropout)
emb_dropouts.append(emb_dropout)
if word_table_np is not None:
self.pretrain_emb = nn.Embedding(word_table_np.shape[0], self.pretrain_dim)
self.pretrain_emb.weight.data.copy_(torch.from_numpy(word_table_np))
self.pretrain_emb.weight.requires_grad_(False)
self.pretrain_emb_dropout = FeatureDropout(0.33)
self.embs = nn.ModuleList(embs)
self.emb_dropouts = nn.ModuleList(emb_dropouts)
if extra_content_dropout is not None:
self.extra_content_dropout = FeatureDropout(extra_content_dropout)
else:
self.extra_content_dropout = None
if normalize:
self.layer_norm = LayerNormalization(d_embedding)
else:
self.layer_norm = lambda x: x
self.dropout = FeatureDropout(dropout)
self.timing_dropout = FeatureDropout(timing_dropout)
# Learned embeddings
self.max_len = max_len
self.position_table = nn.Parameter(torch_t.FloatTensor(max_len, self.d_positional))
init.normal_(self.position_table)
def forward(self, xs, pre_words_idxs, batch_idxs, extra_content_annotations=None):
content_annotations = [
emb_dropout(emb(x), batch_idxs)
for x, emb, emb_dropout in zip(xs, self.embs, self.emb_dropouts)
]
if self.hparams.use_cat:
content_annotations = torch.cat(content_annotations, dim = -1)
else :
content_annotations = sum(content_annotations)
if self.pretrain_dim != 0:
content_annotations = torch.cat([content_annotations, self.pretrain_emb_dropout(self.pretrain_emb(pre_words_idxs), batch_idxs)], dim = 1)
if extra_content_annotations is not None:
if self.extra_content_dropout is not None:
extra_content_annotations = self.extra_content_dropout(extra_content_annotations, batch_idxs)
if self.hparams.use_cat:
content_annotations = torch.cat(
[content_annotations, extra_content_annotations], dim=-1)
else:
content_annotations += extra_content_annotations
timing_signal = []
for seq_len in batch_idxs.seq_lens_np:
this_seq_len = seq_len
timing_signal.append(self.position_table[:this_seq_len,:])
this_seq_len -= self.max_len
while this_seq_len > 0:
timing_signal.append(self.position_table[:this_seq_len,:])
this_seq_len -= self.max_len
timing_signal = torch.cat(timing_signal, dim=0)
timing_signal = self.timing_dropout(timing_signal, batch_idxs)
# Combine the content and timing signals
if self.partitioned:
annotations = torch.cat([content_annotations, timing_signal], 1)
else:
annotations = content_annotations + timing_signal
#print(annotations.shape)
annotations = self.layer_norm(self.dropout(annotations, batch_idxs))
content_annotations = self.dropout(content_annotations, batch_idxs)
return annotations, content_annotations, timing_signal, batch_idxs
#
class CharacterLSTM(nn.Module):
def __init__(self, num_embeddings, d_embedding, d_out,
char_dropout=0.0,
normalize=False,
**kwargs):
super(CharacterLSTM, self).__init__()
self.d_embedding = d_embedding
self.d_out = d_out
self.lstm = nn.LSTM(self.d_embedding, self.d_out // 2, num_layers=1, bidirectional=True)
self.emb = nn.Embedding(num_embeddings, self.d_embedding, **kwargs)
self.char_dropout = nn.Dropout(char_dropout)
if normalize:
print("This experiment: layer-normalizing after character LSTM")
self.layer_norm = LayerNormalization(self.d_out, affine=False)
else:
self.layer_norm = lambda x: x
def forward(self, chars_padded_np, word_lens_np, batch_idxs):
# copy to ensure nonnegative stride for successful transfer to pytorch
decreasing_idxs_np = np.argsort(word_lens_np)[::-1].copy()
decreasing_idxs_torch = from_numpy(decreasing_idxs_np)
decreasing_idxs_torch.requires_grad_(False)
chars_padded = from_numpy(chars_padded_np[decreasing_idxs_np])
chars_padded.requires_grad_(False)
word_lens = from_numpy(word_lens_np[decreasing_idxs_np])
inp_sorted = nn.utils.rnn.pack_padded_sequence(chars_padded, word_lens_np[decreasing_idxs_np], batch_first=True)
inp_sorted_emb = nn.utils.rnn.PackedSequence(
self.char_dropout(self.emb(inp_sorted.data)),
inp_sorted.batch_sizes)
_, (lstm_out, _) = self.lstm(inp_sorted_emb)
lstm_out = torch.cat([lstm_out[0], lstm_out[1]], -1)
# Undo sorting by decreasing word length
res = torch.zeros_like(lstm_out)
res.index_copy_(0, decreasing_idxs_torch, lstm_out)
res = self.layer_norm(res)
return res
def get_elmo_class():
# Avoid a hard dependency by only importing Elmo if it's being used
from allennlp.modules.elmo import Elmo
class ModElmo(Elmo):
def forward(self, inputs):
"""
Unlike Elmo.forward, return vector representations for bos/eos tokens
This modified version does not support extra tensor dimensions
Parameters
----------
inputs : ``torch.autograd.Variable``
Shape ``(batch_size, timesteps, 50)`` of character ids representing the current batch.
Returns
-------
Dict with keys:
``'elmo_representations'``: ``List[torch.autograd.Variable]``
A ``num_output_representations`` list of ELMo representations for the input sequence.
Each representation is shape ``(batch_size, timesteps + 2, embedding_dim)``
``'mask'``: ``torch.autograd.Variable``
Shape ``(batch_size, timesteps + 2)`` long tensor with sequence mask.
"""
# reshape the input if needed
original_shape = inputs.size()
timesteps, num_characters = original_shape[-2:]
assert len(original_shape) == 3, "Only 3D tensors supported here"
reshaped_inputs = inputs
# run the biLM
bilm_output = self._elmo_lstm(reshaped_inputs)
layer_activations = bilm_output['activations']
mask_with_bos_eos = bilm_output['mask']
# compute the elmo representations
representations = []
for i in range(len(self._scalar_mixes)):
scalar_mix = getattr(self, 'scalar_mix_{}'.format(i))
representation_with_bos_eos = scalar_mix(layer_activations, mask_with_bos_eos)
# We don't remove bos/eos here!
representations.append(self._dropout(representation_with_bos_eos))
mask = mask_with_bos_eos
elmo_representations = representations
return {'elmo_representations': elmo_representations, 'mask': mask}
return ModElmo
def get_xlnet(xlnet_model, xlnet_do_lower_case):
# Avoid a hard dependency on BERT by only importing it if it's being used
from transformers import (WEIGHTS_NAME, XLNetModel,
XLMConfig, XLMForSequenceClassification,
XLMTokenizer, XLNetConfig,
XLNetForSequenceClassification,
XLNetTokenizer)
tokenizer = XLNetTokenizer.from_pretrained(xlnet_model, do_lower_case=xlnet_do_lower_case)
xlnet = XLNetModel.from_pretrained(xlnet_model)
return tokenizer, xlnet
def get_roberta(roberta_model, roberta_do_lower_case):
# Avoid a hard dependency on BERT by only importing it if it's being used
from transformers import (WEIGHTS_NAME, RobertaModel,
RobertaConfig,
RobertaForSequenceClassification,
RobertaTokenizer)
tokenizer = RobertaTokenizer.from_pretrained(roberta_model, do_lower_case=roberta_do_lower_case, add_special_tokens=True)
roberta = RobertaModel.from_pretrained(roberta_model)
return tokenizer, roberta
def get_bert(bert_model, bert_do_lower_case):
# Avoid a hard dependency on BERT by only importing it if it's being used
from pretrained_bert import BertTokenizer, BertModel
if bert_model.endswith('.tar.gz'):
tokenizer = BertTokenizer.from_pretrained(bert_model.replace('.tar.gz', '-vocab.txt'), do_lower_case=bert_do_lower_case)
else:
tokenizer = BertTokenizer.from_pretrained(bert_model, do_lower_case=bert_do_lower_case)
bert = BertModel.from_pretrained(bert_model)
return tokenizer, bert
# def get_bert(bert_model, bert_do_lower_case):
# # Avoid a hard dependency on BERT by only importing it if it's being used
# from pytorch_transformers import BertTokenizer, BertModel
# if bert_model.endswith('.tar.gz'):
# tokenizer = BertTokenizer.from_pretrained(bert_model.replace('.tar.gz', '-vocab.txt'), do_lower_case=bert_do_lower_case)
# else:
# tokenizer = BertTokenizer.from_pretrained(bert_model, do_lower_case=bert_do_lower_case)
# bert = BertModel.from_pretrained(bert_model)
# return tokenizer, bert
#
class BiLinear(nn.Module):
'''
Bi-linear layer
'''
def __init__(self, left_features, right_features, out_features, bias=True):
'''
Args:
left_features: size of left input
right_features: size of right input
out_features: size of output
bias: If set to False, the layer will not learn an additive bias.
Default: True
'''
super(BiLinear, self).__init__()
self.left_features = left_features
self.right_features = right_features
self.out_features = out_features
self.U = nn.Parameter(torch.Tensor(self.out_features, self.left_features, self.right_features))
self.W_l = nn.Parameter(torch.Tensor(self.out_features, self.left_features))
self.W_r = nn.Parameter(torch.Tensor(self.out_features, self.left_features))
if bias:
self.bias = nn.Parameter(torch.Tensor(out_features))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
nn.init.xavier_uniform_(self.W_l)
nn.init.xavier_uniform_(self.W_r)
nn.init.constant_(self.bias, 0.)
nn.init.xavier_uniform_(self.U)
def forward(self, input_left, input_right):
'''
Args:
input_left: Tensor
the left input tensor with shape = [batch1, batch2, ..., left_features]
input_right: Tensor
the right input tensor with shape = [batch1, batch2, ..., right_features]
Returns:
'''
# convert left and right input to matrices [batch, left_features], [batch, right_features]
input_left = input_left.view(-1, self.left_features)
input_right = input_right.view(-1, self.right_features)
# output [batch, out_features]
output = nn.functional.bilinear(input_left, input_right, self.U, self.bias)
output = output + nn.functional.linear(input_left, self.W_l, None) + nn.functional.linear(input_right, self.W_r, None)
# convert back to [batch1, batch2, ..., out_features]
return output
#
class BiAAttention(nn.Module):
'''
Bi-Affine attention layer.
'''
def __init__(self, hparams):
super(BiAAttention, self).__init__()
self.hparams = hparams
self.dep_weight = nn.Parameter(torch_t.FloatTensor(hparams.d_biaffine + 1, hparams.d_biaffine + 1))
nn.init.xavier_uniform_(self.dep_weight)
def forward(self, input_d, input_e, input_s = None):
score = torch.matmul(torch.cat(
[input_d, torch_t.FloatTensor(input_d.size(0), 1).fill_(1).requires_grad_(False)],
dim=1), self.dep_weight)
score1 = torch.matmul(score, torch.transpose(torch.cat(
[input_e, torch_t.FloatTensor(input_e.size(0), 1).fill_(1).requires_grad_(False)],
dim=1), 0, 1))
return score1
class Dep_score(nn.Module):
def __init__(self, hparams, num_labels):
super(Dep_score, self).__init__()
self.dropout_out = nn.Dropout2d(p=0.33)
self.hparams = hparams
out_dim = hparams.d_biaffine#d_biaffine
self.arc_h = nn.Linear(hparams.annotation_dim, hparams.d_biaffine)
self.arc_c = nn.Linear(hparams.annotation_dim, hparams.d_biaffine)
self.attention = BiAAttention(hparams)
self.type_h = nn.Linear(hparams.annotation_dim, hparams.d_label_hidden)
self.type_c = nn.Linear(hparams.annotation_dim, hparams.d_label_hidden)
self.bilinear = BiLinear(hparams.d_label_hidden, hparams.d_label_hidden, num_labels)
def forward(self, outputs, outpute):
# output from rnn [batch, length, hidden_size]
# apply dropout for output
# [batch, length, hidden_size] --> [batch, hidden_size, length] --> [batch, length, hidden_size]
outpute = self.dropout_out(outpute.transpose(1, 0)).transpose(1, 0)
outputs = self.dropout_out(outputs.transpose(1, 0)).transpose(1, 0)
# output size [batch, length, arc_space]
arc_h = nn.functional.relu(self.arc_h(outputs))
arc_c = nn.functional.relu(self.arc_c(outpute))
# output size [batch, length, type_space]
type_h = nn.functional.relu(self.type_h(outputs))
type_c = nn.functional.relu(self.type_c(outpute))
# apply dropout
# [batch, length, dim] --> [batch, 2 * length, dim]
arc = torch.cat([arc_h, arc_c], dim=0)
type = torch.cat([type_h, type_c], dim=0)
arc = self.dropout_out(arc.transpose(1, 0)).transpose(1, 0)
arc_h, arc_c = arc.chunk(2, 0)
type = self.dropout_out(type.transpose(1, 0)).transpose(1, 0)
type_h, type_c = type.chunk(2, 0)
type_h = type_h.contiguous()
type_c = type_c.contiguous()
out_arc = self.attention(arc_h, arc_c)
out_type = self.bilinear(type_h, type_c)
return out_arc, out_type
class LabelAttention(nn.Module):
"""
Single-head Attention layer for label-specific representations
"""
def __init__(self, hparams, d_model, d_k, d_v, d_l, d_proj, use_resdrop=True, q_as_matrix=False, residual_dropout=0.1, attention_dropout=0.1, d_positional=None):
super(LabelAttention, self).__init__()
self.hparams = hparams
self.d_k = d_k
self.d_v = d_v
self.d_l = d_l # Number of Labels
self.d_model = d_model # Model Dimensionality
self.d_proj = d_proj # Projection dimension of each label output
self.use_resdrop = use_resdrop # Using Residual Dropout?
self.q_as_matrix = q_as_matrix # Using a Matrix of Q to be multiplied with input instead of learned q vectors
self.combine_as_self = hparams.lal_combine_as_self # Using the Combination Method of Self-Attention
if d_positional is None:
self.partitioned = False
else:
self.partitioned = True
if self.partitioned:
self.d_content = d_model - d_positional
self.d_positional = d_positional
if self.q_as_matrix:
self.w_qs1 = nn.Parameter(torch_t.FloatTensor(self.d_l, self.d_content, d_k // 2), requires_grad=True)
else:
self.w_qs1 = nn.Parameter(torch_t.FloatTensor(self.d_l, d_k // 2), requires_grad=True)
self.w_ks1 = nn.Parameter(torch_t.FloatTensor(self.d_l, self.d_content, d_k // 2), requires_grad=True)
self.w_vs1 = nn.Parameter(torch_t.FloatTensor(self.d_l, self.d_content, d_v // 2), requires_grad=True)
if self.q_as_matrix:
self.w_qs2 = nn.Parameter(torch_t.FloatTensor(self.d_l, self.d_positional, d_k // 2), requires_grad=True)
else:
self.w_qs2 = nn.Parameter(torch_t.FloatTensor(self.d_l, d_k // 2), requires_grad=True)
self.w_ks2 = nn.Parameter(torch_t.FloatTensor(self.d_l, self.d_positional, d_k // 2), requires_grad=True)
self.w_vs2 = nn.Parameter(torch_t.FloatTensor(self.d_l, self.d_positional, d_v // 2), requires_grad=True)
init.xavier_normal_(self.w_qs1)
init.xavier_normal_(self.w_ks1)
init.xavier_normal_(self.w_vs1)
init.xavier_normal_(self.w_qs2)
init.xavier_normal_(self.w_ks2)
init.xavier_normal_(self.w_vs2)
else:
if self.q_as_matrix:
self.w_qs = nn.Parameter(torch_t.FloatTensor(self.d_l, d_model, d_k), requires_grad=True)
else:
self.w_qs = nn.Parameter(torch_t.FloatTensor(self.d_l, d_k), requires_grad=True)
self.w_ks = nn.Parameter(torch_t.FloatTensor(self.d_l, d_model, d_k), requires_grad=True)
self.w_vs = nn.Parameter(torch_t.FloatTensor(self.d_l, d_model, d_v), requires_grad=True)
init.xavier_normal_(self.w_qs)
init.xavier_normal_(self.w_ks)
init.xavier_normal_(self.w_vs)
self.attention = ScaledDotProductAttention(d_model, attention_dropout=attention_dropout)
if self.combine_as_self:
self.layer_norm = LayerNormalization(d_model)
else:
self.layer_norm = LayerNormalization(self.d_proj)
if not self.partitioned:
# The lack of a bias term here is consistent with the t2t code, though
# in my experiments I have never observed this making a difference.
if self.combine_as_self:
self.proj = nn.Linear(self.d_l * d_v, d_model, bias=False)
else:
self.proj = nn.Linear(d_v, d_model, bias=False) # input dimension does not match, should be d_l * d_v
else:
if self.combine_as_self:
self.proj1 = nn.Linear(self.d_l*(d_v//2), self.d_content, bias=False)
self.proj2 = nn.Linear(self.d_l*(d_v//2), self.d_positional, bias=False)
else:
self.proj1 = nn.Linear(d_v//2, self.d_content, bias=False)
self.proj2 = nn.Linear(d_v//2, self.d_positional, bias=False)
if not self.combine_as_self:
self.reduce_proj = nn.Linear(d_model, self.d_proj, bias=False)
self.residual_dropout = FeatureDropout(residual_dropout)
def split_qkv_packed(self, inp, k_inp=None):
len_inp = inp.size(0)
v_inp_repeated = inp.repeat(self.d_l, 1).view(self.d_l, -1, inp.size(-1)) # d_l x len_inp x d_model
if k_inp is None:
k_inp_repeated = v_inp_repeated
else:
k_inp_repeated = k_inp.repeat(self.d_l, 1).view(self.d_l, -1, k_inp.size(-1)) # d_l x len_inp x d_model
if not self.partitioned:
if self.q_as_matrix:
q_s = torch.bmm(k_inp_repeated, self.w_qs) # d_l x len_inp x d_k
else:
q_s = self.w_qs.unsqueeze(1) # d_l x 1 x d_k
k_s = torch.bmm(k_inp_repeated, self.w_ks) # d_l x len_inp x d_k
v_s = torch.bmm(v_inp_repeated, self.w_vs) # d_l x len_inp x d_v
else:
if self.q_as_matrix:
q_s = torch.cat([
torch.bmm(k_inp_repeated[:,:,:self.d_content], self.w_qs1),
torch.bmm(k_inp_repeated[:,:,self.d_content:], self.w_qs2),
], -1)
else:
q_s = torch.cat([
self.w_qs1.unsqueeze(1),
self.w_qs2.unsqueeze(1),
], -1)
k_s = torch.cat([
torch.bmm(k_inp_repeated[:,:,:self.d_content], self.w_ks1),
torch.bmm(k_inp_repeated[:,:,self.d_content:], self.w_ks2),
], -1)
v_s = torch.cat([
torch.bmm(v_inp_repeated[:,:,:self.d_content], self.w_vs1),
torch.bmm(v_inp_repeated[:,:,self.d_content:], self.w_vs2),
], -1)
return q_s, k_s, v_s
def pad_and_rearrange(self, q_s, k_s, v_s, batch_idxs):
# Input is padded representation: n_head x len_inp x d
# Output is packed representation: (n_head * mb_size) x len_padded x d
# (along with masks for the attention and output)
n_head = self.d_l
d_k, d_v = self.d_k, self.d_v
len_padded = batch_idxs.max_len
mb_size = batch_idxs.batch_size
if self.q_as_matrix:
q_padded = q_s.new_zeros((n_head, mb_size, len_padded, d_k))
else:
q_padded = q_s.repeat(mb_size, 1, 1) # (d_l * mb_size) x 1 x d_k