-
Notifications
You must be signed in to change notification settings - Fork 3
/
models.py
1579 lines (1367 loc) · 89 KB
/
models.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
#!/usr/bin/python3
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
import collections
from tqdm import tqdm
from type_aggregator import EntityTypeAggregator, RelationTypeAggregator, Match
pi = 3.14159265358979323846
eps = 1e-6
query_name_dict = {('e',('r',)): '1p',
('e', ('r', 'r')): '2p',
('e', ('r', 'r', 'r')): '3p',
('e', ('r', 'r', 'r', 'r')): '4p',
('e', ('r', 'r', 'r', 'r', 'r')): '5p',
(('e', ('r',)), ('e', ('r',))): '2i',
(('e', ('r',)), ('e', ('r',)), ('e', ('r',))): '3i',
((('e', ('r',)), ('e', ('r',))), ('r',)): 'ip',
(('e', ('r', 'r')), ('e', ('r',))): 'pi',
(('e', ('r',)), ('e', ('r', 'n'))): '2in',
(('e', ('r',)), ('e', ('r',)), ('e', ('r', 'n'))): '3in',
((('e', ('r',)), ('e', ('r', 'n'))), ('r',)): 'inp',
(('e', ('r', 'r')), ('e', ('r', 'n'))): 'pin',
(('e', ('r', 'r', 'n')), ('e', ('r',))): 'pni',
(('e', ('r',)), ('e', ('r',)), ('u',)): '2u-DNF',
((('e', ('r',)), ('e', ('r',)), ('u',)), ('r',)): 'up-DNF',
((('e', ('r', 'n')), ('e', ('r', 'n'))), ('n',)): '2u-DM',
((('e', ('r', 'n')), ('e', ('r', 'n'))), ('n', 'r')): 'up-DM'
}
def Identity(x):
return x
class BoxOffsetIntersection(nn.Module):
def __init__(self, dim):
super(BoxOffsetIntersection, self).__init__()
self.dim = dim
self.layer1 = nn.Linear(self.dim, self.dim)
self.layer2 = nn.Linear(self.dim, self.dim)
nn.init.xavier_uniform_(self.layer1.weight)
nn.init.xavier_uniform_(self.layer2.weight)
def forward(self, embeddings):
layer1_act = F.relu(self.layer1(embeddings))
layer1_mean = torch.mean(layer1_act, dim=0)
gate = torch.sigmoid(self.layer2(layer1_mean))
offset, _ = torch.min(embeddings, dim=0)
return offset * gate
class CenterIntersection(nn.Module):
def __init__(self, dim):
super(CenterIntersection, self).__init__()
self.dim = dim
self.layer1 = nn.Linear(self.dim, self.dim)
self.layer2 = nn.Linear(self.dim, self.dim)
nn.init.xavier_uniform_(self.layer1.weight)
nn.init.xavier_uniform_(self.layer2.weight)
def forward(self, embeddings):
layer1_act = F.relu(self.layer1(embeddings)) # (num_conj, dim)
attention = F.softmax(self.layer2(layer1_act), dim=0) # (num_conj, dim)
embedding = torch.sum(attention * embeddings, dim=0)
return embedding
class BetaIntersection(nn.Module):
def __init__(self, dim):
super(BetaIntersection, self).__init__()
self.dim = dim
self.layer1 = nn.Linear(2 * self.dim, 2 * self.dim)
self.layer2 = nn.Linear(2 * self.dim, self.dim)
nn.init.xavier_uniform_(self.layer1.weight)
nn.init.xavier_uniform_(self.layer2.weight)
def forward(self, alpha_embeddings, beta_embeddings):
all_embeddings = torch.cat([alpha_embeddings, beta_embeddings], dim=-1)
layer1_act = F.relu(self.layer1(all_embeddings)) # (num_conj, batch_size, 2 * dim)
attention = F.softmax(self.layer2(layer1_act), dim=0) # (num_conj, batch_size, dim)
alpha_embedding = torch.sum(attention * alpha_embeddings, dim=0)
beta_embedding = torch.sum(attention * beta_embeddings, dim=0)
return alpha_embedding, beta_embedding
class BetaProjection(nn.Module):
def __init__(self, entity_dim, relation_dim, hidden_dim, projection_regularizer, num_layers, with_regular=True):
super(BetaProjection, self).__init__()
self.entity_dim = entity_dim
self.relation_dim = relation_dim
self.hidden_dim = hidden_dim
self.num_layers = num_layers
self.layer1 = nn.Linear(self.entity_dim + self.relation_dim, self.hidden_dim) # 1st layer
self.layer0 = nn.Linear(self.hidden_dim, self.entity_dim) # final layer
for nl in range(2, num_layers + 1):
setattr(self, "layer{}".format(nl), nn.Linear(self.hidden_dim, self.hidden_dim))
for nl in range(num_layers + 1):
nn.init.xavier_uniform_(getattr(self, "layer{}".format(nl)).weight)
self.projection_regularizer = projection_regularizer
self.with_regular = with_regular
def forward(self, e_embedding, r_embedding):
x = torch.cat([e_embedding, r_embedding], dim=-1)
for nl in range(1, self.num_layers + 1):
x = F.relu(getattr(self, "layer{}".format(nl))(x))
x = self.layer0(x)
x = self.projection_regularizer(x)
if self.with_regular == True:
x = self.projection_regularizer(x)
return x
class Regularizer():
def __init__(self, base_add, min_val, max_val):
self.base_add = base_add
self.min_val = min_val
self.max_val = max_val
def __call__(self, entity_embedding):
return torch.clamp(entity_embedding + self.base_add, self.min_val, self.max_val)
def convert_to_arg(x):
y = torch.tanh(2 * x) * pi / 2 + pi / 2
return y
def convert_to_axis(x):
y = torch.tanh(x) * pi
return y
class AngleScale:
def __init__(self, embedding_range):
self.embedding_range = embedding_range
def __call__(self, axis_embedding, scale=None):
if scale is None:
scale = pi
return axis_embedding / self.embedding_range * scale
class ConeProjection(nn.Module):
def __init__(self, dim, hidden_dim, num_layers, with_regular=True):
super(ConeProjection, self).__init__()
self.entity_dim = dim
self.relation_dim = dim
self.hidden_dim = hidden_dim
self.num_layers = num_layers
self.layer1 = nn.Linear(self.entity_dim + self.relation_dim, self.hidden_dim)
self.layer0 = nn.Linear(self.hidden_dim, self.entity_dim + self.relation_dim)
self.with_regular = with_regular
for nl in range(2, num_layers + 1):
setattr(self, "layer{}".format(nl), nn.Linear(self.hidden_dim, self.hidden_dim))
for nl in range(num_layers + 1):
nn.init.xavier_uniform_(getattr(self, "layer{}".format(nl)).weight)
def forward(self, source_embedding_axis, source_embedding_arg, r_embedding_axis, r_embedding_arg):
x = torch.cat([source_embedding_axis + r_embedding_axis, source_embedding_arg + r_embedding_arg], dim=-1)
for nl in range(1, self.num_layers + 1):
x = F.relu(getattr(self, "layer{}".format(nl))(x))
x = self.layer0(x)
axis, arg = torch.chunk(x, 2, dim=-1)
if self.with_regular:
axis_embeddings = convert_to_axis(axis)
arg_embeddings = convert_to_arg(arg)
else:
axis_embeddings = axis
arg_embeddings = arg
return axis_embeddings, arg_embeddings
class ConeIntersection(nn.Module):
def __init__(self, dim, drop):
super(ConeIntersection, self).__init__()
self.dim = dim
self.layer_axis1 = nn.Linear(self.dim * 2, self.dim)
self.layer_arg1 = nn.Linear(self.dim * 2, self.dim)
self.layer_axis2 = nn.Linear(self.dim, self.dim)
self.layer_arg2 = nn.Linear(self.dim, self.dim)
nn.init.xavier_uniform_(self.layer_axis1.weight)
nn.init.xavier_uniform_(self.layer_arg1.weight)
nn.init.xavier_uniform_(self.layer_axis2.weight)
nn.init.xavier_uniform_(self.layer_arg2.weight)
self.drop = nn.Dropout(p=drop)
def forward(self, axis_embeddings, arg_embeddings):
logits = torch.cat([axis_embeddings - arg_embeddings, axis_embeddings + arg_embeddings], dim=-1)
axis_layer1_act = F.relu(self.layer_axis1(logits))
axis_attention = F.softmax(self.layer_axis2(axis_layer1_act), dim=0)
x_embeddings = torch.cos(axis_embeddings)
y_embeddings = torch.sin(axis_embeddings)
x_embeddings = torch.sum(axis_attention * x_embeddings, dim=0)
y_embeddings = torch.sum(axis_attention * y_embeddings, dim=0)
# when x_embeddings are very closed to zero, the tangent may be nan
# no need to consider the sign of x_embeddings
x_embeddings[torch.abs(x_embeddings) < 1e-3] = 1e-3
axis_embeddings = torch.atan(y_embeddings / x_embeddings)
indicator_x = x_embeddings < 0
indicator_y = y_embeddings < 0
indicator_two = indicator_x & torch.logical_not(indicator_y)
indicator_three = indicator_x & indicator_y
axis_embeddings[indicator_two] = axis_embeddings[indicator_two] + pi
axis_embeddings[indicator_three] = axis_embeddings[indicator_three] - pi
# DeepSets
arg_layer1_act = F.relu(self.layer_arg1(logits))
arg_layer1_mean = torch.mean(arg_layer1_act, dim=0)
gate = torch.sigmoid(self.layer_arg2(arg_layer1_mean))
arg_embeddings = self.drop(arg_embeddings)
arg_embeddings, _ = torch.min(arg_embeddings, dim=0)
arg_embeddings = arg_embeddings * gate
return axis_embeddings, arg_embeddings
class ConeNegation(nn.Module):
def __init__(self):
super(ConeNegation, self).__init__()
def forward(self, axis_embedding, arg_embedding):
indicator_positive = axis_embedding >= 0
indicator_negative = axis_embedding < 0
axis_embedding[indicator_positive] = axis_embedding[indicator_positive] - pi
axis_embedding[indicator_negative] = axis_embedding[indicator_negative] + pi
arg_embedding = pi - arg_embedding
return axis_embedding, arg_embedding
def order_bounds(embedding): # ensure lower < upper truth bound for logic embedding
embedding = torch.clamp(embedding, 0, 1)
lower, upper = torch.chunk(embedding, 2, dim=-1)
contra = lower > upper
if contra.any(): # contradiction
mean = (lower + upper) / 2
lower = torch.where(lower > upper, mean, lower)
upper = torch.where(lower > upper, mean, upper)
ordered_embedding = torch.cat([lower, upper], dim=-1)
return ordered_embedding
def valclamp(x, a=1, b=6, lo=0, hi=1): # relu1 with gradient-transparent clamp on negative
elu_neg = a * (torch.exp(b * x) - 1)
return ((x < lo).float() * (lo + elu_neg - elu_neg.detach()) +
(lo <= x).float() * (x <= hi).float() * x +
(hi < x).float())
class LogicIntersection(nn.Module):
def __init__(self, dim, tnorm, bounded, use_att, use_gtrans):
super(LogicIntersection, self).__init__()
self.dim = dim
self.tnorm = tnorm
self.bounded = bounded
self.use_att = use_att
self.use_gtrans = use_gtrans # gradient transparency
if use_att: # use attention with weighted t-norm
self.layer1 = nn.Linear(2 * self.dim, 2 * self.dim)
if bounded:
self.layer2 = nn.Linear(2 * self.dim, self.dim) # same weight for bound pair
else:
self.layer2 = nn.Linear(2 * self.dim, 2 * self.dim)
nn.init.xavier_uniform_(self.layer1.weight)
nn.init.xavier_uniform_(self.layer2.weight)
def forward(self, embeddings):
if self.use_att: # use attention with weighted t-norm
layer1_act = F.relu(self.layer1(embeddings)) # (num_conj, batch_size, 2 * dim)
attention = F.softmax(self.layer2(layer1_act), dim=0) # (num_conj, batch_size, dim)
attention = attention / torch.max(attention, dim=0, keepdim=True).values
if self.bounded: # same weight for bound pair
attention = torch.cat([attention, attention], dim=-1)
if self.tnorm == 'mins': # minimum / Godel t-norm
smooth_param = -10 # smooth minimum
min_weights = attention * torch.exp(smooth_param * embeddings)
embedding = torch.sum(min_weights * embeddings, dim=0) / torch.sum(min_weights, dim=0)
if self.bounded:
embedding = order_bounds(embedding)
elif self.tnorm == 'luk': # Lukasiewicz t-norm
embedding = 1 - torch.sum(attention * (1 - embeddings), dim=0)
if self.use_gtrans:
embedding = valclamp(embedding, b=6. / embedding.shape[0])
else:
embedding = torch.clamp(embedding, 0, 1)
elif self.tnorm == 'prod': # product t-norm
embedding = torch.prod(torch.pow(torch.clamp(embeddings, 0, 1) + eps, attention), dim=0)
else: # no attention
if self.tnorm == 'mins': # minimum / Godel t-norm
smooth_param = -10 # smooth minimum
min_weights = torch.exp(smooth_param * embeddings)
embedding = torch.sum(min_weights * embeddings, dim=0) / torch.sum(min_weights, dim=0)
if self.bounded:
embedding = order_bounds(embedding)
elif self.tnorm == 'luk': # Lukasiewicz t-norm
embedding = 1 - torch.sum(1 - embeddings, dim=0)
if self.use_gtrans:
embedding = valclamp(embedding, b=6. / embedding.shape[0])
else:
embedding = torch.clamp(embedding, 0, 1)
elif self.tnorm == 'prod': # product t-norm
embedding = torch.prod(embeddings, dim=0)
return embedding
class LogicProjection(nn.Module):
def __init__(self, entity_dim, relation_dim, hidden_dim, num_layers, bounded, with_sigmoid=False):
super(LogicProjection, self).__init__()
self.entity_dim = entity_dim
self.relation_dim = relation_dim
self.hidden_dim = hidden_dim
self.num_layers = num_layers
self.bounded = bounded
self.layer1 = nn.Linear(self.entity_dim + self.relation_dim, self.hidden_dim) # 1st layer
self.layer0 = nn.Linear(self.hidden_dim, self.entity_dim) # final layer
self.with_sigmoid = with_sigmoid
for nl in range(2, num_layers + 1):
setattr(self, "layer{}".format(nl), nn.Linear(self.hidden_dim, self.hidden_dim))
for nl in range(num_layers + 1):
nn.init.xavier_uniform_(getattr(self, "layer{}".format(nl)).weight)
def forward(self, e_embedding, r_embedding):
x = torch.cat([e_embedding, r_embedding], dim=-1)
for nl in range(1, self.num_layers + 1):
x = F.relu(getattr(self, "layer{}".format(nl))(x))
x = self.layer0(x)
if self.with_sigmoid:
x = torch.sigmoid(x)
if self.bounded:
lower, upper = torch.chunk(x, 2, dim=-1)
upper = lower + upper * (1 - lower)
x = torch.cat([lower, upper], dim=-1)
return x
class SizePredict(nn.Module):
def __init__(self, entity_dim):
super(SizePredict, self).__init__()
self.layer2 = nn.Linear(entity_dim, entity_dim // 4)
self.layer1 = nn.Linear(entity_dim // 4, entity_dim // 16)
self.layer0 = nn.Linear(entity_dim // 16, 1)
nn.init.xavier_uniform_(self.layer2.weight)
nn.init.xavier_uniform_(self.layer1.weight)
nn.init.xavier_uniform_(self.layer0.weight)
def forward(self, entropy_embedding):
x = self.layer2(entropy_embedding)
x = F.relu(x)
x = self.layer1(x)
x = F.relu(x)
x = self.layer0(x)
x = torch.sigmoid(x)
return x.squeeze()
class KGReasoning(nn.Module):
def __init__(self, nentity, nrelation, ntype, hidden_dim, entity2type, relation2type, gamma,
geo, test_batch_size=1,
box_mode=None, use_cuda=False,
query_name_dict=None, beta_mode=None, center_reg=None, logic_mode=None, model_mode='baseline', drop=0., neighbor_ent_type_samples=32):
super(KGReasoning, self).__init__()
self.nentity = nentity
self.nrelation = nrelation
self.ntype = ntype
self.hidden_dim = hidden_dim
self.epsilon = 2.0
self.geo = geo
self.use_cuda = use_cuda
self.batch_entity_range = torch.arange(nentity).to(torch.float).repeat(test_batch_size, 1).cuda() if self.use_cuda else torch.arange(nentity).to(torch.float).repeat(test_batch_size, 1) # used in test_step
self.query_name_dict = query_name_dict
self.entity2type = torch.tensor(entity2type).cuda()
self.relation2type = torch.tensor(relation2type).cuda()
self.neighbor_ent_type_samples = neighbor_ent_type_samples
if self.geo == 'vec' or self.geo == 'box' or self.geo == 'cone':
self.ent_neighbor_type_agg = EntityTypeAggregator(input_dim=hidden_dim, output_dim=hidden_dim, self_included=True, neighbor_ent_type_samples=self.neighbor_ent_type_samples)
elif self.geo == 'beta' or self.geo == 'logic':
self.ent_neighbor_type_agg = EntityTypeAggregator(input_dim=hidden_dim*2, output_dim=hidden_dim*2, self_included=True, neighbor_ent_type_samples=self.neighbor_ent_type_samples)
if self.geo == 'logic':
self.rel_neighbor_type_agg = RelationTypeAggregator(hidden_dim * 2)
else:
self.rel_neighbor_type_agg = RelationTypeAggregator(hidden_dim)
if self.geo == 'logic':
self.match = Match(hidden_dim * 2)
else:
self.match = Match(hidden_dim)
self.model_mode = model_mode
self.gamma = nn.Parameter(
torch.Tensor([gamma]),
requires_grad=False
)
self.embedding_range = nn.Parameter(
torch.Tensor([(self.gamma.item() + self.epsilon) / hidden_dim]),
requires_grad=False
)
self.entity_dim = hidden_dim
self.relation_dim = hidden_dim
self.type_dim = hidden_dim
self.cen = center_reg
if self.geo == 'box':
self.entity_embedding = nn.Parameter(torch.zeros(nentity, self.entity_dim)) # centor for entities
activation, cen = box_mode
self.cen = cen # hyperparameter that balances the in-box distance and the out-box distance
if activation == 'none':
self.func = Identity
elif activation == 'relu':
self.func = F.relu
elif activation == 'softplus':
self.func = F.softplus
elif self.geo == 'vec':
self.entity_embedding = nn.Parameter(torch.zeros(nentity, self.entity_dim)) # center for entities
elif self.geo == 'beta':
self.entity_embedding = nn.Parameter(torch.zeros(nentity, self.entity_dim * 2)) # alpha and beta
self.entity_regularizer = Regularizer(1, 0.05, 1e9) # make sure the parameters of beta embeddings are positive
self.projection_regularizer = Regularizer(1, 0.05, 1e9) # make sure the parameters of beta embeddings after relation projection are positive
elif self.geo == 'cone':
self.entity_embedding = nn.Parameter(torch.zeros(nentity, self.entity_dim), requires_grad=True) # axis for entities
self.angle_scale = AngleScale(self.embedding_range.item()) # scale axis embeddings to [-pi, pi]
self.modulus = nn.Parameter(torch.Tensor([0.5 * self.embedding_range.item()]), requires_grad=True)
self.axis_scale = 1.0
self.arg_scale = 1.0
elif self.geo == 'logic':
self.tnorm, self.bounded, use_att, use_gtrans, hidden_dim, num_layers = logic_mode
if self.bounded:
lower = torch.rand((nentity, self.entity_dim))
upper = lower + torch.rand((nentity, self.entity_dim)) * (1 - lower)
self.entity_embedding = nn.Parameter(torch.cat([lower, upper], dim=-1))
else:
self.entity_embedding = nn.Parameter(torch.rand((nentity, self.entity_dim * 2)))
if self.geo in ['box', 'vec', 'beta', 'cone']:
nn.init.uniform_(
tensor=self.entity_embedding,
a=-self.embedding_range.item(),
b=self.embedding_range.item()
)
if self.geo == 'beta' or self.geo == 'logic':
self.relation_embedding = nn.Parameter(torch.zeros(nrelation, self.relation_dim * 2))
else:
self.relation_embedding = nn.Parameter(torch.zeros(nrelation, self.relation_dim))
if self.geo in ['box', 'vec', 'beta', 'cone']:
nn.init.uniform_(
tensor=self.relation_embedding,
a=-self.embedding_range.item(),
b=self.embedding_range.item()
)
if self.geo == 'box':
self.offset_embedding = nn.Parameter(torch.zeros(nrelation, self.entity_dim))
nn.init.uniform_(
tensor=self.offset_embedding,
a=0.,
b=self.embedding_range.item()
)
self.center_net = CenterIntersection(self.entity_dim)
self.offset_net = BoxOffsetIntersection(self.entity_dim)
self.type_embedding = nn.Parameter(torch.zeros(self.ntype, self.type_dim))
nn.init.uniform_(
tensor=self.type_embedding,
a=-self.embedding_range.item(),
b=self.embedding_range.item()
)
elif self.geo == 'vec':
self.center_net = CenterIntersection(self.entity_dim)
self.type_embedding = nn.Parameter(torch.zeros(self.ntype, self.type_dim))
nn.init.uniform_(
tensor=self.type_embedding,
a=-self.embedding_range.item(),
b=self.embedding_range.item()
)
elif self.geo == 'beta':
hidden_dim, num_layers = beta_mode
self.center_net = BetaIntersection(self.entity_dim)
self.relation_center_net = CenterIntersection(self.relation_dim)
self.projection_net = BetaProjection(self.entity_dim * 2,
self.relation_dim * 2,
hidden_dim,
self.projection_regularizer,
num_layers)
self.projection_without_net = BetaProjection(self.entity_dim * 2,
self.relation_dim * 2,
hidden_dim,
self.projection_regularizer,
num_layers, with_regular=False)
self.type_embedding = nn.Parameter(torch.zeros(self.ntype, self.type_dim * 2))
nn.init.uniform_(
tensor=self.type_embedding,
a=-self.embedding_range.item(),
b=self.embedding_range.item()
)
elif self.geo == 'cone':
self.axis_embedding = nn.Parameter(torch.zeros(nrelation, self.relation_dim), requires_grad=True)
nn.init.uniform_(
tensor=self.axis_embedding,
a=-self.embedding_range.item(),
b=self.embedding_range.item()
)
self.arg_embedding = nn.Parameter(torch.zeros(nrelation, self.relation_dim), requires_grad=True)
nn.init.uniform_(
tensor=self.arg_embedding,
a=-self.embedding_range.item(),
b=self.embedding_range.item()
)
self.cone_proj = ConeProjection(self.entity_dim, 1600, 2)
self.cone_intersection = ConeIntersection(self.entity_dim, drop)
self.cone_negation = ConeNegation()
self.relation_center_net = CenterIntersection(self.entity_dim)
self.cone_without_proj = ConeProjection(self.entity_dim, 1600, 2, with_regular=False)
self.type_embedding = nn.Parameter(torch.zeros(self.ntype, self.type_dim), requires_grad=True)
nn.init.uniform_(
tensor=self.type_embedding,
a=-self.embedding_range.item(),
b=self.embedding_range.item()
)
elif self.geo == 'logic':
tnorm, bounded, use_att, use_gtrans, hidden_dim, num_layers = logic_mode
self.center_net = LogicIntersection(self.entity_dim, tnorm, bounded, use_att, use_gtrans)
self.relation_center_net = CenterIntersection(self.entity_dim * 2)
self.projection_net = LogicProjection(self.entity_dim * 2,
self.relation_dim * 2,
hidden_dim,
num_layers,
bounded, with_sigmoid=True)
self.projection_without_net = LogicProjection(self.entity_dim,
self.relation_dim,
hidden_dim,
num_layers,
bounded, with_sigmoid=False)
self.type_embedding = nn.Parameter(torch.rand(self.ntype, self.type_dim * 2))
def forward(self, positive_sample, negative_sample, subsampling_weight, batch_queries_dict, batch_idxs_dict):
if self.geo == 'box':
return self.forward_box(positive_sample, negative_sample, subsampling_weight, batch_queries_dict, batch_idxs_dict)
elif self.geo == 'vec':
return self.forward_vec(positive_sample, negative_sample, subsampling_weight, batch_queries_dict, batch_idxs_dict)
elif self.geo == 'beta':
return self.forward_beta(positive_sample, negative_sample, subsampling_weight, batch_queries_dict, batch_idxs_dict)
elif self.geo == 'cone':
return self.forward_cone(positive_sample, negative_sample, subsampling_weight, batch_queries_dict, batch_idxs_dict)
elif self.geo == 'logic':
return self.forward_logic(positive_sample, negative_sample, subsampling_weight, batch_queries_dict, batch_idxs_dict)
def embed_query_vec(self, queries, query_structure, idx):
'''
Iterative embed a batch of queries with same structure using GQE
queries: a flattened batch of queries
'''
all_relation_flag = True
for ele in query_structure[-1]: # whether the current query tree has merged to one branch and only need to do relation traversal, e.g., path queries or conjunctive queries after the intersection
if ele not in ['r', 'n']:
all_relation_flag = False
break
if all_relation_flag:
if query_structure[0] == 'e':
if self.model_mode == 'baseline':
embedding = torch.index_select(self.entity_embedding, dim=0, index=queries[:, idx])
elif self.model_mode == 'temp':
embedding = torch.index_select(self.entity_embedding, dim=0, index=queries[:, idx])
ent_type_id = torch.index_select(self.entity2type, dim=0, index=queries[:, idx])
entity_neighbor_type_embedding = torch.index_select(self.type_embedding, dim=0, index=ent_type_id.view(-1)).view(ent_type_id.shape[0], ent_type_id.shape[1], -1)
embedding = self.ent_neighbor_type_agg(embedding, entity_neighbor_type_embedding)
idx += 1
else:
embedding, idx = self.embed_query_vec(queries, query_structure[0], idx)
for i in range(len(query_structure[-1])):
if query_structure[-1][i] == 'n':
assert False, "vec cannot handle queries with negation"
else:
if self.model_mode == 'baseline':
r_embedding = torch.index_select(self.relation_embedding, dim=0, index=queries[:, idx])
embedding += r_embedding
elif self.model_mode == 'temp':
r_embedding = torch.index_select(self.relation_embedding, dim=0, index=queries[:, idx])
rel_type_id = torch.index_select(self.relation2type, dim=0, index=queries[:, idx])
relation_neighbor_type_embedding = torch.index_select(self.type_embedding, dim=0, index=rel_type_id.view(-1)).view(rel_type_id.shape[0], rel_type_id.shape[1], -1)
relation_neighbor_type_embedding = torch.transpose(relation_neighbor_type_embedding, 0, 1)
rel_type_cent = self.center_net(relation_neighbor_type_embedding)
embedding = embedding.unsqueeze(1)
r_embedding = r_embedding.unsqueeze(1)
rel_type_cent = rel_type_cent.unsqueeze(1)
ent_rel = self.match([embedding, r_embedding])
ent_rel_type = self.match([embedding, rel_type_cent])
rel_ent = self.match([r_embedding, embedding])
rel_rel_type = self.match([r_embedding, rel_type_cent])
embedding = self.rel_neighbor_type_agg([ent_rel.squeeze(1), ent_rel_type.squeeze(1)])
r_embedding = self.rel_neighbor_type_agg([rel_ent.squeeze(1), rel_rel_type.squeeze(1)])
embedding += r_embedding
idx += 1
else:
embedding_list = []
for i in range(len(query_structure)):
embedding, idx = self.embed_query_vec(queries, query_structure[i], idx)
embedding_list.append(embedding)
embedding = self.center_net(torch.stack(embedding_list))
return embedding, idx
def embed_query_box(self, queries, query_structure, idx):
'''
Iterative embed a batch of queries with same structure using Query2box
queries: a flattened batch of queries
'''
all_relation_flag = True
for ele in query_structure[-1]: # whether the current query tree has merged to one branch and only need to do relation traversal, e.g., path queries or conjunctive queries after the intersection
if ele not in ['r', 'n']:
all_relation_flag = False
break
if all_relation_flag:
if query_structure[0] == 'e':
if self.model_mode == 'baseline':
embedding = torch.index_select(self.entity_embedding, dim=0, index=queries[:, idx])
elif self.model_mode == 'temp':
embedding = torch.index_select(self.entity_embedding, dim=0, index=queries[:, idx])
ent_type_id = torch.index_select(self.entity2type, dim=0, index=queries[:, idx])
entity_neighbor_type_embedding = torch.index_select(self.type_embedding, dim=0, index=ent_type_id.view(-1)).view(ent_type_id.shape[0], ent_type_id.shape[1], -1)
embedding = self.ent_neighbor_type_agg(embedding, entity_neighbor_type_embedding)
if self.use_cuda:
offset_embedding = torch.zeros_like(embedding).cuda()
else:
offset_embedding = torch.zeros_like(embedding)
idx += 1
else:
embedding, offset_embedding, idx = self.embed_query_box(queries, query_structure[0], idx)
for i in range(len(query_structure[-1])):
if query_structure[-1][i] == 'n':
assert False, "box cannot handle queries with negation"
else:
if self.model_mode == 'baseline':
r_embedding = torch.index_select(self.relation_embedding, dim=0, index=queries[:, idx])
r_offset_embedding = torch.index_select(self.offset_embedding, dim=0, index=queries[:, idx])
embedding += r_embedding
offset_embedding += self.func(r_offset_embedding)
elif self.model_mode == 'temp':
r_embedding = torch.index_select(self.relation_embedding, dim=0, index=queries[:, idx])
r_offset_embedding = torch.index_select(self.offset_embedding, dim=0, index=queries[:, idx])
rel_type_id = torch.index_select(self.relation2type, dim=0, index=queries[:, idx])
relation_neighbor_type_embedding = torch.index_select(self.type_embedding, dim=0, index=rel_type_id.view(-1)).view(rel_type_id.shape[0], rel_type_id.shape[1], -1)
relation_neighbor_type_embedding = torch.transpose(relation_neighbor_type_embedding, 0, 1)
rel_type_cent = self.center_net(relation_neighbor_type_embedding)
embedding = embedding.unsqueeze(1)
r_embedding = r_embedding.unsqueeze(1)
rel_type_cent = rel_type_cent.unsqueeze(1)
ent_rel = self.match([embedding, r_embedding])
ent_rel_type = self.match([embedding, rel_type_cent])
rel_ent = self.match([r_embedding, embedding])
rel_rel_type = self.match([r_embedding, rel_type_cent])
embedding = self.rel_neighbor_type_agg([ent_rel.squeeze(1), ent_rel_type.squeeze(1)])
r_embedding = self.rel_neighbor_type_agg([rel_ent.squeeze(1), rel_rel_type.squeeze(1)])
embedding += r_embedding
offset_embedding += self.func(r_offset_embedding)
idx += 1
else:
embedding_list = []
offset_embedding_list = []
for i in range(len(query_structure)):
embedding, offset_embedding, idx = self.embed_query_box(queries, query_structure[i], idx)
embedding_list.append(embedding)
offset_embedding_list.append(offset_embedding)
embedding = self.center_net(torch.stack(embedding_list))
offset_embedding = self.offset_net(torch.stack(offset_embedding_list))
return embedding, offset_embedding, idx
def embed_query_beta(self, queries, query_structure, idx, filter_flag=False):
'''
Iterative embed a batch of queries with same structure using BetaE
queries: a flattened batch of queries
'''
all_relation_flag = True
if self.model_mode == 'temp':
if filter_flag == False:
if query_structure in query_name_dict and query_name_dict[query_structure] == 'ip':
filter_flag = True
for ele in query_structure[-1]: # whether the current query tree has merged to one branch and only need to do relation traversal, e.g., path queries or conjunctive queries after the intersection
if ele not in ['r', 'n']:
all_relation_flag = False
break
if all_relation_flag:
if query_structure[0] == 'e':
if self.model_mode == 'baseline':
embedding = self.entity_regularizer(torch.index_select(self.entity_embedding, dim=0, index=queries[:, idx]))
elif self.model_mode == 'temp':
embedding = torch.index_select(self.entity_embedding, dim=0, index=queries[:, idx])
ent_type_id = torch.index_select(self.entity2type, dim=0, index=queries[:, idx])
entity_neighbor_type_embedding = torch.index_select(self.type_embedding, dim=0, index=ent_type_id.view(-1)).view(ent_type_id.shape[0], ent_type_id.shape[1], -1)
embedding = self.ent_neighbor_type_agg(embedding, entity_neighbor_type_embedding)
idx += 1
else:
alpha_embedding, beta_embedding, idx = self.embed_query_beta(queries, query_structure[0], idx)
embedding = torch.cat([alpha_embedding, beta_embedding], dim=-1)
for i in range(len(query_structure[-1])):
if query_structure[-1][i] == 'n':
assert (queries[:, idx] == -2).all()
if self.model_mode == 'temp':
embedding = self.entity_regularizer(embedding)
embedding = 1./embedding
else:
if self.model_mode == 'baseline':
r_embedding = torch.index_select(self.relation_embedding, dim=0, index=queries[:, idx])
embedding = self.projection_net(embedding, r_embedding)
elif self.model_mode == 'temp':
r_embedding = torch.index_select(self.relation_embedding, dim=0, index=queries[:, idx])
rel_type_id = torch.index_select(self.relation2type, dim=0, index=queries[:, idx])
relation_neighbor_type_embedding = torch.index_select(self.type_embedding, dim=0, index=rel_type_id.view(-1)).view(rel_type_id.shape[0], rel_type_id.shape[1], -1)
relation_neighbor_type_embedding = torch.transpose(relation_neighbor_type_embedding, 0, 1)
alpha_relation_neighbor_type_embedding, beta_relation_neighbor_type_embedding = torch.chunk(relation_neighbor_type_embedding, 2, dim=-1)
alpha_embedding, beta_embedding = torch.chunk(embedding, 2, dim=-1)
alpha_r_embedding, beta_r_embedding = torch.chunk(r_embedding, 2, dim=-1)
alpha_rel_type_cent = self.relation_center_net(alpha_relation_neighbor_type_embedding)
beta_rel_type_cent = self.relation_center_net(beta_relation_neighbor_type_embedding)
alpha_embedding = alpha_embedding.unsqueeze(1)
alpha_r_embedding = alpha_r_embedding.unsqueeze(1)
alpha_rel_type_cent = alpha_rel_type_cent.unsqueeze(1)
alpha_ent_rel = self.match([alpha_embedding, alpha_r_embedding])
alpha_ent_rel_type = self.match([alpha_embedding, alpha_rel_type_cent])
alpha_rel_ent = self.match([alpha_r_embedding, alpha_embedding])
alpha_rel_rel_type = self.match([alpha_r_embedding, alpha_rel_type_cent])
alpha_embedding = self.rel_neighbor_type_agg([alpha_ent_rel.squeeze(1), alpha_ent_rel_type.squeeze(1)])
alpha_r_embedding = self.rel_neighbor_type_agg([alpha_rel_ent.squeeze(1), alpha_rel_rel_type.squeeze(1)])
beta_embedding = beta_embedding.unsqueeze(1)
beta_r_embedding = beta_r_embedding.unsqueeze(1)
beta_rel_type_cent = beta_rel_type_cent.unsqueeze(1)
beta_ent_rel = self.match([beta_embedding, beta_r_embedding])
beta_ent_rel_type = self.match([beta_embedding, beta_rel_type_cent])
beta_rel_ent = self.match([beta_r_embedding, beta_embedding])
beta_rel_rel_type = self.match([beta_r_embedding, beta_rel_type_cent])
beta_embedding = self.rel_neighbor_type_agg([beta_ent_rel.squeeze(1), beta_ent_rel_type.squeeze(1)])
beta_r_embedding = self.rel_neighbor_type_agg([beta_rel_ent.squeeze(1), beta_rel_rel_type.squeeze(1)])
embedding = torch.cat([alpha_embedding, beta_embedding], dim=-1)
r_embedding = torch.cat([alpha_r_embedding, beta_r_embedding], dim=-1)
embedding = self.projection_without_net(embedding, r_embedding)
idx += 1
if self.model_mode == 'temp':
if filter_flag == False:
embedding = self.entity_regularizer(embedding)
alpha_embedding, beta_embedding = torch.chunk(embedding, 2, dim=-1)
else:
alpha_embedding_list = []
beta_embedding_list = []
for i in range(len(query_structure)):
alpha_embedding, beta_embedding, idx = self.embed_query_beta(queries, query_structure[i], idx)
alpha_embedding_list.append(alpha_embedding)
beta_embedding_list.append(beta_embedding)
alpha_embedding, beta_embedding = self.center_net(torch.stack(alpha_embedding_list), torch.stack(beta_embedding_list))
return alpha_embedding, beta_embedding, idx
def embed_query_cone(self, queries, query_structure, idx, filter_flag=False):
all_relation_flag = True
if self.model_mode == 'temp':
if filter_flag == False:
if query_structure in query_name_dict and query_name_dict[query_structure] == 'ip':
filter_flag = True
for ele in query_structure[-1]:
if ele not in ['r', 'n']:
all_relation_flag = False
break
if all_relation_flag:
if query_structure[0] == 'e':
if self.model_mode == 'baseline':
axis_entity_embedding = torch.index_select(self.entity_embedding, dim=0, index=queries[:, idx])
axis_entity_embedding = self.angle_scale(axis_entity_embedding, self.axis_scale)
axis_entity_embedding = convert_to_axis(axis_entity_embedding)
elif self.model_mode == 'temp':
axis_entity_embedding = torch.index_select(self.entity_embedding, dim=0, index=queries[:, idx])
ent_type_id = torch.index_select(self.entity2type, dim=0, index=queries[:, idx])
entity_neighbor_type_embedding = torch.index_select(self.type_embedding, dim=0, index=ent_type_id.view(-1)).view(ent_type_id.shape[0], ent_type_id.shape[1], -1)
axis_entity_embedding = self.ent_neighbor_type_agg(axis_entity_embedding, entity_neighbor_type_embedding)
axis_entity_embedding = self.angle_scale(axis_entity_embedding, self.axis_scale)
if self.use_cuda:
arg_entity_embedding = torch.zeros_like(axis_entity_embedding).cuda()
else:
arg_entity_embedding = torch.zeros_like(axis_entity_embedding)
idx += 1
axis_embedding = axis_entity_embedding
arg_embedding = arg_entity_embedding
else:
axis_embedding, arg_embedding, idx = self.embed_query_cone(queries, query_structure[0], idx, filter_flag)
for i in range(len(query_structure[-1])):
# negation
if query_structure[-1][i] == 'n':
assert (queries[:, idx] == -2).all()
if self.model_mode == 'temp':
axis_embedding = self.angle_scale(axis_embedding, self.axis_scale)
axis_embedding = convert_to_axis(axis_embedding)
axis_embedding, arg_embedding = self.cone_negation(axis_embedding, arg_embedding)
# projection
else:
if self.model_mode == 'baseline':
axis_r_embedding = torch.index_select(self.axis_embedding, dim=0, index=queries[:, idx])
arg_r_embedding = torch.index_select(self.arg_embedding, dim=0, index=queries[:, idx])
axis_r_embedding = self.angle_scale(axis_r_embedding, self.axis_scale)
arg_r_embedding = self.angle_scale(arg_r_embedding, self.arg_scale)
axis_r_embedding = convert_to_axis(axis_r_embedding)
arg_r_embedding = convert_to_axis(arg_r_embedding)
axis_embedding, arg_embedding = self.cone_proj(axis_embedding, arg_embedding, axis_r_embedding, arg_r_embedding)
elif self.model_mode == 'temp':
axis_r_embedding = torch.index_select(self.axis_embedding, dim=0, index=queries[:, idx])
axis_rel_type_id = torch.index_select(self.relation2type, dim=0, index=queries[:, idx])
axis_relation_neighbor_type_embedding = torch.index_select(self.type_embedding, dim=0, index=axis_rel_type_id.view(-1)).view(axis_rel_type_id.shape[0], axis_rel_type_id.shape[1], -1)
axis_relation_neighbor_type_embedding = torch.transpose(axis_relation_neighbor_type_embedding, 0, 1)
axis_rel_type_cent = self.relation_center_net(axis_relation_neighbor_type_embedding)
axis_r_embedding = self.angle_scale(axis_r_embedding, self.axis_scale)
axis_rel_type_cent = self.angle_scale(axis_rel_type_cent, self.axis_scale)
arg_r_embedding = torch.index_select(self.arg_embedding, dim=0, index=queries[:, idx])
arg_rel_type_id = torch.index_select(self.relation2type, dim=0, index=queries[:, idx])
arg_relation_neighbor_type_embedding = torch.index_select(self.type_embedding, dim=0, index=arg_rel_type_id.view(-1)).view(arg_rel_type_id.shape[0], arg_rel_type_id.shape[1], -1)
arg_relation_neighbor_type_embedding = torch.transpose(arg_relation_neighbor_type_embedding, 0, 1)
arg_rel_type_cent = self.relation_center_net(arg_relation_neighbor_type_embedding)
arg_r_embedding = self.angle_scale(arg_r_embedding, self.axis_scale)
arg_rel_type_cent = self.angle_scale(arg_rel_type_cent, self.axis_scale)
axis_embedding = axis_embedding.unsqueeze(1)
axis_r_embedding = axis_r_embedding.unsqueeze(1)
axis_rel_type_cent = axis_rel_type_cent.unsqueeze(1)
axis_ent_rel = self.match([axis_embedding, axis_r_embedding])
axis_ent_rel_type = self.match([axis_embedding, axis_rel_type_cent])
axis_rel_ent = self.match([axis_r_embedding, axis_embedding])
axis_rel_rel_type = self.match([axis_r_embedding, axis_rel_type_cent])
axis_embedding = self.rel_neighbor_type_agg([axis_ent_rel.squeeze(1), axis_ent_rel_type.squeeze(1)])
axis_r_embedding = self.rel_neighbor_type_agg([axis_rel_ent.squeeze(1), axis_rel_rel_type.squeeze(1)])
arg_embedding = arg_embedding.unsqueeze(1)
arg_r_embedding = arg_r_embedding.unsqueeze(1)
arg_rel_type_cent = arg_rel_type_cent.unsqueeze(1)
arg_ent_rel = self.match([arg_embedding, arg_r_embedding])
arg_ent_rel_type = self.match([arg_embedding, arg_rel_type_cent])
arg_rel_ent = self.match([arg_r_embedding, arg_embedding])
arg_rel_rel_type = self.match([arg_r_embedding, arg_rel_type_cent])
arg_embedding = self.rel_neighbor_type_agg([arg_ent_rel.squeeze(1), arg_ent_rel_type.squeeze(1)])
arg_r_embedding = self.rel_neighbor_type_agg([arg_rel_ent.squeeze(1), arg_rel_rel_type.squeeze(1)])
axis_embedding, arg_embedding = self.cone_without_proj(axis_embedding, arg_embedding, axis_r_embedding, arg_r_embedding)
idx += 1
if self.model_mode == 'temp':
if filter_flag == False:
axis_embedding = convert_to_axis(axis_embedding)
arg_embedding = convert_to_axis(arg_embedding)
else:
# intersection
axis_embedding_list = []
arg_embedding_list = []
for i in range(len(query_structure)):
axis_embedding, arg_embedding, idx = self.embed_query_cone(queries, query_structure[i], idx, filter_flag)
axis_embedding_list.append(axis_embedding)
arg_embedding_list.append(arg_embedding)
stacked_axis_embeddings = torch.stack(axis_embedding_list)
stacked_arg_embeddings = torch.stack(arg_embedding_list)
axis_embedding, arg_embedding = self.cone_intersection(stacked_axis_embeddings, stacked_arg_embeddings)
return axis_embedding, arg_embedding, idx
def embed_query_logic(self, queries, query_structure, idx, filter_flag=False):
'''
Iterative embed a batch of queries with same structure using logic embeddings
queries: a flattened batch of queries
'''
all_relation_flag = True
if filter_flag == False:
if query_structure in query_name_dict and query_name_dict[query_structure] == 'ip':
filter_flag = True
for ele in query_structure[-1]: # whether the current query tree has merged to one branch and only need to do relation traversal, e.g., path queries or conjunctive queries after the intersection
if ele not in ['r', 'n']:
all_relation_flag = False
break
if all_relation_flag:
if query_structure[0] == 'e':
if self.model_mode == 'baseline':
embedding = torch.index_select(self.entity_embedding, dim=0, index=queries[:, idx])
elif self.model_mode == 'temp':
embedding = torch.index_select(self.entity_embedding, dim=0, index=queries[:, idx])
ent_type_id = torch.index_select(self.entity2type, dim=0, index=queries[:, idx])
entity_neighbor_type_embedding = torch.index_select(self.type_embedding, dim=0, index=ent_type_id.view(-1)).view(ent_type_id.shape[0], ent_type_id.shape[1], -1)
embedding = self.ent_neighbor_type_agg(embedding, entity_neighbor_type_embedding)
idx += 1
else:
embedding, idx = self.embed_query_logic(queries, query_structure[0], idx, filter_flag)
for i in range(len(query_structure[-1])):
if query_structure[-1][i] == 'n':
assert (queries[:, idx] == -2).all()
if self.bounded:
lower_embedding, upper_embedding = torch.chunk(embedding, 2, dim=-1)
embedding = torch.cat([1 - upper_embedding, 1 - lower_embedding], dim=-1)
else:
embedding = 1 - embedding
else:
if self.model_mode == 'baseline':
r_embedding = torch.index_select(self.relation_embedding, dim=0, index=queries[:, idx])
embedding = self.projection_net(embedding, r_embedding)
elif self.model_mode == 'temp':
r_embedding = torch.index_select(self.relation_embedding, dim=0, index=queries[:, idx])
rel_type_id = torch.index_select(self.relation2type, dim=0, index=queries[:, idx])
relation_neighbor_type_embedding = torch.index_select(self.type_embedding, dim=0, index=rel_type_id.view(-1)).view(rel_type_id.shape[0], rel_type_id.shape[1], -1)
relation_neighbor_type_embedding = torch.transpose(relation_neighbor_type_embedding, 0, 1)
rel_type_cent = self.relation_center_net(relation_neighbor_type_embedding)
embedding = embedding.unsqueeze(1)
r_embedding = r_embedding.unsqueeze(1)
rel_type_cent = rel_type_cent.unsqueeze(1)
ent_rel = self.match([embedding, r_embedding])
ent_rel_type = self.match([embedding, rel_type_cent])
rel_ent = self.match([r_embedding, embedding])
rel_rel_type = self.match([r_embedding, rel_type_cent])
embedding = self.rel_neighbor_type_agg([ent_rel.squeeze(1), ent_rel_type.squeeze(1)])
r_embedding = self.rel_neighbor_type_agg([rel_ent.squeeze(1), rel_rel_type.squeeze(1)])
embedding = self.projection_net(embedding, r_embedding)
idx += 1
else:
embedding_list = []
for i in range(len(query_structure)):
embedding, idx = self.embed_query_logic(queries, query_structure[i], idx, filter_flag)
embedding_list.append(embedding)
embedding = self.center_net(torch.stack(embedding_list))
return embedding, idx
def transform_union_query(self, queries, query_structure):
'''
transform 2u queries to two 1p queries
transform up queries to two 2p queries
'''
if self.query_name_dict[query_structure] == '2u-DNF':
queries = queries[:, :-1] # remove union -1
elif self.query_name_dict[query_structure] == 'up-DNF':
queries = torch.cat([torch.cat([queries[:, :2], queries[:, 5:6]], dim=1), torch.cat([queries[:, 2:4], queries[:, 5:6]], dim=1)], dim=1)
queries = torch.reshape(queries, [queries.shape[0]*2, -1])
return queries
def transform_union_structure(self, query_structure):
if self.query_name_dict[query_structure] == '2u-DNF':
return ('e', ('r',))
elif self.query_name_dict[query_structure] == 'up-DNF':
return ('e', ('r', 'r'))