-
Notifications
You must be signed in to change notification settings - Fork 9
/
modules.py
2267 lines (1674 loc) · 88.4 KB
/
modules.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
from torch.autograd import Variable
import torch.optim as optim
import torch.nn.init as weight_init
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
import os
import numpy as np
import random
import sys
from torch.autograd import Variable
import math
parentPath = os.path.abspath("..")
sys.path.insert(0, parentPath)# add parent folder to path so as to import common modules
from helper import SOS_ID, EOS_ID
class MLP(nn.Module):
def __init__(self, input_size, arch, output_size, activation=nn.ReLU(), batch_norm=True, init_w=0.02, discriminator=False):
super(MLP, self).__init__()
self.input_size = input_size
self.output_size = output_size
self.init_w= init_w
layer_sizes = [input_size] + [int(x) for x in arch.split('-')]
self.layers = []
for i in range(len(layer_sizes)-1):
layer = nn.Linear(layer_sizes[i], layer_sizes[i+1])
self.layers.append(layer)
self.add_module("layer"+str(i+1), layer)
if batch_norm and not(discriminator and i==0):# if used as discriminator, then there is no batch norm in the first layer
bn = nn.BatchNorm1d(layer_sizes[i+1], eps=1e-05, momentum=0.1)
self.layers.append(bn)
self.add_module("bn"+str(i+1), bn)
self.layers.append(activation)
self.add_module("activation"+str(i+1), activation)
layer = nn.Linear(layer_sizes[-1], output_size)
self.layers.append(layer)
self.add_module("layer"+str(len(self.layers)), layer)
self.init_weights()
def forward(self, x):
for i, layer in enumerate(self.layers):
x = layer(x)
return x
def init_weights(self):
for layer in self.layers:
try:
layer.weight.data.normal_(0, self.init_w)
layer.bias.data.fill_(0)
except: pass
class Encoder(nn.Module):
def __init__(self, embedder, input_size, hidden_size, bidir, n_layers, dropout=0.5, noise_radius=0.2):
super(Encoder, self).__init__()
self.hidden_size = hidden_size
self.noise_radius=noise_radius
self.n_layers = n_layers
self.bidir = bidir
assert type(self.bidir)==bool
self.dropout=dropout
self.embedding = embedder # nn.Embedding(vocab_size, emb_size)
self.rnn = nn.GRU(input_size, hidden_size, n_layers, batch_first=True, bidirectional=bidir)
self.init_h = nn.Parameter(torch.randn(self.n_layers*(1+self.bidir), 1, self.hidden_size), requires_grad=True)#learnable h0
self.init_weights()
def init_weights(self):
for w in self.rnn.parameters(): # initialize the gate weights with orthogonal
if w.dim()>1:
weight_init.orthogonal_(w)
def store_grad_norm(self, grad):
norm = torch.norm(grad, 2, 1)
self.grad_norm = norm.detach().data.mean()
return grad
def forward(self, inputs, input_lens=None, init_h=None, noise=False):
# init_h: [n_layers*n_dir x batch_size x hid_size]
if self.embedding is not None:
inputs=self.embedding(inputs) # input: [batch_sz x seq_len] -> [batch_sz x seq_len x emb_sz]
batch_size, seq_len, emb_size=inputs.size()
inputs=F.dropout(inputs, self.dropout, self.training)# dropout
if input_lens is not None:# sort and pack sequence
input_lens_sorted, indices = input_lens.sort(descending=True)
inputs_sorted = inputs.index_select(0, indices)
inputs = pack_padded_sequence(inputs_sorted, input_lens_sorted.data.tolist(), batch_first=True)
if init_h is None:
init_h = self.init_h.expand(-1,batch_size,-1).contiguous()# use learnable initial states, expanding along batches
#self.rnn.flatten_parameters() # time consuming!!
hids, h_n = self.rnn(inputs, init_h) # hids: [b x seq x (n_dir*hid_sz)]
# h_n: [(n_layers*n_dir) x batch_sz x hid_sz] (2=fw&bw)
if input_lens is not None: # reorder and pad
_, inv_indices = indices.sort()
hids, lens = pad_packed_sequence(hids, batch_first=True)
hids = hids.index_select(0, inv_indices)
h_n = h_n.index_select(1, inv_indices)
h_n = h_n.view(self.n_layers, (1+self.bidir), batch_size, self.hidden_size) #[n_layers x n_dirs x batch_sz x hid_sz]
h_n = h_n[-1] # get the last layer [n_dirs x batch_sz x hid_sz]
enc = h_n.transpose(0,1).contiguous().view(batch_size,-1) #[batch_sz x (n_dirs*hid_sz)]
#if enc.requires_grad:
# enc.register_hook(self.store_grad_norm) # store grad norm
# norms = torch.norm(enc, 2, 1) # normalize to unit ball (l2 norm of 1) - p=2, dim=1
# enc = torch.div(enc, norms.unsqueeze(1).expand_as(enc)+1e-5)
if noise and self.noise_radius > 0:
gauss_noise = torch.normal(means=torch.zeros(enc.size(), device=inputs.device),std=self.noise_radius)
enc = enc + gauss_noise
return enc, hids
class Encoder_cluster(nn.Module):
# def __init__(self, embedder, input_size, hidden_size, bidir, n_layers, dropout=0.5, noise_radius=0.2):
def __init__(self, input_dim, hidden_size, dropout, device, bidir = True, block = 'LSTM', n_layers=1):
super(Encoder_cluster, self).__init__()
self.hidden_size = hidden_size
# self.noise_radius=noise_radius
self.n_layers = n_layers
self.bidir = bidir
self.device = device
assert type(self.bidir)==bool
self.dropout=dropout
# self.embedding = embedder # nn.Embedding(vocab_size, emb_size)
self.block = block
if self.block == 'GRU':
self.rnn = nn.GRU(input_dim, hidden_size, n_layers, batch_first=True, bidirectional=bidir, dropout = self.dropout)
else:
self.rnn = nn.LSTM(input_dim, hidden_size, n_layers, batch_first=True, bidirectional=bidir, dropout = self.dropout)
# self.init_h = nn.Parameter(torch.randn(self.n_layers*(1+self.bidir), 1, self.hidden_size), requires_grad=True)#learnable h0
self.init_h = torch.zeros([self.n_layers*(1+self.bidir), 1, self.hidden_size], device = self.device)
if self.block == 'LSTM':
self.init_c = torch.zeros([self.n_layers*(1+self.bidir), 1, self.hidden_size],device = self.device)
# self.init_weights()
def init_weights(self):
for w in self.rnn.parameters(): # initialize the gate weights with orthogonal
if w.dim()>1:
weight_init.orthogonal_(w)
def store_grad_norm(self, grad):
norm = torch.norm(grad, 2, 1)
self.grad_norm = norm.detach().data.mean()
return grad
def forward2(self, inputs, input_lens, rnn_out, exp_last_h_n, exp_last_c_n, init_h=None, init_c = None, noise=False):
batch_size, seq_len, emb_size=inputs.size()
# if input_lens is not None:# sort and pack sequence
output = torch.zeros_like(inputs)
input_lens_sorted, indices = input_lens.sort(descending=True)
# print(inputs.shape, input_lens.shape)
inputs_sorted = inputs.index_select(0, indices)
if init_h is None:
init_h = self.init_h.expand(-1,batch_size,-1).contiguous()# use learnable initial states, expanding along batches
if self.block == 'LSTM':
if init_c is None:
init_c = self.init_c.expand(-1,batch_size,-1).contiguous()
last_len = None
last_id = None
last_h_n = torch.zeros([(1+self.bidir)*self.n_layers, batch_size, self.hidden_size])
last_c_n = torch.zeros([(1+self.bidir)*self.n_layers, batch_size, self.hidden_size])
output_list = torch.zeros([batch_size, seq_len,(1+self.bidir)*self.hidden_size])
for k in range(len(input_lens_sorted)):
if last_len is None:
last_len = input_lens_sorted[k]
last_id = k
else:
if last_len == input_lens_sorted[k]:
continue
else:
if self.block == 'LSTM':
hids, (h_n, c_n) = self.rnn(inputs_sorted[last_id:k, 0:last_len], (init_h[:,last_id:k,:], init_c[:,last_id:k,:]))
last_c_n[:,last_id:k] = c_n
else:
hids, h_n = self.rnn(inputs_sorted[last_id:k, 0:last_len], init_h[:,last_id:k,:])
output_list[last_id:k, 0:last_len] = hids
last_h_n[:,last_id:k] = h_n
last_id = k
last_len = input_lens_sorted[k]
if self.block == 'LSTM':
hids, (h_n, c_n) = self.rnn(inputs_sorted[last_id:k+1, 0:last_len], (init_h[:,last_id:k+1,:], init_c[:,last_id:k+1,:]))
last_c_n[:,last_id:k+1] = c_n
else:
hids, h_n = self.rnn(inputs_sorted[last_id:k+1, 0:last_len], init_h[:,last_id:k+1,:])
output_list[last_id:k+1, 0:last_len] = hids
last_h_n[:,last_id:k+1] = h_n
_, inv_indices = indices.sort()
output_hiddens = output_list[inv_indices]
print(torch.norm(output_hiddens[0, 0:input_lens[0]] - rnn_out[0, 0:input_lens[0]]))
print(torch.norm(output_hiddens[-1, 0:input_lens[-1]] - rnn_out[-1, 0:input_lens[-1]]))
print(torch.norm(last_h_n[:,inv_indices] - exp_last_h_n))
print(torch.norm(last_c_n[:,inv_indices] - exp_last_c_n))
return output_hiddens, (last_h_n[:,inv_indices], last_c_n[:, inv_indices])
# shifted_lens = torch.zeros_like(input_lens_sorted)
#
# shifted_lens[0:len(input_lens_sorted) - 1] = input_lens_sorted[1:len(input_lens_sorted)]
#
# gaps = shifted_lens - input_lens_sorted
# for k in range(len(input_lens_sorted)):
# sorted_inputs = inputs[inputs_sorted]
def check_hidden_states(self, x, x_lens, init_h, init_c, hids, h_n, c_n):
T_max = x_lens.max()
for i in range(x.shape[0]):
origin_hids, (curr_h_n, curr_c_n) = self.rnn(x[i, 0:x_lens[i]].view(1, x_lens[i], x.shape[2]), (init_h[:,i,:].view(init_h[:,i,:].shape[0], 1, init_h[:,i,:].shape[1]), init_c[:,i,:].view(init_c[:,i,:].shape[0], 1, init_c[:,i,:].shape[1])))
# print(torch.norm(origin_hids - hids[i]))
print('lens::', T_max, x_lens[i])
print(torch.norm(curr_h_n.view(-1) - h_n[:,i,:].reshape((-1))))
print(torch.norm(curr_c_n.view(-1) - c_n[:,i,:].reshape((-1))))
def forward(self, inputs, input_lens=None, init_h=None, init_c = None, noise=False, test = False):
# init_h: [n_layers*n_dir x batch_size x hid_size]
# if self.embedding is not None:
# inputs=self.embedding(inputs) # input: [batch_sz x seq_len] -> [batch_sz x seq_len x emb_sz]
# input_data = inputs.clone()
origin_inputs = inputs.clone()
batch_size, seq_len, emb_size=inputs.size()
# inputs=F.dropout(inputs, self.dropout, self.training)# dropout
if input_lens is not None:# sort and pack sequence
input_lens_sorted, indices = input_lens.sort(descending=True)
# print(inputs.shape, input_lens.shape)
inputs_sorted = inputs.index_select(0, indices)
inputs = pack_padded_sequence(inputs_sorted, input_lens_sorted.data.tolist(), batch_first=True)
if init_h is not None:
# origin_init_h = init_h.clone()
init_h = init_h.index_select(1, indices)
if self.block == 'LSTM':
# origin_init_c= init_c.clone()
init_c = init_c.index_select(1, indices)
# origin_hids2, (h_n2, c_n2) = self.rnn(input_data, (origin_init_h, origin_init_c))
if init_h is None:
init_h = self.init_h.expand(-1,batch_size,-1).contiguous()# use learnable initial states, expanding along batches
if self.block == 'LSTM':
if init_c is None:
init_c = self.init_c.expand(-1,batch_size,-1).contiguous()
origin_hids, (h_n, c_n) = self.rnn(inputs, (init_h, init_c))
else:
origin_hids, h_n = self.rnn(inputs, init_h)
#self.rnn.flatten_parameters() # time consuming!!
# hids: [b x seq x (n_dir*hid_sz)]
# h_n: [(n_layers*n_dir) x batch_sz x hid_sz] (2=fw&bw)
if input_lens is not None: # reorder and pad
_, inv_indices = indices.sort()
hids, lens = pad_packed_sequence(origin_hids, batch_first=True)
hids = hids.index_select(0, inv_indices)
h_n = h_n.index_select(1, inv_indices)
if self.block == 'LSTM':
c_n = c_n.index_select(1, inv_indices)
# if test:
#
# lstm_layer = nn.LSTM(self.rnn.input_size, self.rnn.hidden_size, batch_first=True)
#
# print(input_data.shape, lstm_layer)
#
# full_rnn_decoded_out4, (last_decoded_h_n4, last_decoded_c_n4) = lstm_layer(input_data, (init_h, init_c))
#
# print(torch.norm(full_rnn_decoded_out4 - hids))
#
# print('here')
# self.check_hidden_states(origin_inputs, input_lens, init_h, init_c, hids, h_n, c_n)
#
# print('here')
# h_n = h_n.view(self.n_layers, (1+self.bidir), batch_size, self.hidden_size) #[n_layers x n_dirs x batch_sz x hid_sz]
# h_n = h_n[-1] # get the last layer [n_dirs x batch_sz x hid_sz]
# enc_h = h_n.transpose(0,1).contiguous().view(batch_size,-1) #[batch_sz x (n_dirs*hid_sz)]
#
# if self.block == 'LSTM':
# c_n = c_n.view(self.n_layers, (1+self.bidir), batch_size, self.hidden_size) #[n_layers x n_dirs x batch_sz x hid_sz]
# c_n = c_n[-1] # get the last layer [n_dirs x batch_sz x hid_sz]
# enc_c = c_n.transpose(0,1).contiguous().view(batch_size,-1) #[batch_sz x (n_dirs*hid_sz)]
#if enc.requires_grad:
# enc.register_hook(self.store_grad_norm) # store grad norm
# norms = torch.norm(enc, 2, 1) # normalize to unit ball (l2 norm of 1) - p=2, dim=1
# enc = torch.div(enc, norms.unsqueeze(1).expand_as(enc)+1e-5)
# if noise and self.noise_radius > 0:
# gauss_noise = torch.normal(means=torch.zeros(enc.size(), device=inputs.device),std=self.noise_radius)
# enc = enc + gauss_noise
if self.block =='LSTM':
return hids, (h_n, c_n)
else:
return hids, h_n
class GatedTransition2(nn.Module):
"""
Parameterizes the gaussian latent transition probability `p(z_t | z_{t-1})`
See section 5 in the reference for comparison.
"""
def __init__(self, z_dim, h_dim, trans_dim):
super(GatedTransition2, self).__init__()
self.gate = nn.Sequential(
nn.Linear(h_dim, trans_dim),
nn.ReLU(),
nn.Linear(trans_dim, z_dim),
nn.Sigmoid()
)
self.proposed_mean = nn.Sequential(
nn.Linear(h_dim, trans_dim),
nn.ReLU(),
nn.Linear(trans_dim, z_dim)
)
self.lstm = torch.nn.LSTM(z_dim, h_dim)
self.z_to_mu = nn.Linear(z_dim, z_dim)
# modify the default initialization of z_to_mu so that it starts out as the identity function
self.z_to_mu.weight.data = torch.eye(z_dim)
self.z_to_mu.bias.data = torch.zeros(z_dim)
self.z_to_logvar = nn.Linear(z_dim, z_dim)
self.relu = nn.ReLU()
def forward(self, z_t_1, h_t_1, c_t_1):
"""
Given the latent `z_{t-1}` corresponding to the time step t-1
we return the mean and scale vectors that parameterize the (diagonal) gaussian distribution `p(z_t | z_{t-1})`
"""
gate = self.gate(h_t_1) # compute the gating function
_, (h_t, c_t) = self.lstm(z_t_1.view(1, z_t_1.shape[0], z_t_1.shape[1]).contiguous(), (h_t_1, c_t_1))
proposed_mean = self.proposed_mean(h_t) # compute the 'proposed mean'
mu = (1 - gate) * self.z_to_mu(z_t_1) + gate * proposed_mean # compute the scale used to sample z_t, using the proposed mean from
logvar = self.z_to_logvar(self.relu(proposed_mean))
epsilon = torch.randn(z_t_1.size(), device=z_t_1.device) # sampling z by re-parameterization
z_t = mu + epsilon * torch.exp(0.5 * logvar) # [batch_sz x z_sz]
return z_t, mu.view(mu.shape[1], mu.shape[2]), logvar.view(logvar.shape[1], logvar.shape[2]), h_t, c_t
class GatedTransition(nn.Module):
"""
Parameterizes the gaussian latent transition probability `p(z_t | z_{t-1})`
See section 5 in the reference for comparison.
"""
def __init__(self, z_dim, trans_dim):
super(GatedTransition, self).__init__()
self.gate = nn.Sequential(
nn.Linear(z_dim, z_dim),
nn.Sigmoid()
)
self.proposed_mean = nn.Sequential(
nn.Linear(z_dim, z_dim)
)
self.z_to_mu = nn.Linear(z_dim, z_dim)
# modify the default initialization of z_to_mu so that it starts out as the identity function
self.z_to_mu.weight.data = torch.eye(z_dim)
self.z_to_mu.bias.data = torch.zeros(z_dim)
self.z_to_logvar = nn.Linear(z_dim, z_dim)
self.relu = nn.ReLU()
def forward(self, z_t_1):
"""
Given the latent `z_{t-1}` corresponding to the time step t-1
we return the mean and scale vectors that parameterize the (diagonal) gaussian distribution `p(z_t | z_{t-1})`
"""
gate = self.gate(z_t_1) # compute the gating function
proposed_mean = self.proposed_mean(z_t_1) # compute the 'proposed mean'
mu = (1 - gate) * self.z_to_mu(z_t_1) + gate * proposed_mean # compute the scale used to sample z_t, using the proposed mean from
logvar = F.softplus(self.z_to_logvar(self.relu(proposed_mean)))
epsilon = torch.randn(z_t_1.size(), device=z_t_1.device) # sampling z by re-parameterization
# z_t = mu + epsilon * torch.exp(0.5 * logvar) # [batch_sz x z_sz]
z_t = mu + epsilon * logvar
return z_t, mu, logvar
class PostNet_cluster(nn.Module):
"""
Parameterizes `q(z_t|z_{t-1}, x_{t:T})`, which is the basic building block of the inference (i.e. the variational distribution).
The dependence on `x_{t:T}` is through the hidden state of the RNN
"""
def __init__(self, z_dim, h_dim, cluster_num, dropout, sampling_times, bidirt = True):
super(PostNet_cluster, self).__init__()
# self.z_to_h = nn.Sequential(
# nn.Linear(z_dim, (1+bidirt)*h_dim),
# nn.Tanh(),
# nn.Dropout(p = dropout)
# )
# self.t_thres = t_thres
self.h_to_z = nn.Sequential(
nn.Linear((1+bidirt)*h_dim + z_dim, cluster_num),
nn.Dropout(p = dropout)
# nn.ReLU()
# nn.Linear(e_dim, cluster_num)
# nn.Softmax()
)
# self.use_sprasemax = use_sprasemax
#
# self.use_gumbel_softmax = use_gumbel_softmax
self.sampling_times = sampling_times
# self.h_to_mu = nn.Linear(h_dim, z_dim)
# self.h_to_logvar = nn.Linear(h_dim, z_dim)
# def sample_multi_times(self, z_t_prev_category, phi_table, S, h_x):
#
# averaged_z_t_category = 0
#
# for i in range(S):
# sampled_z_t_prev = F.gumbel_softmax(torch.log(z_t_prev_category), tau = 0.1, dim = -1)
#
# phi_z_t_prev = self.get_z_t_from_samples(sampled_z_t_prev, phi_table)
#
# z_t_category = self.gen_z_t_dist_now(phi_z_t_prev, h_x)* sampled_z_t_prev * z_t_prev_category #q(z_t|z_{t-1})
#
# averaged_z_t_category += sampled_z_t_prev
#
# sampled_z_t_prev = sampled_z_t_prev/S
def gen_z_t_dist_now(self, z_t_1, h_x):
# h_combined = 0.5*(self.z_to_h(z_t_1) + h_x)# combine the rnn hidden state with a transformed version of z_t_1
h_combined = torch.cat([z_t_1, h_x], -1)
# if not self.use_sprasemax:
z_category = F.softmax(self.h_to_z(h_combined), dim = -1)
return z_category,z_category
# else:
# z_category = F.softmax(self.h_to_z(h_combined), dim = -1)
#
# z_category_sparse = sparsemax(self.h_to_z(h_combined))
#
# return z_category, z_category_sparse
def get_z_t_from_samples(self, z_t, phi_table):
return torch.mm(z_t, torch.t(phi_table))
def forward(self, z_t_1, h_x, phi_table, t, temp=0):
"""
Given the latent z at a particular time step t-1 as well as the hidden
state of the RNN `h(x_{t:T})` we return the mean and scale vectors that
parameterize the (diagonal) gaussian distribution `q(z_t|z_{t-1}, x_{t:T})`
"""
# sparsemax.device = z_t_1.device
z_category, z_category_sparse = self.gen_z_t_dist_now(z_t_1, h_x)
# if t > self.t_thres:
#
# if self.use_gumbel_softmax:
# # print(t, 'inference here')
# # device = z_category.device
#
# averaged_z_t = 0
#
# log_prob = Variable(torch.log(z_category))
#
# for k in range(self.sampling_times):
# curr_z_t = F.gumbel_softmax(log_prob, tau = 0.05)
#
# # curr_z_t = sparsemax(log_prob)
#
#
# averaged_z_t += curr_z_t
#
# del curr_z_t
#
# # averaged_z_t = averaged_z_t.to(device)
#
# z_t = averaged_z_t/self.sampling_times
#
# # print('diff::', torch.norm(z_t - z_category))
# #
# # print()
# else:
# z_t = z_category
#
# else:
z_t = z_category
if len(z_t.shape) == 2:
phi_z = torch.mm(z_t, torch.t(phi_table))
else:
phi_table_full = (torch.t(phi_table)).view(1, phi_table.shape[1], phi_table.shape[0])
phi_table_full = phi_table_full.repeat(phi_table.shape[1], 1, 1)
phi_z = torch.bmm(z_t, phi_table_full)
# mu = self.h_to_mu(h_combined)
# logvar = self.h_to_logvar(h_combined)
# std = torch.exp(0.5 * logvar)
# epsilon = torch.randn(z_t_1.size(), device=z_t_1.device) # sampling z by re-parameterization
# z_t = epsilon * std + mu # [batch_sz x z_sz]
return z_t, z_category, phi_z, z_category_sparse
class PostNet_cluster_time(nn.Module):
"""
Parameterizes `q(z_t|z_{t-1}, x_{t:T})`, which is the basic building block of the inference (i.e. the variational distribution).
The dependence on `x_{t:T}` is through the hidden state of the RNN
"""
def __init__(self, z_dim, h_dim, cluster_num, dropout, use_gumbel_softmax, sampling_times, bidirt = True):
super(PostNet_cluster_time, self).__init__()
self.z_to_h = nn.Sequential(
nn.Linear(z_dim+1, (1+bidirt)*h_dim),
nn.Tanh(),
nn.Dropout(p = dropout)
)
self.h_to_z = nn.Sequential(
nn.Linear((1+bidirt)*h_dim, cluster_num),
nn.Dropout(p = dropout)
# nn.ReLU()
# nn.Linear(e_dim, cluster_num)
# nn.Softmax()
)
self.use_gumbel_softmax = use_gumbel_softmax
self.sampling_times = sampling_times
# self.h_to_mu = nn.Linear(h_dim, z_dim)
# self.h_to_logvar = nn.Linear(h_dim, z_dim)
# def sample_multi_times(self, z_t_prev_category, phi_table, S, h_x):
#
# averaged_z_t_category = 0
#
# for i in range(S):
# sampled_z_t_prev = F.gumbel_softmax(torch.log(z_t_prev_category), tau = 0.1, dim = -1)
#
# phi_z_t_prev = self.get_z_t_from_samples(sampled_z_t_prev, phi_table)
#
# z_t_category = self.gen_z_t_dist_now(phi_z_t_prev, h_x)* sampled_z_t_prev * z_t_prev_category #q(z_t|z_{t-1})
#
# averaged_z_t_category += sampled_z_t_prev
#
# sampled_z_t_prev = sampled_z_t_prev/S
def gen_z_t_dist_now(self, z_t_1, h_x):
h_combined = 0.5*(self.z_to_h(z_t_1) + h_x)# combine the rnn hidden state with a transformed version of z_t_1
z_category = F.softmax(self.h_to_z(h_combined), dim = 1)
return z_category
def get_z_t_from_samples(self, z_t, phi_table):
return torch.mm(z_t, torch.t(phi_table))
def forward(self, z_t_1, h_x, phi_table):
"""
Given the latent z at a particular time step t-1 as well as the hidden
state of the RNN `h(x_{t:T})` we return the mean and scale vectors that
parameterize the (diagonal) gaussian distribution `q(z_t|z_{t-1}, x_{t:T})`
"""
z_category = self.gen_z_t_dist_now(z_t_1, h_x)
if self.use_gumbel_softmax:
# device = z_category.device
averaged_z_t = 0
log_prob = Variable(torch.log(z_category))
for k in range(self.sampling_times):
curr_z_t = F.gumbel_softmax(log_prob, tau = 0.1)
averaged_z_t += curr_z_t
del curr_z_t
# averaged_z_t = averaged_z_t.to(device)
z_t = averaged_z_t/self.sampling_times
else:
z_t = z_category
phi_z = torch.mm(z_t, torch.t(phi_table))
# mu = self.h_to_mu(h_combined)
# logvar = self.h_to_logvar(h_combined)
# std = torch.exp(0.5 * logvar)
# epsilon = torch.randn(z_t_1.size(), device=z_t_1.device) # sampling z by re-parameterization
# z_t = epsilon * std + mu # [batch_sz x z_sz]
return z_t, z_category, phi_z
class PostNet_cluster2(nn.Module):
"""
Parameterizes `q(z_t|z_{t-1}, x_{t:T})`, which is the basic building block of the inference (i.e. the variational distribution).
The dependence on `x_{t:T}` is through the hidden state of the RNN
"""
def __init__(self, z_dim, h_dim, z_std, dropout):
super(PostNet_cluster2, self).__init__()
self.z_to_h = nn.Sequential(
nn.Linear(z_dim, 2*h_dim),
nn.Tanh(),
nn.Dropout(p = dropout)
)
self.h_to_z_mean = nn.Sequential(
nn.Linear(2*h_dim, z_dim),
nn.Dropout(p = dropout)
# nn.ReLU()
# nn.Linear(e_dim, cluster_num)
# nn.Softmax()
)
# self.z_std = z_std
self.h_to_z_var = nn.Sequential(
nn.Linear(2*h_dim, z_dim),
nn.Dropout(p = dropout)
# nn.ReLU()
# nn.Linear(e_dim, cluster_num)
# nn.Softmax()
)
# self.h_to_mu = nn.Linear(h_dim, z_dim)
# self.h_to_logvar = nn.Linear(h_dim, z_dim)
def forward(self, z_t_1, h_x):
"""
Given the latent z at a particular time step t-1 as well as the hidden
state of the RNN `h(x_{t:T})` we return the mean and scale vectors that
parameterize the (diagonal) gaussian distribution `q(z_t|z_{t-1}, x_{t:T})`
"""
h_combined = 0.5*(self.z_to_h(z_t_1) + h_x)# combine the rnn hidden state with a transformed version of z_t_1
z_mean = self.h_to_z_mean(h_combined)
z_var = self.h_to_z_var(h_combined)
epsilon = torch.randn(z_t_1.size(), device=z_t_1.device) # sampling z by re-parameterization
z_t = z_mean + epsilon * torch.exp(0.5 * z_var) # [batch_sz x z_sz]
# z_t = F.gumbel_softmax(z_category)
# z_t = z_category
#
# phi_z = torch.mm(z_t, torch.t(phi_table))
# mu = self.h_to_mu(h_combined)
# logvar = self.h_to_logvar(h_combined)
# std = torch.exp(0.5 * logvar)
# epsilon = torch.randn(z_t_1.size(), device=z_t_1.device) # sampling z by re-parameterization
# z_t = epsilon * std + mu # [batch_sz x z_sz]
return z_t, z_mean, z_var
class PostNet(nn.Module):
"""
Parameterizes `q(z_t|z_{t-1}, x_{t:T})`, which is the basic building block of the inference (i.e. the variational distribution).
The dependence on `x_{t:T}` is through the hidden state of the RNN
"""
def __init__(self, z_dim, h_dim):
super(PostNet, self).__init__()
self.z_to_h = nn.Sequential(
nn.Linear(z_dim, h_dim),
nn.Tanh()
)
self.h_to_mu = nn.Linear(h_dim, z_dim)
self.h_to_logvar = nn.Linear(h_dim, z_dim)
def forward(self, z_t_1, h_x):
"""
Given the latent z at a particular time step t-1 as well as the hidden
state of the RNN `h(x_{t:T})` we return the mean and scale vectors that
parameterize the (diagonal) gaussian distribution `q(z_t|z_{t-1}, x_{t:T})`
"""
h_combined = 0.5*(self.z_to_h(z_t_1) + h_x)# combine the rnn hidden state with a transformed version of z_t_1
mu = self.h_to_mu(h_combined)
logvar = self.h_to_logvar(h_combined)
std = F.softplus(logvar)
epsilon = torch.randn(z_t_1.size(), device=z_t_1.device) # sampling z by re-parameterization
z_t = epsilon * std + mu # [batch_sz x z_sz]
return z_t, mu, logvar
class FilterLinear(nn.Module):
def __init__(self, in_features, out_features, filter_square_matrix, bias=True):
'''
filter_square_matrix : filter square matrix, whose each elements is 0 or 1.
'''
super(FilterLinear, self).__init__()
self.in_features = in_features
self.out_features = out_features
use_gpu = torch.cuda.is_available()
self.filter_square_matrix = None
if use_gpu:
self.filter_square_matrix = Variable(filter_square_matrix.cuda(), requires_grad=False)
else:
self.filter_square_matrix = Variable(filter_square_matrix, requires_grad=False)
self.weight = Parameter(torch.Tensor(out_features, in_features))
if bias:
self.bias = Parameter(torch.Tensor(out_features))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
stdv = 1. / math.sqrt(self.weight.size(1))
self.weight.data.uniform_(-stdv, stdv)
if self.bias is not None:
self.bias.data.uniform_(-stdv, stdv)
# print(self.weight.data)
# print(self.bias.data)
def forward(self, input):
# print(self.filter_square_matrix.mul(self.weight))
return F.linear(input, self.filter_square_matrix.mul(self.weight), self.bias)
def __repr__(self):
return self.__class__.__name__ + '(' \
+ 'in_features=' + str(self.in_features) \
+ ', out_features=' + str(self.out_features) \
+ ', bias=' + str(self.bias is not None) + ')'
class GRU_module(nn.Module):
def __init__(self, input_size, hidden_size, device, num_layers=1, x_mean=0,\
bias=True, batch_first=False, bidirectional=False, dropout=0, dropout_type='mloss', return_hidden = False):
super(GRU_module, self).__init__()
self.hidden_size = hidden_size
# self.noise_radius=noise_radius
self.n_layers = num_layers
self.bidir = bidirectional
self.device = device
assert type(self.bidir)==bool
self.dropout=dropout
# self.embedding = embedder # nn.Embedding(vocab_size, emb_size)
self.rnn = GRUD_cell(input_size, hidden_size, device, self.n_layers, x_mean, bias = True, batch_first=True, bidirectional=self.bidir, dropout = self.dropout)
# self.init_h = nn.Parameter(torch.randn(self.n_layers*(1+self.bidir), 1, self.hidden_size), requires_grad=True)#learnable h0
self.init_h = torch.zeros([self.n_layers, 1, self.hidden_size], device = self.device)
# if self.block == 'LSTM':
# self.init_c = torch.zeros([self.n_layers*(1+self.bidir), 1, self.hidden_size],device = self.device)
def forward2(self, inputs, masks, input_lens, deltas, init_h=None):
batch_size, seq_len, emb_size=inputs.size()
# if input_lens is not None:# sort and pack sequence
# output = torch.zeros_like(inputs)
input_lens_sorted, indices = input_lens.sort(descending=True)
# print(inputs.shape, input_lens.shape)
inputs_sorted = inputs.index_select(0, indices)
mask_sorted = masks.index_select(0, indices)
delta_sorted = deltas.index_select(0, indices)
if init_h is None:
init_h = self.init_h.expand(-1,batch_size,-1).contiguous()# use learnable initial states, expanding along batches
# if self.block == 'LSTM':
# if init_c is None:
# init_c = self.init_c.expand(-1,batch_size,-1).contiguous()
hids, _ = self.rnn(inputs_sorted, mask_sorted, delta_sorted, init_h)
last_len = None
last_id = None
last_h_n = torch.zeros([self.n_layers, batch_size, self.hidden_size], device = self.device)
# last_c_n = torch.zeros([self.n_layers, batch_size, self.hidden_size])
# output_list = torch.zeros([batch_size, seq_len,(1+self.bidir)*self.hidden_size])
output_list = torch.zeros([batch_size, seq_len,1*self.hidden_size], device = self.device)
for k in range(len(input_lens_sorted)):
if last_len is None:
last_len = input_lens_sorted[k]
last_id = k
else:
if last_len == input_lens_sorted[k]:
continue
else:
# if self.block == 'LSTM':
# hids, (h_n, c_n) = self.rnn(inputs_sorted[last_id:k, 0:last_len], (init_h[:,last_id:k,:], init_c[:,last_id:k,:]))
# last_c_n[:,last_id:k] = c_n
# else:
'''Mask, Delta, init_h'''
# hids, h_n = self.rnn(inputs_sorted[last_id:k, 0:last_len], mask_sorted[last_id:k, 0:last_len], delta_sorted[last_id:k, 0:last_len], init_h[:,last_id:k,:])
# output_list[last_id:k, 0:last_len] = hids
last_h_n[:,last_id:k] = hids[last_id:k, last_len - 1]
last_id = k
last_len = input_lens_sorted[k]
# if self.block == 'LSTM':
# hids, (h_n, c_n) = self.rnn(inputs_sorted[last_id:k+1, 0:last_len], (init_h[:,last_id:k+1,:], init_c[:,last_id:k+1,:]))
# last_c_n[:,last_id:k+1] = c_n
# else:
# hids, h_n = self.rnn(inputs_sorted[last_id:k+1, 0:last_len], mask_sorted[last_id:k+1, 0:last_len], delta_sorted[last_id:k+1, 0:last_len], init_h[:,last_id:k+1,:])
# output_list[last_id:k+1, 0:last_len] = hids
last_h_n[:,last_id:k+1] = hids[last_id:k+1, last_len - 1]
_, inv_indices = indices.sort()
output_hiddens = hids[inv_indices]
# print(torch.norm(output_hiddens[0, 0:input_lens[0]] - rnn_out[0, 0:input_lens[0]]))
#
# print(torch.norm(output_hiddens[-1, 0:input_lens[-1]] - rnn_out[-1, 0:input_lens[-1]]))
#
# print(torch.norm(last_h_n[:,inv_indices] - exp_last_h_n))
#
# print(torch.norm(last_c_n[:,inv_indices] - exp_last_c_n))
return output_hiddens, last_h_n[:,inv_indices]#, last_c_n[:, inv_indices])
def forward(self, inputs, masks, input_lens, deltas, init_h=None):
batch_size, seq_len, emb_size=inputs.size()
# if input_lens is not None:# sort and pack sequence
# output = torch.zeros_like(inputs)
input_lens_sorted, indices = input_lens.sort(descending=True)
# print(inputs.shape, input_lens.shape)
inputs_sorted = inputs.index_select(0, indices)
mask_sorted = masks.index_select(0, indices)
delta_sorted = deltas.index_select(0, indices)
if init_h is None:
init_h = self.init_h.expand(-1,batch_size,-1).contiguous()# use learnable initial states, expanding along batches
# if self.block == 'LSTM':
# if init_c is None:
# init_c = self.init_c.expand(-1,batch_size,-1).contiguous()
last_len = None
last_id = None
last_h_n = torch.zeros([self.n_layers, batch_size, self.hidden_size], device = self.device)
# last_c_n = torch.zeros([self.n_layers, batch_size, self.hidden_size])
# output_list = torch.zeros([batch_size, seq_len,(1+self.bidir)*self.hidden_size])
output_list = torch.zeros([batch_size, seq_len,1*self.hidden_size], device = self.device)
for k in range(len(input_lens_sorted)):
if last_len is None:
last_len = input_lens_sorted[k]
last_id = k
else:
if last_len == input_lens_sorted[k]:
continue
else:
# if self.block == 'LSTM':
# hids, (h_n, c_n) = self.rnn(inputs_sorted[last_id:k, 0:last_len], (init_h[:,last_id:k,:], init_c[:,last_id:k,:]))
# last_c_n[:,last_id:k] = c_n
# else:
'''Mask, Delta, init_h'''
hids, h_n = self.rnn(inputs_sorted[last_id:k, 0:last_len], mask_sorted[last_id:k, 0:last_len], delta_sorted[last_id:k, 0:last_len], init_h[:,last_id:k,:])
output_list[last_id:k, 0:last_len] = hids
last_h_n[:,last_id:k] = h_n
last_id = k
last_len = input_lens_sorted[k]
# if self.block == 'LSTM':
# hids, (h_n, c_n) = self.rnn(inputs_sorted[last_id:k+1, 0:last_len], (init_h[:,last_id:k+1,:], init_c[:,last_id:k+1,:]))
# last_c_n[:,last_id:k+1] = c_n
# else:
hids, h_n = self.rnn(inputs_sorted[last_id:k+1, 0:last_len], mask_sorted[last_id:k+1, 0:last_len], delta_sorted[last_id:k+1, 0:last_len], init_h[:,last_id:k+1,:])
output_list[last_id:k+1, 0:last_len] = hids
last_h_n[:,last_id:k+1] = h_n
_, inv_indices = indices.sort()
output_hiddens = output_list[inv_indices]
# print(torch.norm(output_hiddens[0, 0:input_lens[0]] - rnn_out[0, 0:input_lens[0]]))
#
# print(torch.norm(output_hiddens[-1, 0:input_lens[-1]] - rnn_out[-1, 0:input_lens[-1]]))
#
# print(torch.norm(last_h_n[:,inv_indices] - exp_last_h_n))
#
# print(torch.norm(last_c_n[:,inv_indices] - exp_last_c_n))
return output_hiddens, last_h_n[:,inv_indices]#, last_c_n[:, inv_indices])
class GRUI_cell(nn.Module):
"""
Implementation of GRUD.