-
Notifications
You must be signed in to change notification settings - Fork 1
/
model.py
1633 lines (1418 loc) · 68.5 KB
/
model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import unicode_literals, print_function, division
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import torch.nn.init as init
from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence
def binary_cross_entropy_weight(y_pred, y, has_weight=False, weight_length=1, weight_max=10, device='cpu'):
"""
:param y_pred:
:param y:
:param weight_length: how long until the end of sequence shall we add weight
:param weight_value: the magnitude that the weight is enhanced
:return:
"""
if has_weight:
weight = torch.ones(y.size(0), y.size(1), y.size(2))
weight_linear = torch.arange(1, weight_length + 1) / weight_length * weight_max
weight_linear = weight_linear.view(1, weight_length, 1).repeat(y.size(0), 1, y.size(2))
weight[:, -1 * weight_length:, :] = weight_linear
loss = F.binary_cross_entropy(y_pred, y, weight=weight.to(device))
# loss = F.binary_cross_entropy(y_pred, y, weight=weight.cuda()
else:
loss = F.binary_cross_entropy(y_pred, y)
return loss.to(device)
def sample_tensor(y, sample=True, thres=0.5, device='cpu'):
# do sampling
if sample:
# y_thres = Variable(torch.rand(y.size())).cuda()
y_thres = Variable(torch.rand(y.size())).to(device)
y_result = torch.gt(y, y_thres).float()
# do max likelihood based on some threshold
else:
# y_thres = Variable(torch.ones(y.size()) * thres).cuda()
y_thres = Variable(torch.ones(y.size()) * thres).to(device)
y_result = torch.gt(y, y_thres).float()
return y_result
def gumbel_softmax(logits, temperature, eps=1e-9, device='cpu'):
"""
:param logits: shape: N*L
:param temperature:
:param eps:
:return:
"""
# get gumbel noise
noise = torch.rand(logits.size())
noise.add_(eps).log_().neg_()
noise.add_(eps).log_().neg_()
# noise = Variable(noise).cuda()
noise = Variable(noise).to(device)
x = (logits + noise) / temperature
x = F.softmax(x)
return x
# for i in range(10):
# x = Variable(torch.randn(1,10)).cuda()
# y = gumbel_softmax(x, temperature=0.01)
# print(x)
# print(y)
# _,id = y.topk(1)
# print(id)
def gumbel_sigmoid(logits, temperature, device='cpu'):
"""
:param logits:
:param temperature:
:param eps:
:return:
"""
# get gumbel noise
noise = torch.rand(logits.size()) # uniform(0,1)
noise_logistic = torch.log(noise) - torch.log(1 - noise) # logistic(0,1)
# noise = Variable(noise_logistic).cuda()
noise = Variable(noise_logistic).to(device)
x = (logits + noise) / temperature
x = torch.sigmoid(x)
return x
# x = Variable(torch.randn(100)).cuda()
# y = gumbel_sigmoid(x,temperature=0.01)
# print(x)
# print(y)
def sample_sigmoid(y_pred, sample=True, thres=0.5, sample_time=2, device='cpu'):
"""
do sampling over unnormalized score
:param y_pred: output (y_pred = fout(h). That's basically the logits. The unnormalized \theta in the paper).
:param sample: bool
:param thres: if not sample, the threshold
:param sample_time: how many times do we sample, if =1, do single sample
:return: sampled result
"""
# do sigmoid first
y_pred = torch.sigmoid(y_pred)
if sample:
if sample_time > 1:
# y_result = Variable(torch.rand(y.size(0), y.size(1), y.size(2))).cuda()
y_sampled_result = Variable(torch.rand(y_pred.size(0), y_pred.size(1), y_pred.size(2))).to(device)
# do sampling (loop over all batches)
for i in range(y_sampled_result.size(0)):
# do `multi_sample` times sampling
for j in range(sample_time):
# y_thres = Variable(torch.rand(y.size(1), y.size(2))).cuda()
y_thres = Variable(torch.rand(y_pred.size(1), y_pred.size(2))).to(device)
y_sampled_result[i] = torch.gt(y_pred[i], y_thres).float()
if (torch.sum(y_sampled_result[i]).data > 0).any():
break
# else:
# print('all zero', j)
else:
# y_thres = Variable(torch.rand(y.size(0), y.size(1), y.size(2))).cuda()
y_thres = Variable(torch.rand(y_pred.size(0), y_pred.size(1), y_pred.size(2))).to(device)
y_sampled_result = torch.gt(y_pred, y_thres).float()
else: # do max likelihood based on some threshold
# y_thres = Variable(torch.ones(y.size(0), y.size(1), y.size(2)) * thres).cuda()
y_thres = Variable(torch.ones(y_pred.size(0), y_pred.size(1), y_pred.size(2)) * thres).to(device)
y_sampled_result = torch.gt(y_pred, y_thres).float()
return y_sampled_result
def sample_softmax(y_pred, sample=True, device='cpu'):
"""
do sampling over unnormalized score
:param y_pred: output (y_pred = fout(h). That's basically the logits. The unnormalized \theta in the paper).
:param sample: bool If False, sample the value with the maximum likelihood.
:return: sampled result
"""
# do softmax first
y_pred = F.softmax(y_pred, dim=-1)
if sample:
y_sampled_result = Variable(torch.zeros(y_pred.shape[0], y_pred.shape[1])).to(torch.int64)
for i in range(y_pred.shape[0]):
y_sampled_result[i, 0] = torch.multinomial(y_pred[i, 0], 1).view(-1)
else: # do max likelihood
y_sampled_result = Variable(torch.zeros(y_pred.shape[0], y_pred.shape[1], y_pred.shape[2])).to(torch.int64)
for i in range(y_pred.shape[0]):
y_sampled_result[i, 0] = torch.argmax(y_pred[i, 0], dim=-1)
y_sampled_result = y_sampled_result.to(torch.int64)
return y_sampled_result
def sample_sigmoid_supervised(y_pred, y, current, y_len, sample_time=2, device='cpu'):
"""
do sampling over unnormalized score
:param y_pred: input
:param y: supervision
:param sample: bool
:param sample_time: how many times do we sample, if =1, do single sample
:return: sampled result
"""
# do sigmoid first
y_pred = torch.sigmoid(y_pred)
# do sampling
# y_result = Variable(torch.rand(y_pred.size(0), y_pred.size(1), y_pred.size(2))).cuda()
y_result = Variable(torch.rand(y_pred.size(0), y_pred.size(1), y_pred.size(2))).to(device)
# loop over all batches
for i in range(y_result.size(0)):
# using supervision
if current < y_len[i]:
while True:
# y_thres = Variable(torch.rand(y_pred.size(1), y_pred.size(2))).cuda()
y_thres = Variable(torch.rand(y_pred.size(1), y_pred.size(2))).to(device)
y_result[i] = torch.gt(y_pred[i], y_thres).float()
# print('current',current)
# print('y_result',y_result[i].data)
# print('y',y[i])
y_diff = y_result[i].data - y[i]
if (y_diff >= 0).all():
break
# supervision done
else:
# do `multi_sample` times sampling
for j in range(sample_time):
# y_thres = Variable(torch.rand(y_pred.size(1), y_pred.size(2))).cuda()
y_thres = Variable(torch.rand(y_pred.size(1), y_pred.size(2))).to(device)
y_result[i] = torch.gt(y_pred[i], y_thres).float()
if (torch.sum(y_result[i]).data > 0).any():
break
return y_result
def sample_softmax_supervised(y_pred, y, current, y_len, sample_time=2, device='cpu'):
"""
do sampling over unnormalized score
:param y_pred: input
:param y: supervision
:param sample: bool
:param sample_time: how many times do we sample, if =1, do single sample
:return: sampled result
"""
# do sigmoid first
y_pred = torch.sigmoid(y_pred)
# do sampling
# y_result = Variable(torch.rand(y_pred.size(0), y_pred.size(1), y_pred.size(2))).cuda()
y_result = Variable(torch.rand(y_pred.size(0), y_pred.size(1), y_pred.size(2))).to(device)
# loop over all batches
for i in range(y_result.size(0)):
# using supervision
if current < y_len[i]:
while True:
# y_thres = Variable(torch.rand(y_pred.size(1), y_pred.size(2))).cuda()
y_thres = Variable(torch.rand(y_pred.size(1), y_pred.size(2))).to(device)
y_result[i] = torch.gt(y_pred[i], y_thres).float()
# print('current',current)
# print('y_result',y_result[i].data)
# print('y',y[i])
y_diff = y_result[i].data - y[i]
if (y_diff >= 0).all():
break
# supervision done
else:
# do `multi_sample` times sampling
for j in range(sample_time):
# y_thres = Variable(torch.rand(y_pred.size(1), y_pred.size(2))).cuda()
y_thres = Variable(torch.rand(y_pred.size(1), y_pred.size(2))).to(device)
y_result[i] = torch.gt(y_pred[i], y_thres).float()
if (torch.sum(y_result[i]).data > 0).any():
break
return y_result
def sample_sigmoid_supervised_simple(y_pred, y, current, y_len, sample_time=2, device='cpu'):
"""
do sampling over unnormalized score
:param y_pred: input
:param y: supervision
:param sample: bool
:param sample_time: how many times do we sample, if =1, do single sample
:return: sampled result
"""
# apply sigmoid first
y_pred = torch.sigmoid(y_pred)
# y_result = Variable(torch.rand(y_pred.size(0), y_pred.size(1), y_pred.size(2))).cuda()
y_result = Variable(torch.rand(y_pred.size(0), y_pred.size(1), y_pred.size(2))).to(device)
# do sampling (loop over all batches)
for i in range(y_result.size(0)):
# using supervision
if current < y_len[i]:
y_result[i] = y[i]
# supervision done
else:
# do `multi_sample` times sampling
for j in range(sample_time):
# y_thres = Variable(torch.rand(y_pred.size(1), y_pred.size(2))).cuda()
y_thres = Variable(torch.rand(y_pred.size(1), y_pred.size(2))).to(device)
y_result[i] = torch.gt(y_pred[i], y_thres).float()
if (torch.sum(y_result[i]).data > 0).any():
break
return y_result
def sample_softmax_supervised_simple(y_pred, y, current, y_len, sample_time=2, device='cpu'):
"""
do sampling over unnormalized score
:param y_pred: input
:param y: supervision
:param sample: bool
:param sample_time: how many times do we sample, if =1, do single sample
:return: sampled result
"""
# apply sigmoid first
y_pred = torch.sigmoid(y_pred)
# y_result = Variable(torch.rand(y_pred.size(0), y_pred.size(1), y_pred.size(2))).cuda()
y_result = Variable(torch.rand(y_pred.size(0), y_pred.size(1), y_pred.size(2))).to(device)
# do sampling (loop over all batches)
for i in range(y_result.size(0)):
# using supervision
if current < y_len[i]:
y_result[i] = y[i]
# supervision done
else:
# do `multi_sample` times sampling
for j in range(sample_time):
# y_thres = Variable(torch.rand(y_pred.size(1), y_pred.size(2))).cuda()
y_thres = Variable(torch.rand(y_pred.size(1), y_pred.size(2))).to(device)
y_result[i] = torch.gt(y_pred[i], y_thres).float()
if (torch.sum(y_result[i]).data > 0).any():
break
return y_result
# current adopted model, LSTM+MLP || LSTM+VAE || LSTM+LSTM (where LSTM can be GRU as well)
#
# definition of terms
# h: hidden state of LSTM
# y: edge prediction, model output
# n: noise for generator
# l: whether an output is real or not, binary
# plain LSTM model
class LSTMPlain(nn.Module):
def __init__(
self,
input_size,
embedding_size,
hidden_size,
num_layers,
transform_input=True,
output_size=None,
device='cpu'
):
super(LSTMPlain, self).__init__()
self.input_size = input_size
self.embedding_size = embedding_size
self.hidden_size = hidden_size
self.num_layers = num_layers
self.transform_input = transform_input
self.output_size = output_size
self.device = device
if transform_input:
self.input = nn.Linear(self.input_size, self.embedding_size)
self.rnn = nn.LSTM(input_size=self.embedding_size, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True)
else:
self.rnn = nn.LSTM(input_size=self.input_size, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True)
if self.output_size is not None:
self.output = nn.Sequential(
nn.Linear(hidden_size, embedding_size),
nn.ReLU(),
nn.Linear(embedding_size, output_size)
)
self.relu = nn.ReLU()
# initialize
self.hidden = None # need initialize before forward run
for name, param in self.rnn.named_parameters():
if 'bias' in name:
nn.init.constant(param, 0.25)
elif 'weight' in name:
nn.init.xavier_uniform_(param, gain=nn.init.calculate_gain('sigmoid'))
for m in self.modules():
if isinstance(m, nn.Linear):
m.weight.data = init.xavier_uniform_(m.weight.data, gain=nn.init.calculate_gain('relu'))
def init_hidden(self, batch_size):
return (Variable(torch.zeros(self.num_layers, batch_size, self.hidden_size)).to(self.device),
Variable(torch.zeros(self.num_layers, batch_size, self.hidden_size)).to(self.device))
# return (Variable(torch.zeros(self.num_layers, batch_size, self.hidden_size)).cuda(),
# Variable(torch.zeros(self.num_layers, batch_size, self.hidden_size)).cuda())
def forward(self, input_raw, pack=False, input_len=None):
if self.transform_input:
input = self.input(input_raw)
input = self.relu(input)
else:
input = input_raw
if pack:
input = pack_padded_sequence(input, input_len, batch_first=True)
# output_raw[i, t]: hidden RNN embedding of the t-th time step of the **last** RNN layer of example i
# self.hidden[k, i]: hidden RNN embedding of the last time step of the k-th RNN layer of example i
# output_raw[i, input_len[i]-1] == self.hidden[-1, i]
output_raw, self.hidden = self.rnn(input, self.hidden)
if pack:
output_raw = pad_packed_sequence(output_raw, batch_first=True)[0]
if self.output_size is not None:
output_raw = self.output(output_raw)
# return hidden state at each time step
return output_raw
# plain GRU model
class GRUPlain(nn.Module):
def __init__(
self,
input_size,
embedding_size,
hidden_size,
num_layers,
transform_input=True,
output_size=None, # `output_size` is when the RNN has an output different than the hidden vectors
vocab_size_node_label=None, # `vocab_size_node_label` is when we convert labels to embeddings
embedding_size_node_label=None,
device='cpu'
):
super(GRUPlain, self).__init__()
self.input_size = input_size
self.embedding_size = embedding_size
self.embedding_size_node_label = embedding_size_node_label
self.hidden_size = hidden_size
self.num_layers = num_layers
self.transform_input = transform_input
self.output_size = output_size
self.vocab_size_node_label = vocab_size_node_label
self.device = device
if self.transform_input:
if self.vocab_size_node_label is not None and self.embedding_size_node_label is not None:
self.input_graph = nn.Linear(self.input_size, self.embedding_size)
self.input_node_label = nn.Embedding(self.vocab_size_node_label, self.embedding_size_node_label)
self.linear = nn.Linear(self.input_size * self.embedding_size_node_label, self.embedding_size)
rnn_input_size = 2 * self.embedding_size
else:
self.input = nn.Linear(self.input_size, self.embedding_size)
rnn_input_size = self.embedding_size
else:
rnn_input_size = self.input_size
self.rnn = nn.GRU(
input_size=rnn_input_size,
hidden_size=self.hidden_size,
num_layers=self.num_layers,
batch_first=True
)
if self.output_size is not None:
self.output = nn.Sequential(
nn.Linear(self.hidden_size, self.embedding_size),
nn.ReLU(),
nn.Linear(self.embedding_size, self.output_size)
)
self.relu = nn.ReLU()
self.hidden = None # need to initialize before forward run
for name, param in self.rnn.named_parameters():
if 'bias' in name:
nn.init.constant_(param, 0.25)
elif 'weight' in name:
nn.init.xavier_uniform_(param, gain=nn.init.calculate_gain('sigmoid'))
for m in self.modules():
if isinstance(m, nn.Linear) or isinstance(m, nn.Embedding):
m.weight.data = init.xavier_uniform_(m.weight.data, gain=nn.init.calculate_gain('relu'))
def init_hidden(self, batch_size):
return Variable(torch.zeros(self.num_layers, batch_size, self.hidden_size)).to(self.device)
# return Variable(torch.zeros(self.num_layers, batch_size, self.hidden_size)).cuda()
def forward(self, input_raw, pack=False, input_len=None):
if self.transform_input:
# input_raw[0]: (batch_size, max_num_node, max_num_node) -- input_raw[0][:, i]: edges of node i-1 against nodes 0, 1, ..., i-2
# input_raw[1]: (batch_size, max_num_node, max_num_node) -- input_raw[1][:, i]: labels up to node i-1 (0, 1, ..., i-1)
if isinstance(input_raw, tuple):
# input_graph: (batch_size, max_num_node, self.embedding_size)
input_graph = self.input_graph(input_raw[0])
# input_node_label: (batch_size, max_num_node, max_num_node, self.embedding_size_node_label)
input_node_label = self.input_node_label(input_raw[1])
# input_node_label: (batch_size, max_num_node, max_num_node * self.embedding_size_node_label)
input_node_label = input_node_label.contiguous().view(input_node_label.shape[0], input_node_label.shape[1], -1)
input_node_label = self.linear(input_node_label) # (batch_size, max_num_node, self.embedding_size)
input = torch.cat([input_graph, input_node_label], dim=-1) # (batch_size, max_num_node, 2 * self.embedding_size)
else:
input = self.input(input_raw)
input = self.relu(input)
else:
input = input_raw
if pack:
input = pack_padded_sequence(input, input_len, batch_first=True)
# output_raw[i, t]: hidden RNN embedding of the t-th time step of the **last** RNN layer of example i
# self.hidden[k, i]: hidden RNN embedding of the last time step of the k-th RNN layer of example i
# output_raw[i, input_len[i]-1] == self.hidden[-1, i]
output_raw, self.hidden = self.rnn(input, self.hidden)
if pack:
output_raw = pad_packed_sequence(output_raw, batch_first=True)[0]
# return hidden state at each time step
return output_raw if self.output_size is None else self.output(output_raw)
# a deterministic linear output
class MLPPlain(nn.Module):
def __init__(self, h_size, embedding_size, y_size):
super(MLPPlain, self).__init__()
self.h_size = h_size
self.embedding_size = embedding_size
self.y_size = y_size
self.deterministic_output = nn.Sequential(
nn.Linear(self.h_size, self.embedding_size),
nn.ReLU(),
nn.Linear(self.embedding_size, self.y_size)
)
for m in self.modules():
if isinstance(m, nn.Linear):
m.weight.data = init.xavier_uniform_(m.weight.data, gain=nn.init.calculate_gain('relu'))
def forward(self, h):
y = self.deterministic_output(h)
return y
# a deterministic linear output, additional output indicates if the sequence should continue to grow
class MLPTokenPlain(nn.Module):
def __init__(self, h_size, embedding_size, y_size):
super(MLPTokenPlain, self).__init__()
self.deterministic_output = nn.Sequential(
nn.Linear(h_size, embedding_size),
nn.ReLU(),
nn.Linear(embedding_size, y_size)
)
self.token_output = nn.Sequential(
nn.Linear(h_size, embedding_size),
nn.ReLU(),
nn.Linear(embedding_size, 1)
)
for m in self.modules():
if isinstance(m, nn.Linear):
m.weight.data = init.xavier_uniform_(m.weight.data, gain=nn.init.calculate_gain('relu'))
def forward(self, h):
y = self.deterministic_output(h)
t = self.token_output(h)
return y, t
# a deterministic linear output (update: add noise)
class MLPVAEPlain(nn.Module):
def __init__(self, h_size, embedding_size, y_size, device='cpu'):
super(MLPVAEPlain, self).__init__()
self.device = device
self.encode_11 = nn.Linear(h_size, embedding_size) # mu
self.encode_12 = nn.Linear(h_size, embedding_size) # lsgms
self.decode_1 = nn.Linear(embedding_size, embedding_size)
self.decode_2 = nn.Linear(embedding_size, y_size) # make edge prediction (reconstruct)
self.relu = nn.ReLU()
for m in self.modules():
if isinstance(m, nn.Linear):
m.weight.data = init.xavier_uniform_(m.weight.data, gain=nn.init.calculate_gain('relu'))
def forward(self, h):
# encoder
z_mu = self.encode_11(h)
z_lsgms = self.encode_12(h)
# re-parameterize
z_sgm = z_lsgms.mul(0.5).exp_()
eps = Variable(torch.randn(z_sgm.size())).to(self.device)
# eps = Variable(torch.randn(z_sgm.size())).cuda()
z = eps * z_sgm + z_mu
# decoder
y = self.decode_1(z)
y = self.relu(y)
y = self.decode_2(y)
return y, z_mu, z_lsgms
# a deterministic linear output (update: add noise)
class MLPVAEConditionalPlain(nn.Module):
def __init__(self, h_size, embedding_size, y_size, device='cpu'):
super(MLPVAEConditionalPlain, self).__init__()
self.device = device
self.encode_11 = nn.Linear(h_size, embedding_size) # mu
self.encode_12 = nn.Linear(h_size, embedding_size) # lsgms
self.decode_1 = nn.Linear(embedding_size + h_size, embedding_size)
self.decode_2 = nn.Linear(embedding_size, y_size) # make edge prediction (reconstruct)
self.relu = nn.ReLU()
for m in self.modules():
if isinstance(m, nn.Linear):
m.weight.data = init.xavier_uniform_(m.weight.data, gain=nn.init.calculate_gain('relu'))
def forward(self, h):
# encoder
z_mu = self.encode_11(h)
z_lsgms = self.encode_12(h)
# reparameterize
z_sgm = z_lsgms.mul(0.5).exp_()
eps = Variable(torch.randn(z_sgm.size(0), z_sgm.size(1), z_sgm.size(2))).to(self.device)
# eps = Variable(torch.randn(z_sgm.size(0), z_sgm.size(1), z_sgm.size(2))).cuda()
z = eps * z_sgm + z_mu
# decoder
y = self.decode_1(torch.cat((h, z), dim=2))
y = self.relu(y)
y = self.decode_2(y)
return y, z_mu, z_lsgms
# baseline model 1: Learning deep generative model of graphs
class DGMGraphs(nn.Module):
def __init__(self, h_size):
# h_size: node embedding size
# h_size*2: graph embedding size
super(DGMGraphs, self).__init__()
# all modules used by the model
# 1 message passing, 2 times
self.m_uv_1 = nn.Linear(h_size * 2, h_size * 2)
self.f_n_1 = nn.GRUCell(h_size * 2, h_size) # input_size, hidden_size
self.m_uv_2 = nn.Linear(h_size * 2, h_size * 2)
self.f_n_2 = nn.GRUCell(h_size * 2, h_size) # input_size, hidden_size
# 2 graph embedding and new node embedding
# for graph embedding
self.f_m = nn.Linear(h_size, h_size * 2)
self.f_gate = nn.Sequential(
nn.Linear(h_size, 1),
nn.Sigmoid()
)
# for new node embedding
self.f_m_init = nn.Linear(h_size, h_size * 2)
self.f_gate_init = nn.Sequential(
nn.Linear(h_size, 1),
nn.Sigmoid()
)
self.f_init = nn.Linear(h_size * 2, h_size)
# 3 f_addnode
self.f_an = nn.Sequential(
nn.Linear(h_size * 2, 1),
nn.Sigmoid()
)
# 4 f_addedge
self.f_ae = nn.Sequential(
nn.Linear(h_size * 2, 1),
nn.Sigmoid()
)
# 5 f_nodes
self.f_s = nn.Linear(h_size * 2, 1)
def message_passing(node_neighbor, node_embedding, model, device='cpu'):
node_embedding_new = []
for i in range(len(node_neighbor)):
neighbor_num = len(node_neighbor[i])
if neighbor_num > 0:
node_self = node_embedding[i].expand(neighbor_num, node_embedding[i].size(1))
node_self_neighbor = torch.cat([node_embedding[j] for j in node_neighbor[i]], dim=0)
message = torch.sum(model.m_uv_1(torch.cat((node_self, node_self_neighbor), dim=1)), dim=0, keepdim=True)
node_embedding_new.append(model.f_n_1(message, node_embedding[i]))
else:
message_null = Variable(torch.zeros((node_embedding[i].size(0), node_embedding[i].size(1) * 2))).to(device)
# message_null = Variable(torch.zeros((node_embedding[i].size(0), node_embedding[i].size(1) * 2))).cuda()
node_embedding_new.append(model.f_n_1(message_null, node_embedding[i]))
node_embedding = node_embedding_new
node_embedding_new = []
for i in range(len(node_neighbor)):
neighbor_num = len(node_neighbor[i])
if neighbor_num > 0:
node_self = node_embedding[i].expand(neighbor_num, node_embedding[i].size(1))
node_self_neighbor = torch.cat([node_embedding[j] for j in node_neighbor[i]], dim=0)
message = torch.sum(model.m_uv_1(torch.cat((node_self, node_self_neighbor), dim=1)), dim=0, keepdim=True)
node_embedding_new.append(model.f_n_1(message, node_embedding[i]))
else:
message_null = Variable(torch.zeros((node_embedding[i].size(0), node_embedding[i].size(1) * 2))).to(device)
# message_null = Variable(torch.zeros((node_embedding[i].size(0), node_embedding[i].size(1) * 2))).cuda()
node_embedding_new.append(model.f_n_1(message_null, node_embedding[i]))
return node_embedding_new
def calc_graph_embedding(node_embedding_cat, model):
node_embedding_graph = model.f_m(node_embedding_cat)
node_embedding_graph_gate = model.f_gate(node_embedding_cat)
graph_embedding = torch.sum(torch.mul(node_embedding_graph, node_embedding_graph_gate), dim=0, keepdim=True)
return graph_embedding
def calc_init_embedding(node_embedding_cat, model):
node_embedding_init = model.f_m_init(node_embedding_cat)
node_embedding_init_gate = model.f_gate_init(node_embedding_cat)
init_embedding = torch.sum(torch.mul(node_embedding_init, node_embedding_init_gate), dim=0, keepdim=True)
init_embedding = model.f_init(init_embedding)
return init_embedding
# code that is NOT used for final version
# RNN that updates according to graph structure, new proposed model
class GraphRNNStructure(nn.Module):
def __init__(self, hidden_size, batch_size, output_size, num_layers, is_dilation=True, is_bn=True, device='cpu'):
super(GraphRNNStructure, self).__init__()
# model configuration
self.device = device
self.hidden_size = hidden_size
self.batch_size = batch_size
self.output_size = output_size
self.num_layers = num_layers # num_layers of cnn_output
self.is_bn = is_bn
# model
self.relu = nn.ReLU()
# self.linear_output = nn.Linear(hidden_size, 1)
# self.linear_output_simple = nn.Linear(hidden_size, output_size)
# for state transition use only, input is null
# self.gru = nn.GRU(input_size=1, hidden_size=hidden_size, num_layers=num_layers, batch_first=True)
# use CNN to produce output prediction
# self.cnn_output = nn.Sequential(
# nn.Conv1d(hidden_size, hidden_size, kernel_size=3, dilation=1, padding=1),
# # nn.BatchNorm1d(hidden_size),
# nn.ReLU(),
# nn.Conv1d(hidden_size, 1, kernel_size=3, dilation=1, padding=1)
# )
if is_dilation:
self.conv_block = nn.ModuleList([nn.Conv1d(hidden_size, hidden_size, kernel_size=3, dilation=2 ** i, padding=2 ** i)
for i in range(num_layers - 1)])
else:
self.conv_block = nn.ModuleList([nn.Conv1d(hidden_size, hidden_size, kernel_size=3, dilation=1, padding=1)
for i in range(num_layers - 1)])
self.bn_block = nn.ModuleList([nn.BatchNorm1d(hidden_size) for i in range(num_layers - 1)])
self.conv_out = nn.Conv1d(hidden_size, 1, kernel_size=3, dilation=1, padding=1)
# use CNN to do state transition
# self.cnn_transition = nn.Sequential(
# nn.Conv1d(hidden_size, hidden_size, kernel_size=3, dilation=1, padding=1),
# # nn.BatchNorm1d(hidden_size),
# nn.ReLU(),
# nn.Conv1d(hidden_size, hidden_size, kernel_size=3, dilation=1, padding=1)
# )
# use linear to do transition, same as GCN mean aggregator
self.linear_transition = nn.Sequential(
nn.Linear(hidden_size, hidden_size),
nn.ReLU()
)
# GRU based output, output a single edge prediction at a time
# self.gru_output = nn.GRU(input_size=1, hidden_size=hidden_size, num_layers=num_layers, batch_first=True)
# use a list to keep all generated hidden vectors, each hidden has size batch*hidden_dim*1, and the list size is expanding
# when using convolution to compute attention weight,
# we need to first concat the list into a pytorch variable: batch*hidden_dim*current_num_nodes
self.hidden_all = []
# initialize
for m in self.modules():
if isinstance(m, nn.Linear):
# print('linear')
m.weight.data = init.xavier_uniform_(m.weight.data, gain=nn.init.calculate_gain('relu'))
# print(m.weight.data.size())
if isinstance(m, nn.Conv1d):
# print('conv1d')
m.weight.data = init.xavier_uniform_(m.weight.data, gain=nn.init.calculate_gain('relu'))
# print(m.weight.data.size())
if isinstance(m, nn.BatchNorm1d):
# print('batchnorm1d')
m.weight.data.fill_(1)
m.bias.data.zero_()
# print(m.weight.data.size())
if isinstance(m, nn.GRU):
# print('gru')
m.weight_ih_l0.data = init.xavier_uniform_(m.weight_ih_l0.data, gain=nn.init.calculate_gain('sigmoid'))
m.weight_hh_l0.data = init.xavier_uniform_(m.weight_hh_l0.data, gain=nn.init.calculate_gain('sigmoid'))
m.bias_ih_l0.data = torch.ones(m.bias_ih_l0.data.size(0)) * 0.25
m.bias_hh_l0.data = torch.ones(m.bias_hh_l0.data.size(0)) * 0.25
def init_hidden(self, len=None):
if len is None:
return Variable(torch.ones(self.batch_size, self.hidden_size, 1)).to(self.device)
# return Variable(torch.ones(self.batch_size, self.hidden_size, 1)).cuda()
else:
hidden_list = []
for i in range(len):
hidden_list.append(Variable(torch.ones(self.batch_size, self.hidden_size, 1)).to(self.device))
# hidden_list.append(Variable(torch.ones(self.batch_size, self.hidden_size, 1)).cuda())
return hidden_list
# only run a single forward step
def forward(self, x, teacher_forcing, temperature=0.5, bptt=True, bptt_len=20, flexible=True, max_prev_node=100):
# x: batch*1*self.output_size, the ground truth
# todo: current only look back to self.output_size nodes, try to look back according to bfs sequence
# 1 first compute new state
# print('hidden_all', self.hidden_all[-1*self.output_size:])
# hidden_all_cat = torch.cat(self.hidden_all[-1*self.output_size:], dim=2)
# # # add BPTT, detach the first variable
# if bptt:
# self.hidden_all[0] = Variable(self.hidden_all[0].data).cuda()
hidden_all_cat = torch.cat(self.hidden_all, dim=2)
# print(hidden_all_cat.size())
# print('hidden_all_cat',hidden_all_cat.size())
# att_weight size: batch*1*current_num_nodes
for i in range(self.num_layers - 1):
hidden_all_cat = self.conv_block[i](hidden_all_cat)
if self.is_bn:
hidden_all_cat = self.bn_block[i](hidden_all_cat)
hidden_all_cat = self.relu(hidden_all_cat)
x_pred = self.conv_out(hidden_all_cat)
# 2 then compute output, using a gru
# first try the simple version, directly give the edge prediction
# x_pred = self.linear_output_simple(hidden_new)
# x_pred = x_pred.view(x_pred.size(0),1,x_pred.size(1))
# todo: use a gru version output
# if sample==False:
# # when training: we know the ground truth, input the sequence at once
# y_pred,_ = self.gru_output(x, hidden_new.permute(2,0,1))
# y_pred = self.linear_output(y_pred)
# else:
# # when validating, we need to sampling at each time step
# y_pred = Variable(torch.zeros(x.size(0), x.size(1), x.size(2))).cuda()
# y_pred_long = Variable(torch.zeros(x.size(0), x.size(1), x.size(2))).cuda()
# y_pred = y_pred.cuda()
# y_pred_long = y_pred_long.cuda()
# x_step = x[:, 0:1, :]
# for i in range(x.size(1)):
# y_step,_ = self.gru_output(x_step)
# y_step = self.linear_output(y_step)
# y_pred[:, i, :] = y_step
# y_step = torch.sigmoid(y_step)
# x_step = sample(y_step, sample=True, thres=0.45)
# y_pred_long[:, i, :] = x_step
# pass
# 3 then update self.hidden_all list
# i.e., model will use ground truth to update new node
# x_pred_sample = gumbel_sigmoid(x_pred, temperature=temperature)
x_pred_sample = sample_tensor(torch.sigmoid(x_pred), sample=True, device=self.device)
thres = 0.5
x_thres = Variable(torch.ones(x_pred_sample.size(0), x_pred_sample.size(1), x_pred_sample.size(2)) * thres).to(self.device)
# x_thres = Variable(torch.ones(x_pred_sample.size(0), x_pred_sample.size(1), x_pred_sample.size(2)) * thres).cuda()
x_pred_sample_long = torch.gt(x_pred_sample, x_thres).long()
if teacher_forcing:
# first mask previous hidden states
hidden_all_cat_select = hidden_all_cat * x
x_sum = torch.sum(x, dim=2, keepdim=True).float()
# i.e., the model will use its own prediction to attend
else:
# first mask previous hidden states
hidden_all_cat_select = hidden_all_cat * x_pred_sample
x_sum = torch.sum(x_pred_sample_long, dim=2, keepdim=True).float()
# update hidden vector for new nodes
hidden_new = torch.sum(hidden_all_cat_select, dim=2, keepdim=True) / x_sum
hidden_new = self.linear_transition(hidden_new.permute(0, 2, 1))
hidden_new = hidden_new.permute(0, 2, 1)
if flexible:
# use ground truth to maintain history state
if teacher_forcing:
x_id = torch.min(torch.nonzero(torch.squeeze(x.data)))
self.hidden_all = self.hidden_all[x_id:]
# use prediction to maintain history state
else:
x_id = torch.min(torch.nonzero(torch.squeeze(x_pred_sample_long.data)))
start = max(len(self.hidden_all) - max_prev_node + 1, x_id)
self.hidden_all = self.hidden_all[start:]
# maintain a fixed size history state
else:
# self.hidden_all.pop(0)
self.hidden_all = self.hidden_all[1:]
self.hidden_all.append(hidden_new)
# 4 return prediction
# print('x_pred',x_pred)
# print('x_pred_mean', torch.mean(x_pred))
# print('x_pred_sample_mean', torch.mean(x_pred_sample))
return x_pred, x_pred_sample
# batch_size = 8
# output_size = 4
# generator = Graph_RNN_structure(hidden_size=16, batch_size=batch_size, output_size=output_size, num_layers=1).cuda()
# for i in range(4):
# generator.hidden_all.append(generator.init_hidden())
#
# x = Variable(torch.rand(batch_size,1,output_size)).cuda()
# x_pred = generator(x,teacher_forcing=True, sample=True)
# print(x_pred)
# current baseline model, generating a graph by LSTM
class GraphGeneratorLSTM(nn.Module):
def __init__(self, feature_size, input_size, hidden_size, output_size, batch_size, num_layers, device='cpu'):
super(GraphGeneratorLSTM, self).__init__()
self.device = device
self.batch_size = batch_size
self.num_layers = num_layers
self.hidden_size = hidden_size
self.lstm = nn.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, batch_first=True)
self.linear_input = nn.Linear(feature_size, input_size)
self.linear_output = nn.Linear(hidden_size, output_size)
self.relu = nn.ReLU()
# initialize
# self.hidden,self.cell = self.init_hidden()
self.hidden = self.init_hidden()
self.lstm.weight_ih_l0.data = init.xavier_uniform_(self.lstm.weight_ih_l0.data, gain=nn.init.calculate_gain('sigmoid'))
self.lstm.weight_hh_l0.data = init.xavier_uniform_(self.lstm.weight_hh_l0.data, gain=nn.init.calculate_gain('sigmoid'))
self.lstm.bias_ih_l0.data = torch.ones(self.lstm.bias_ih_l0.data.size(0)) * 0.25
self.lstm.bias_hh_l0.data = torch.ones(self.lstm.bias_hh_l0.data.size(0)) * 0.25
for m in self.modules():
if isinstance(m, nn.Linear):
m.weight.data = init.xavier_uniform_(m.weight.data, gain=nn.init.calculate_gain('relu'))
def init_hidden(self):
return (Variable(torch.zeros(self.num_layers, self.batch_size, self.hidden_size)).to(self.device),
Variable(torch.zeros(self.num_layers, self.batch_size, self.hidden_size)).to(self.device))
# return (Variable(torch.zeros(self.num_layers, self.batch_size, self.hidden_size)).cuda(),
# Variable(torch.zeros(self.num_layers, self.batch_size, self.hidden_size)).cuda())
def forward(self, input_raw, pack=False, len=None):
input = self.linear_input(input_raw)
input = self.relu(input)
if pack:
input = pack_padded_sequence(input, len, batch_first=True)
# output_raw[i, t]: hidden RNN embedding of the t-th time step of the **last** RNN layer of example i
# self.hidden[k, i]: hidden RNN embedding of the last time step of the k-th RNN layer of example i
# output_raw[i, input_len[i]-1] == self.hidden[-1, i]
output_raw, self.hidden = self.lstm(input, self.hidden)
if pack:
output_raw = pad_packed_sequence(output_raw, batch_first=True)[0]
output = self.linear_output(output_raw)
return output
# a simple MLP generator output
class GraphGeneratorLSTMOutputGenerator(nn.Module):
def __init__(self, h_size, n_size, y_size):
super(GraphGeneratorLSTMOutputGenerator, self).__init__()
# one layer MLP
self.generator_output = nn.Sequential(
nn.Linear(h_size + n_size, 64),
nn.ReLU(),
nn.Linear(64, y_size),
nn.Sigmoid()
)
def forward(self, h, n, temperature):
y_cat = torch.cat((h, n), dim=2)
y = self.generator_output(y_cat)
# y = gumbel_sigmoid(y,temperature=temperature)
return y
# a simple MLP discriminator
class GraphGeneratorLSTMOutputDiscriminator(nn.Module):
def __init__(self, h_size, y_size):
super(GraphGeneratorLSTMOutputDiscriminator, self).__init__()
# one layer MLP
self.discriminator_output = nn.Sequential(
nn.Linear(h_size + y_size, 64),
nn.ReLU(),
nn.Linear(64, 1),
nn.Sigmoid()
)
def forward(self, h, y):
y_cat = torch.cat((h, y), dim=2)
l = self.discriminator_output(y_cat)
return l
# GCN basic operation
class GraphConv(nn.Module):
def __init__(self, input_dim, output_dim, device='cpu'):
super(GraphConv, self).__init__()
self.input_dim = input_dim
self.output_dim = output_dim
self.weight = nn.Parameter(torch.FloatTensor(input_dim, output_dim).to(device))
# self.weight = nn.Parameter(torch.FloatTensor(input_dim, output_dim).cuda())
# self.relu = nn.ReLU()
def forward(self, x, adj):
y = torch.matmul(adj, x)
y = torch.matmul(y, self.weight)
return y
# vanilla GCN encoder
class GCNEncoder(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim, device='cpu'):
super(GCNEncoder, self).__init__()
self.device = device
self.conv1 = GraphConv(input_dim=input_dim, output_dim=hidden_dim, device=device)
self.conv2 = GraphConv(input_dim=hidden_dim, output_dim=output_dim, device=device)
# self.bn1 = nn.BatchNorm1d(output_dim)
# self.bn2 = nn.BatchNorm1d(output_dim)
self.relu = nn.ReLU()
for m in self.modules():