-
Notifications
You must be signed in to change notification settings - Fork 11
/
layers.py
1597 lines (1351 loc) · 64.5 KB
/
layers.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 math
import numpy as np
import h5py
import copy
import torch.nn.functional as F
def compute_mask(x):
mask = torch.ne(x, 0).float()
if x.is_cuda:
mask = mask.cuda()
return mask
def to_one_hot(y_true, n_classes):
# y_true: batch x time
batch_size, length = y_true.size(0), y_true.size(1)
y_onehot = torch.FloatTensor(batch_size, length, n_classes) # batch x time x n_class
if y_true.is_cuda:
y_onehot = y_onehot.cuda()
y_onehot.zero_()
y_onehot = y_onehot.view(-1, y_onehot.size(-1)) # batch*time x n_class
y_true = y_true.view(-1, 1) # batch*time x 1
y_onehot.scatter_(1, y_true, 1) # batch*time x n_class
return y_onehot.view(batch_size, length, -1)
def NegativeLogLoss(y_pred, y_true, mask=None, smoothing_eps=0.0):
"""
Shape:
- y_pred: batch x time x vocab
- y_true: batch x time
- mask: batch x time
"""
y_true_onehot = to_one_hot(y_true, y_pred.size(-1)) # batch x time x vocab
if smoothing_eps > 0.0:
y_true_onehot = y_true_onehot * (1.0 - smoothing_eps) + (1.0 - y_true_onehot) * smoothing_eps / (y_pred.size(-1) - 1)
P = y_true_onehot * y_pred # batch x time x vocab
P = torch.sum(P, dim=-1) # batch x time
gt_zero = torch.gt(P, 0.0).float() # batch x time
epsilon = torch.le(P, 0.0).float() * 1e-8 # batch x time
log_P = torch.log(P + epsilon) * gt_zero # batch x time
if mask is not None:
log_P = log_P * mask
output = -torch.sum(log_P, dim=1) # batch
return output
def NLL(y_pred, y_true_onehot, mask=None):
"""
Shape:
- y_pred: batch x n_class
- y_true: batch x n_class
- mask: batch x n_class
"""
y_true_onehot = y_true_onehot.float()
P = y_true_onehot * y_pred # batch x n_class
gt_zero = torch.gt(P, 0.0).float() # batch x n_class
epsilon = torch.le(P, 0.0).float() * 1e-8 # batch x n_class
log_P = torch.log(P + epsilon) * gt_zero # batch x n_class
if mask is not None:
log_P = log_P * mask
output = -torch.sum(log_P, dim=1) # batch
return torch.mean(output)
def masked_softmax(x, m=None, axis=-1):
'''
Softmax with mask (optional)
'''
x = torch.clamp(x, min=-15.0, max=15.0)
if m is not None:
m = m.float()
x = x * m
e_x = torch.exp(x - torch.max(x, dim=axis, keepdim=True)[0])
if m is not None:
e_x = e_x * m
softmax = e_x / (torch.sum(e_x, dim=axis, keepdim=True) + 1e-6)
return softmax
def masked_mean(x, m=None, dim=1):
"""
mean pooling when there're paddings
input: tensor: batch x time x h
mask: batch x time
output: tensor: batch x h
"""
if m is None:
return torch.mean(x, dim=dim)
x = x * m.unsqueeze(-1)
mask_sum = torch.sum(m, dim=-1) # batch
tmp = torch.eq(mask_sum, 0).float()
if x.is_cuda:
tmp = tmp.cuda()
mask_sum = mask_sum + tmp
res = torch.sum(x, dim=dim) # batch x h
res = res / mask_sum.unsqueeze(-1)
return res
def masked_ave_aggregator(x, mask):
"""
ave aggregator of the node embedding
input: tensor: batch x num_nodes x dim
mask: tensor: batch x num_nodes
"""
mask_sum = torch.sum(mask, -1).unsqueeze(-1) # batch x 1
mask = mask.unsqueeze(-1) # batch x num_nodes x 1
mask = mask.expand(-1, -1, x.shape[-1]) # batch x num_nodes x dim
masked_x = x * mask # batch x num_nodes x dim
sum_masked_x = torch.sum(masked_x, 1)
ave_masked_x = sum_masked_x / mask_sum
return ave_masked_x
class LayerNorm(torch.nn.Module):
def __init__(self, input_dim):
super(LayerNorm, self).__init__()
self.gamma = torch.nn.Parameter(torch.ones(input_dim))
self.beta = torch.nn.Parameter(torch.zeros(input_dim))
self.eps = 1e-6
def forward(self, x, mask=None):
# x: nbatch x hidden
# mask: nbatch
mean = x.mean(-1, keepdim=True)
std = torch.sqrt(x.var(dim=-1, keepdim=True) + self.eps)
output = self.gamma * (x - mean) / (std + self.eps) + self.beta
if mask is not None:
return output * mask.unsqueeze(-1)
else:
return output
class H5EmbeddingManager(object):
def __init__(self, h5_path):
f = h5py.File(h5_path, 'r')
self.W = np.array(f['embedding'])
print("embedding data type=%s, shape=%s" % (type(self.W), self.W.shape))
id2word = f['words_flatten'][0].split(b'\n')
self.id2word = [item.decode("utf-8") for item in id2word]
self.word2id = dict(zip(self.id2word, range(len(self.id2word))))
def __getitem__(self, item):
item_type = type(item)
if item_type is str:
index = self.word2id[item]
embs = self.W[index]
return embs
else:
raise RuntimeError("don't support type: %s" % type(item))
def word_embedding_initialize(self, words_list, dim_size=300, scale=0.1, oov_init='random'):
shape = (len(words_list), dim_size)
self.rng = np.random.RandomState(42)
if 'zero' == oov_init:
W2V = np.zeros(shape, dtype='float32')
elif 'one' == oov_init:
W2V = np.ones(shape, dtype='float32')
else:
W2V = self.rng.uniform(low=-scale, high=scale, size=shape).astype('float32')
W2V[0, :] = 0
in_vocab = np.ones(shape[0], dtype=np.bool)
word_ids = []
for i, word in enumerate(words_list):
if word in self.word2id:
word_ids.append(self.word2id[word])
else:
in_vocab[i] = False
W2V[in_vocab] = self.W[np.array(word_ids, dtype='int32')][:, :dim_size]
return W2V
class Embedding(torch.nn.Module):
'''
inputs: x: batch x ...
outputs:embedding: batch x ... x emb
mask: batch x ...
'''
def __init__(self, embedding_size, vocab_size, dropout_rate=0.0, trainable=True, id2word=None,
embedding_oov_init='random', load_pretrained=False, pretrained_embedding_path=None):
super(Embedding, self).__init__()
self.embedding_size = embedding_size
self.vocab_size = vocab_size
self.id2word = id2word
self.dropout_rate = dropout_rate
self.load_pretrained = load_pretrained
self.embedding_oov_init = embedding_oov_init
self.pretrained_embedding_path = pretrained_embedding_path
self.trainable = trainable
self.embedding_layer = torch.nn.Embedding(self.vocab_size, self.embedding_size, padding_idx=0)
self.init_weights()
def init_weights(self):
init_embedding_matrix = self.embedding_init()
if self.embedding_layer.weight.is_cuda:
init_embedding_matrix = init_embedding_matrix.cuda()
self.embedding_layer.weight = torch.nn.Parameter(init_embedding_matrix)
if not self.trainable:
self.embedding_layer.weight.requires_grad = False
def embedding_init(self):
# Embeddings
if self.load_pretrained is False:
word_embedding_init = np.random.uniform(low=-0.05, high=0.05, size=(self.vocab_size, self.embedding_size))
word_embedding_init[0, :] = 0
else:
embedding_initr = H5EmbeddingManager(self.pretrained_embedding_path)
word_embedding_init = embedding_initr.word_embedding_initialize(self.id2word,
dim_size=self.embedding_size,
oov_init=self.embedding_oov_init)
del embedding_initr
word_embedding_init = torch.from_numpy(word_embedding_init).float()
return word_embedding_init
def compute_mask(self, x):
mask = torch.ne(x, 0).float()
if x.is_cuda:
mask = mask.cuda()
return mask
def forward(self, x):
embeddings = self.embedding_layer(x) # batch x time x emb
embeddings = F.dropout(embeddings, p=self.dropout_rate, training=self.training)
mask = self.compute_mask(x) # batch x time
return embeddings, mask
class FastUniLSTM(torch.nn.Module):
"""
Adapted from https://github.com/facebookresearch/DrQA/
now supports: different rnn size for each layer
all zero rows in batch (from time distributed layer, by reshaping certain dimension)
"""
def __init__(self, ninp, nhids, dropout_between_rnn_layers=0.):
super(FastUniLSTM, self).__init__()
self.ninp = ninp
self.nhids = nhids
self.nlayers = len(self.nhids)
self.dropout_between_rnn_layers = dropout_between_rnn_layers
self.stack_rnns()
def stack_rnns(self):
rnns = [torch.nn.LSTM(self.ninp if i == 0 else self.nhids[i - 1],
self.nhids[i],
num_layers=1,
bidirectional=False) for i in range(self.nlayers)]
self.rnns = torch.nn.ModuleList(rnns)
def forward(self, x, mask):
def pad_(tensor, n):
if n > 0:
zero_pad = torch.autograd.Variable(torch.zeros((n,) + tensor.size()[1:]))
if x.is_cuda:
zero_pad = zero_pad.cuda()
tensor = torch.cat([tensor, zero_pad])
return tensor
"""
inputs: x: batch x time x inp
mask: batch x time
output: encoding: batch x time x hidden[-1]
"""
# Compute sorted sequence lengths
batch_size = x.size(0)
lengths = mask.data.eq(1).long().sum(1) # .squeeze()
_, idx_sort = torch.sort(lengths, dim=0, descending=True)
_, idx_unsort = torch.sort(idx_sort, dim=0)
lengths = list(lengths[idx_sort])
idx_sort = torch.autograd.Variable(idx_sort)
idx_unsort = torch.autograd.Variable(idx_unsort)
# Sort x
x = x.index_select(0, idx_sort)
# remove non-zero rows, and remember how many zeros
n_nonzero = np.count_nonzero(lengths)
n_zero = batch_size - n_nonzero
if n_zero != 0:
lengths = lengths[:n_nonzero]
x = x[:n_nonzero]
# Transpose batch and sequence dims
x = x.transpose(0, 1)
# Pack it up
rnn_input = torch.nn.utils.rnn.pack_padded_sequence(x, lengths)
# Encode all layers
outputs = [rnn_input]
for i in range(self.nlayers):
rnn_input = outputs[-1]
# dropout between rnn layers
if self.dropout_between_rnn_layers > 0:
dropout_input = F.dropout(rnn_input.data,
p=self.dropout_between_rnn_layers,
training=self.training)
rnn_input = torch.nn.utils.rnn.PackedSequence(dropout_input,
rnn_input.batch_sizes)
seq, last = self.rnns[i](rnn_input)
outputs.append(seq)
if i == self.nlayers - 1:
# last layer
last_state = last[0] # (num_layers * num_directions, batch, hidden_size)
last_state = last_state[0] # batch x hidden_size
# Unpack everything
for i, o in enumerate(outputs[1:], 1):
outputs[i] = torch.nn.utils.rnn.pad_packed_sequence(o)[0]
output = outputs[-1]
# Transpose and unsort
output = output.transpose(0, 1) # batch x time x enc
# re-padding
output = pad_(output, n_zero)
last_state = pad_(last_state, n_zero)
output = output.index_select(0, idx_unsort)
last_state = last_state.index_select(0, idx_unsort)
# Pad up to original batch sequence length
if output.size(1) != mask.size(1):
padding = torch.zeros(output.size(0),
mask.size(1) - output.size(1),
output.size(2)).type(output.data.type())
output = torch.cat([output, torch.autograd.Variable(padding)], 1)
output = output.contiguous() * mask.unsqueeze(-1)
return output, last_state, mask
class FastBiLSTM(torch.nn.Module):
"""
Adapted from https://github.com/facebookresearch/DrQA/
now supports: different rnn size for each layer
all zero rows in batch (from time distributed layer, by reshaping certain dimension)
"""
def __init__(self, ninp, nhids, dropout_between_rnn_layers=0.):
super(FastBiLSTM, self).__init__()
self.ninp = ninp
self.nhids = [h // 2 for h in nhids]
self.nlayers = len(self.nhids)
self.dropout_between_rnn_layers = dropout_between_rnn_layers
self.stack_rnns()
def stack_rnns(self):
rnns = [torch.nn.LSTM(self.ninp if i == 0 else self.nhids[i - 1] * 2,
self.nhids[i],
num_layers=1,
bidirectional=True) for i in range(self.nlayers)]
self.rnns = torch.nn.ModuleList(rnns)
def forward(self, x, mask):
def pad_(tensor, n):
if n > 0:
zero_pad = torch.autograd.Variable(torch.zeros((n,) + tensor.size()[1:]))
if x.is_cuda:
zero_pad = zero_pad.cuda()
tensor = torch.cat([tensor, zero_pad])
return tensor
"""
inputs: x: batch x time x inp
mask: batch x time
output: encoding: batch x time x hidden[-1]
"""
# Compute sorted sequence lengths
batch_size = x.size(0)
lengths = mask.data.eq(1).long().sum(1) # .squeeze()
_, idx_sort = torch.sort(lengths, dim=0, descending=True)
_, idx_unsort = torch.sort(idx_sort, dim=0)
lengths = list(lengths[idx_sort])
idx_sort = torch.autograd.Variable(idx_sort)
idx_unsort = torch.autograd.Variable(idx_unsort)
# Sort x
x = x.index_select(0, idx_sort)
# remove non-zero rows, and remember how many zeros
n_nonzero = np.count_nonzero(lengths)
n_zero = batch_size - n_nonzero
if n_zero != 0:
lengths = lengths[:n_nonzero]
x = x[:n_nonzero]
# Transpose batch and sequence dims
x = x.transpose(0, 1)
# Pack it up
rnn_input = torch.nn.utils.rnn.pack_padded_sequence(x, lengths)
# Encode all layers
outputs = [rnn_input]
for i in range(self.nlayers):
rnn_input = outputs[-1]
# dropout between rnn layers
if self.dropout_between_rnn_layers > 0:
dropout_input = F.dropout(rnn_input.data,
p=self.dropout_between_rnn_layers,
training=self.training)
rnn_input = torch.nn.utils.rnn.PackedSequence(dropout_input,
rnn_input.batch_sizes)
seq, last = self.rnns[i](rnn_input)
outputs.append(seq)
if i == self.nlayers - 1:
# last layer
last_state = last[0] # (num_layers * num_directions, batch, hidden_size)
last_state = torch.cat([last_state[0], last_state[1]], 1) # batch x hid_f+hid_b
# Unpack everything
for i, o in enumerate(outputs[1:], 1):
outputs[i] = torch.nn.utils.rnn.pad_packed_sequence(o)[0]
output = outputs[-1]
# Transpose and unsort
output = output.transpose(0, 1) # batch x time x enc
# re-padding
output = pad_(output, n_zero)
last_state = pad_(last_state, n_zero)
output = output.index_select(0, idx_unsort)
last_state = last_state.index_select(0, idx_unsort)
# Pad up to original batch sequence length
if output.size(1) != mask.size(1):
padding = torch.zeros(output.size(0),
mask.size(1) - output.size(1),
output.size(2)).type(output.data.type())
output = torch.cat([output, torch.autograd.Variable(padding)], 1)
output = output.contiguous() * mask.unsqueeze(-1)
return output, last_state, mask
class LSTMCell(torch.nn.Module):
"""A basic LSTM cell."""
def __init__(self, input_size, hidden_size, use_bias=True):
"""
Most parts are copied from torch.nn.LSTMCell.
"""
super(LSTMCell, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.use_bias = use_bias
self.pre_act_linear = torch.nn.Linear(input_size + hidden_size, 4 * hidden_size, bias=False)
if use_bias:
self.bias_f = torch.nn.Parameter(torch.FloatTensor(hidden_size))
self.bias_iog = torch.nn.Parameter(torch.FloatTensor(3 * hidden_size))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
torch.nn.init.xavier_uniform_(self.pre_act_linear.weight.data)
if self.use_bias:
self.bias_f.data.fill_(1.0)
self.bias_iog.data.fill_(0.0)
def get_init_hidden(self, bsz, use_cuda):
h_0 = torch.autograd.Variable(torch.FloatTensor(bsz, self.hidden_size).zero_())
c_0 = torch.autograd.Variable(torch.FloatTensor(bsz, self.hidden_size).zero_())
if use_cuda:
h_0, c_0 = h_0.cuda(), c_0.cuda()
return h_0, c_0
def forward(self, input_, mask_=None, h_0=None, c_0=None):
"""
Args:
input_: A (batch, input_size) tensor containing input features.
mask_: (batch)
hx: A tuple (h_0, c_0), which contains the initial hidden
and cell state, where the size of both states is
(batch, hidden_size).
Returns:
h_1, c_1: Tensors containing the next hidden and cell state.
"""
if h_0 is None or c_0 is None:
h_init, c_init = self.get_init_hidden(input_.size(0), use_cuda=input_.is_cuda)
if h_0 is None:
h_0 = h_init
if c_0 is None:
c_0 = c_init
if mask_ is None:
mask_ = torch.ones_like(torch.sum(input_, -1))
if input_.is_cuda:
mask_ = mask_.cuda()
pre_act = self.pre_act_linear(torch.cat([input_, h_0], -1)) # batch x 4*hid
if self.use_bias:
pre_act = pre_act + torch.cat([self.bias_f, self.bias_iog]).unsqueeze(0)
f, i, o, g = torch.split(pre_act, split_size_or_sections=self.hidden_size, dim=1)
expand_mask_ = mask_.unsqueeze(1) # batch x 1
c_1 = torch.sigmoid(f) * c_0 + torch.sigmoid(i) * torch.tanh(g)
c_1 = c_1 * expand_mask_ + c_0 * (1 - expand_mask_)
h_1 = torch.sigmoid(o) * torch.tanh(c_1)
h_1 = h_1 * expand_mask_ + h_0 * (1 - expand_mask_)
return h_1, c_1
def __repr__(self):
s = '{name}({input_size}, {hidden_size})'
return s.format(name=self.__class__.__name__, **self.__dict__)
class MatchLSTMAttention(torch.nn.Module):
'''
input: p: batch x inp_p
p_mask: batch
q: batch x time x inp_q
q_mask: batch x time
h_tm1: batch x out
depth: int
output: z: batch x inp_p+inp_q
'''
def __init__(self, input_p_dim, input_q_dim, output_dim):
super(MatchLSTMAttention, self).__init__()
self.input_p_dim = input_p_dim
self.input_q_dim = input_q_dim
self.output_dim = output_dim
self.nlayers = len(self.output_dim)
W_p_r = [torch.nn.Linear(self.output_dim[i] + (self.input_p_dim if i == 0 else self.output_dim[i - 1]), self.output_dim[i]) for i in range(self.nlayers)]
W_q = [torch.nn.Linear(self.input_q_dim, self.output_dim[i]) for i in range(self.nlayers)]
w = [torch.nn.Parameter(torch.FloatTensor(self.output_dim[i])) for i in range(self.nlayers)]
match_b = [torch.nn.Parameter(torch.FloatTensor(1)) for i in range(self.nlayers)]
self.W_p_r = torch.nn.ModuleList(W_p_r)
self.W_q = torch.nn.ModuleList(W_q)
self.w = torch.nn.ParameterList(w)
self.match_b = torch.nn.ParameterList(match_b)
self.init_weights()
def init_weights(self):
for i in range(self.nlayers):
torch.nn.init.xavier_uniform_(self.W_p_r[i].weight.data)
torch.nn.init.xavier_uniform_(self.W_q[i].weight.data)
self.W_p_r[i].bias.data.fill_(0)
self.W_q[i].bias.data.fill_(0)
torch.nn.init.normal_(self.w[i].data, mean=0, std=0.05)
self.match_b[i].data.fill_(1.0)
def forward(self, input_p, mask_p, input_q, mask_q, h_tm1, depth):
G_p_r = self.W_p_r[depth](torch.cat([input_p, h_tm1], -1)).unsqueeze(1) # batch x None x out
G_q = self.W_q[depth](input_q) # batch x time x out
G = torch.tanh(G_p_r + G_q) # batch x time x out
alpha = torch.matmul(G, self.w[depth]) # batch x time
alpha = alpha + self.match_b[depth].unsqueeze(0) # batch x time
alpha = masked_softmax(alpha, mask_q, axis=-1) # batch x time
alpha = alpha.unsqueeze(1) # batch x 1 x time
# batch x time x input_q, batch x 1 x time
z = torch.bmm(alpha, input_q) # batch x 1 x input_q
z = z.squeeze(1) # batch x input_q
z = torch.cat([input_p, z], 1) # batch x input_p+input_q
return z
class StackedMatchLSTM(torch.nn.Module):
'''
inputs: p: batch x time x inp_p
mask_p: batch x time
q: batch x time x inp_q
mask_q: batch x time
outputs:
encoding: batch x time x h
Dropout types:
dropout_between_rnn_layers -- if multi layer rnns
dropout_in_rnn_weights -- rnn weight dropout
'''
def __init__(self, input_p_dim, input_q_dim, nhids, attention_layer,
dropout_between_rnn_layers=0.):
super(StackedMatchLSTM, self).__init__()
self.nhids = nhids
self.input_p_dim = input_p_dim
self.input_q_dim = input_q_dim
self.attention_layer = attention_layer
self.dropout_between_rnn_layers = dropout_between_rnn_layers
self.nlayers = len(self.nhids)
self.stack_rnns()
def stack_rnns(self):
rnns = [LSTMCell((self.input_p_dim + self.input_q_dim) if i == 0 else (self.nhids[i - 1] + self.input_q_dim), self.nhids[i], use_bias=True)
for i in range(self.nlayers)]
self.rnns = torch.nn.ModuleList(rnns)
def get_init_hidden(self, bsz, use_cuda):
weight = next(self.parameters()).data
if use_cuda:
return [[(torch.autograd.Variable(weight.new(bsz, self.nhids[i]).zero_()).cuda(),
torch.autograd.Variable(weight.new(bsz, self.nhids[i]).zero_()).cuda())]
for i in range(self.nlayers)]
else:
return [[(torch.autograd.Variable(weight.new(bsz, self.nhids[i]).zero_()),
torch.autograd.Variable(weight.new(bsz, self.nhids[i]).zero_()))]
for i in range(self.nlayers)]
def forward(self, input_p, mask_p, input_q, mask_q):
batch_size = input_p.size(0)
state_stp = self.get_init_hidden(batch_size, use_cuda=input_p.is_cuda)
for d, rnn in enumerate(self.rnns):
for t in range(input_p.size(1)):
input_mask = mask_p[:, t]
if d == 0:
# 0th layer
curr_input = input_p[:, t]
else:
curr_input = state_stp[d - 1][t][0]
# apply dropout layer-to-layer
drop_input = F.dropout(curr_input, p=self.dropout_between_rnn_layers, training=self.training) if d > 0 else curr_input
previous_h, previous_c = state_stp[d][t]
drop_input = self.attention_layer(drop_input, input_mask, input_q, mask_q, h_tm1=previous_h, depth=d)
new_h, new_c = rnn(drop_input, input_mask, previous_h, previous_c)
state_stp[d].append((new_h, new_c))
states = [h[0] for h in state_stp[-1][1:]] # list of batch x hid
states = torch.stack(states, 1) # batch x time x hid
return states
class BiMatchLSTM(torch.nn.Module):
'''
inputs: p: batch x time_p x emb
mask_p: batch x time_p
q: batch x time_q x emb
mask_q: batch x time_q
outputs:encoding: batch x time_p x hid
last state: batch x hid
Dropout types:
dropouth -- dropout on hidden-to-hidden connections
'''
def __init__(self, input_p_dim, input_q_dim, nhids, dropout_between_rnn_layers=0.):
super(BiMatchLSTM, self).__init__()
self.nhids = nhids
self.input_p_dim = input_p_dim
self.input_q_dim = input_q_dim
self.attention_layer = MatchLSTMAttention(input_p_dim, input_q_dim,
output_dim=[hid // 2 for hid in self.nhids])
self.forward_rnn = StackedMatchLSTM(input_p_dim=self.input_p_dim,
input_q_dim=self.input_q_dim,
nhids=[hid // 2 for hid in self.nhids],
attention_layer=self.attention_layer,
dropout_between_rnn_layers=dropout_between_rnn_layers)
self.backward_rnn = StackedMatchLSTM(input_p_dim=self.input_p_dim,
input_q_dim=self.input_q_dim,
nhids=[hid // 2 for hid in self.nhids],
attention_layer=self.attention_layer,
dropout_between_rnn_layers=dropout_between_rnn_layers)
def forward(self, input_p, mask_p, input_q, mask_q):
# forward pass
forward_states = self.forward_rnn(input_p, mask_p, input_q, mask_q)
forward_last_state = forward_states[:, -1] # batch x hid/2
# backward pass
input_p_inverted = torch.flip(input_p, dims=[1]) # batch x time x p_dim (backward)
mask_p_inverted = torch.flip(mask_p, dims=[1]) # batch x time (backward)
backward_states = self.backward_rnn(input_p_inverted, mask_p_inverted, input_q, mask_q)
backward_last_state = backward_states[:, -1] # batch x hid/2
backward_states = torch.flip(backward_states, dims=[1]) # batch x time x hid/2
concat_states = torch.cat([forward_states, backward_states], -1) # batch x time x hid
concat_states = concat_states * mask_p.unsqueeze(-1) # batch x time x hid
concat_last_state = torch.cat([forward_last_state, backward_last_state], -1) # batch x hid
return concat_states, concat_last_state
class ActionScorerAttention(torch.nn.Module):
def __init__(self, input_q_dim, output_dim, noisy_net=False):
super(ActionScorerAttention, self).__init__()
self.input_q_dim = input_q_dim
self.output_dim = output_dim
self.noisy_net = noisy_net
if self.noisy_net:
self.W_a = NoisyLinear(self.input_q_dim, self.output_dim)
else:
self.W_a = torch.nn.Linear(self.input_q_dim, self.output_dim)
self.init_weights()
def init_weights(self):
if not self.noisy_net:
torch.nn.init.xavier_uniform_(self.W_a.weight.data, gain=1)
self.W_a.bias.data.fill_(0)
def forward(self, H_q):
# H_q: batch x inp_q
Fk_prime = self.W_a(H_q) # batch x out
Fk_prime = torch.sigmoid(Fk_prime) # batch x out
return Fk_prime
def reset_noise(self):
if self.noisy_net:
self.W_a.reset_noise()
class ActionScorerAttentionAdvantage(torch.nn.Module):
def __init__(self, input_seq_dim, input_q_dim, output_dim, noisy_net=False):
super(ActionScorerAttentionAdvantage, self).__init__()
self.input_seq_dim = input_seq_dim
self.input_q_dim = input_q_dim
self.output_dim = output_dim
self.noisy_net = noisy_net
if self.noisy_net:
self.V = NoisyLinear(self.input_seq_dim, self.output_dim)
self.W_a = NoisyLinear(self.input_q_dim, self.output_dim)
else:
self.V = torch.nn.Linear(self.input_seq_dim, self.output_dim)
self.W_a = torch.nn.Linear(self.input_q_dim, self.output_dim)
self.v = torch.nn.Parameter(torch.FloatTensor(self.output_dim))
self.init_weights()
def init_weights(self):
if not self.noisy_net:
torch.nn.init.xavier_uniform_(self.V.weight.data, gain=1)
torch.nn.init.xavier_uniform_(self.W_a.weight.data, gain=1)
self.V.bias.data.fill_(0)
self.W_a.bias.data.fill_(0)
torch.nn.init.normal_(self.v.data, mean=0, std=0.05)
def forward(self, H_r, mask_r, H_q):
# H_r: batch x time x input_seq_dim
# mask_r: batch x time
# H_q: batch x inp_q
batch_size, time = H_r.size(0), H_r.size(1)
Fk = self.V(H_r.view(-1, H_r.size(2))) # batch*time x out
Fk_prime = self.W_a(H_q) # batch x out
Fk = Fk.view(batch_size, time, -1) # batch x time x out
Fk = torch.sigmoid(Fk + Fk_prime.unsqueeze(1)) # batch x time x out
Fk = Fk * mask_r.unsqueeze(-1) # batch x time x out
return Fk
def reset_noise(self):
if self.noisy_net:
self.V.reset_noise()
self.W_a.reset_noise()
class BoundaryDecoderAttention(torch.nn.Module):
def __init__(self, input_dim, output_dim, noisy_net=False):
super(BoundaryDecoderAttention, self).__init__()
self.input_dim = input_dim
self.output_dim = output_dim
self.noisy_net = noisy_net
if self.noisy_net:
self.V = NoisyLinear(self.input_dim, self.output_dim)
self.W_a = NoisyLinear(self.output_dim, self.output_dim)
else:
self.V = torch.nn.Linear(self.input_dim, self.output_dim)
self.W_a = torch.nn.Linear(self.output_dim, self.output_dim)
self.v = torch.nn.Parameter(torch.FloatTensor(self.output_dim))
self.c = torch.nn.Parameter(torch.FloatTensor(1))
self.init_weights()
def init_weights(self):
if not self.noisy_net:
torch.nn.init.xavier_uniform_(self.V.weight.data)
torch.nn.init.xavier_uniform_(self.W_a.weight.data)
self.V.bias.data.fill_(0)
self.W_a.bias.data.fill_(0)
torch.nn.init.normal_(self.v.data, mean=0, std=0.05)
self.c.data.fill_(1.0)
def forward(self, H_r, mask_r, h_tm1):
# H_r: batch x time x inp
# mask_r: batch x time
# h_tm1: batch x out
batch_size, time = H_r.size(0), H_r.size(1)
Fk = self.V(H_r.view(-1, H_r.size(2))) # batch*time x out
Fk_prime = self.W_a(h_tm1) # batch x out
Fk = Fk.view(batch_size, time, -1) # batch x time x out
Fk = torch.tanh(Fk + Fk_prime.unsqueeze(1)) # batch x time x out
beta = torch.matmul(Fk, self.v) # batch x time
beta = beta + self.c.unsqueeze(0) # batch x time
beta = masked_softmax(beta, mask_r, axis=-1) # batch x time
z = torch.bmm(beta.view(beta.size(0), 1, beta.size(1)), H_r) # batch x 1 x inp
z = z.view(z.size(0), -1) # batch x inp
return z, beta
def reset_noise(self):
if self.noisy_net:
self.V.reset_noise()
self.W_a.reset_noise()
def zero_noise(self):
if self.noisy_net:
self.V.zero_noise()
self.W_a.zero_noise()
class BoundaryDecoder(torch.nn.Module):
'''
input: encoded stories: batch x time x input_dim
story mask: batch x time
init states: batch x hid
encoded question: batch x input_dim_q
'''
def __init__(self, input_dim, hidden_dim, noisy_net=False):
super(BoundaryDecoder, self).__init__()
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.noisy_net = noisy_net
self.attention_layer = BoundaryDecoderAttention(input_dim=input_dim,
output_dim=hidden_dim,
noisy_net=self.noisy_net)
self.rnn = LSTMCell(self.input_dim, self.hidden_dim, use_bias=True)
def forward(self, x, x_mask, h_0):
state_stp = [(h_0, h_0)]
beta_list = []
mask = torch.autograd.Variable(torch.ones(x.size(0))) # fake mask
mask = mask.cuda() if x.is_cuda else mask
for t in range(2):
previous_h, previous_c = state_stp[t]
curr_input, beta = self.attention_layer(x, x_mask, h_tm1=previous_h)
new_h, new_c = self.rnn(curr_input, mask, previous_h, previous_c)
state_stp.append((new_h, new_c))
beta_list.append(beta)
# beta list: list of batch x time
res = torch.stack(beta_list, 2) # batch x time x 2
res = res * x_mask.unsqueeze(2) # batch x time x 2
return res
def reset_noise(self):
if self.noisy_net:
self.attention_layer.reset_noise()
def zero_noise(self):
if self.noisy_net:
self.attention_layer.zero_noise()
class NoisyLinear(torch.nn.Module):
# Factorised NoisyLinear layer with bias
def __init__(self, in_features, out_features, std_init=0.5):
super(NoisyLinear, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.std_init = std_init
self.weight_mu = torch.nn.Parameter(torch.empty(out_features, in_features))
self.weight_sigma = torch.nn.Parameter(torch.empty(out_features, in_features))
self.register_buffer('weight_epsilon', torch.empty(out_features, in_features))
self.bias_mu = torch.nn.Parameter(torch.empty(out_features))
self.bias_sigma = torch.nn.Parameter(torch.empty(out_features))
self.register_buffer('bias_epsilon', torch.empty(out_features))
self.reset_parameters()
self.reset_noise()
self._zero_noise = False
def reset_parameters(self):
mu_range = 1 / math.sqrt(self.in_features)
self.weight_mu.data.uniform_(-mu_range, mu_range)
self.weight_sigma.data.fill_(self.std_init / math.sqrt(self.in_features))
self.bias_mu.data.uniform_(-mu_range, mu_range)
self.bias_sigma.data.fill_(self.std_init / math.sqrt(self.out_features))
def _scale_noise(self, size):
x = torch.randn(size)
return x.sign().mul_(x.abs().sqrt_())
def reset_noise(self):
epsilon_in = self._scale_noise(self.in_features)
epsilon_out = self._scale_noise(self.out_features)
self.weight_epsilon.copy_(epsilon_out.ger(epsilon_in))
self.bias_epsilon.copy_(epsilon_out)
def zero_noise(self):
self._zero_noise = True
def forward(self, input):
if self.training:
if self._zero_noise is True:
return F.linear(input, self.weight_mu, self.bias_mu)
else:
return F.linear(input, self.weight_mu + self.weight_sigma * self.weight_epsilon, self.bias_mu + self.bias_sigma * self.bias_epsilon)
else:
return F.linear(input, self.weight_mu, self.bias_mu)
################################# qanet
def PosEncoder(x, min_timescale=1.0, max_timescale=1.0e4):
length = x.size(1)
channels = x.size(2)
signal = get_timing_signal(length, channels, min_timescale, max_timescale)
return x + (signal.cuda() if x.is_cuda else signal)
def get_timing_signal(length, channels, min_timescale=1.0, max_timescale=1.0e4):
position = torch.arange(length).type(torch.float32)
num_timescales = channels // 2
log_timescale_increment = (math.log(float(max_timescale) / float(min_timescale)) / (float(num_timescales)-1))
inv_timescales = min_timescale * torch.exp(
torch.arange(num_timescales).type(torch.float32) * -log_timescale_increment)
scaled_time = position.unsqueeze(1) * inv_timescales.unsqueeze(0)
signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], dim = 1)
m = torch.nn.ZeroPad2d((0, (channels % 2), 0, 0))
signal = m(signal)
signal = signal.view(1, length, channels)
return signal
class DepthwiseSeparableConv(torch.nn.Module):
def __init__(self, in_ch, out_ch, k, bias=True):
super().__init__()
self.depthwise_conv = torch.nn.Conv1d(in_channels=in_ch, out_channels=in_ch, kernel_size=k, groups=in_ch, padding=k // 2, bias=False)
self.pointwise_conv = torch.nn.Conv1d(in_channels=in_ch, out_channels=out_ch, kernel_size=1, padding=0, bias=bias)
def forward(self, x):
x = x.transpose(1,2)
res = torch.relu(self.pointwise_conv(self.depthwise_conv(x)))
res = res.transpose(1,2)
return res
class SimpleSelfAttention(torch.nn.Module):
def __init__(self, hidden_size):
super(SimpleSelfAttention, self).__init__()
self.hidden_size = hidden_size
self.att_weights = torch.nn.Parameter(torch.Tensor(hidden_size, 1), requires_grad=True)
torch.nn.init.xavier_uniform(self.att_weights.data)
def forward(self, input, mask):
batch_size = input.size(0)
# apply attention layer
weights = torch.bmm(input, self.att_weights.unsqueeze(0).repeat(batch_size, 1, 1)).squeeze(-1)
attentions = masked_softmax(weights, mask)
# apply attention weights
weighted = torch.mul(input, attentions.unsqueeze(-1).expand_as(input))
return weighted, attentions
class ScaledDotProductAttention(torch.nn.Module):
''' Scaled Dot-Product Attention '''
def __init__(self, temperature, attn_dropout=0.1):
super().__init__()
self.temperature = temperature
self.dropout = torch.nn.Dropout(attn_dropout)
def forward(self, q, k, v, mask):
attn = torch.bmm(q, k.transpose(1, 2))
attn = attn / self.temperature
attn = masked_softmax(attn, mask, 2)
attn = self.dropout(attn)
output = torch.bmm(attn, v)
return output, attn
class SelfAttention(torch.nn.Module):
''' From Multi-Head Attention module
https://github.com/jadore801120/attention-is-all-you-need-pytorch'''
def __init__(self, block_hidden_dim, n_head, dropout=0.1):
super().__init__()
self.n_head = n_head
self.block_hidden_dim = block_hidden_dim
self.w_qs = torch.nn.Linear(block_hidden_dim, n_head * block_hidden_dim, bias=False)
self.w_ks = torch.nn.Linear(block_hidden_dim, n_head * block_hidden_dim, bias=False)
self.w_vs = torch.nn.Linear(block_hidden_dim, n_head * block_hidden_dim, bias=False)
torch.nn.init.normal_(self.w_qs.weight, mean=0, std=np.sqrt(2.0 / (block_hidden_dim * 2)))
torch.nn.init.normal_(self.w_ks.weight, mean=0, std=np.sqrt(2.0 / (block_hidden_dim * 2)))
torch.nn.init.normal_(self.w_vs.weight, mean=0, std=np.sqrt(2.0 / (block_hidden_dim * 2)))
self.attention = ScaledDotProductAttention(temperature=np.power(block_hidden_dim, 0.5))
self.fc = torch.nn.Linear(n_head * block_hidden_dim, block_hidden_dim)
self.layer_norm = torch.nn.LayerNorm(self.block_hidden_dim)