-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsgrl_link_pred.py
1609 lines (1421 loc) · 72 KB
/
sgrl_link_pred.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 pathlib import Path
from timeit import default_timer
import torch
import shutil
import argparse
import time
import os
import sys
import os.path as osp
from shutil import copy
import copy as cp
from ray import tune
from torch_geometric import seed_everything
from torch_geometric.loader import DataLoader
from torch_geometric.profile import profileit, timeit
from torch_geometric.transforms import OneHotDegree, NormalizeFeatures
from tqdm import tqdm
import pdb
from sklearn.metrics import roc_auc_score, average_precision_score
import scipy.sparse as ssp
from torch.nn import BCEWithLogitsLoss
from torch_sparse import coalesce, SparseTensor
from torch_geometric.datasets import Planetoid, AttributedGraphDataset, WikipediaNetwork, WebKB, Coauthor
from torch_geometric.data import Dataset, InMemoryDataset, Data
from torch_geometric.utils import to_undirected, to_dense_adj
from ogb.linkproppred import PygLinkPropPredDataset, Evaluator
import warnings
from scipy.sparse import SparseEfficiencyWarning
from custom_losses import auc_loss, hinge_auc_loss
from data_utils import read_label, read_edges
from models import SAGE, DGCNN, GCN, GIN, SIGNNet
from n2v_prep import node_2_vec_pretrain
from profiler_utils import profile_helper
from tuned_SIGN import TunedSIGN
# DO NOT REMOVE AA CN PPR IMPORTS
from utils import get_pos_neg_edges, extract_enclosing_subgraphs, construct_pyg_graph, k_hop_subgraph, do_edge_split, \
Logger, AA, CN, PPR, calc_ratio_helper, create_rw_cache
warnings.simplefilter('ignore', SparseEfficiencyWarning)
warnings.simplefilter('ignore', FutureWarning)
warnings.simplefilter('ignore', UserWarning)
class SEALDataset(InMemoryDataset):
def __init__(self, root, data, split_edge, num_hops, percent=100, split='train',
use_coalesce=False, node_label='drnl', ratio_per_hop=1.0,
max_nodes_per_hop=None, directed=False, rw_kwargs=None, device='cpu', pairwise=False,
pos_pairwise=False, neg_ratio=1, use_feature=False, sign_type="", args=None):
self.data = data
self.split_edge = split_edge
self.num_hops = num_hops
self.percent = int(percent) if percent >= 1.0 else percent
self.split = split
self.use_coalesce = use_coalesce
self.node_label = node_label
self.ratio_per_hop = ratio_per_hop
self.max_nodes_per_hop = max_nodes_per_hop
self.directed = directed
self.device = device
self.N = self.data.num_nodes
self.E = self.data.edge_index.size()[-1]
self.sparse_adj = SparseTensor(
row=self.data.edge_index[0].to(self.device), col=self.data.edge_index[1].to(self.device),
value=torch.arange(self.E, device=self.device),
sparse_sizes=(self.N, self.N))
self.rw_kwargs = rw_kwargs
self.pairwise = pairwise
self.pos_pairwise = pos_pairwise
self.neg_ratio = neg_ratio
self.use_feature = use_feature
self.sign_type = sign_type
self.args = args
super(SEALDataset, self).__init__(root)
if not self.rw_kwargs.get('calc_ratio', False):
self.data, self.slices = torch.load(self.processed_paths[0])
@property
def processed_file_names(self):
if self.percent == 100:
name = 'SEAL_{}_data'.format(self.split)
else:
name = 'SEAL_{}_data_{}'.format(self.split, self.percent)
name += '.pt'
return [name]
def process(self):
pos_edge, neg_edge = get_pos_neg_edges(self.split, self.split_edge,
self.data.edge_index,
self.data.num_nodes,
self.percent, neg_ratio=self.neg_ratio)
if self.use_coalesce: # compress mutli-edge into edge with weight
self.data.edge_index, self.data.edge_weight = coalesce(
self.data.edge_index, self.data.edge_weight,
self.data.num_nodes, self.data.num_nodes)
if 'edge_weight' in self.data:
edge_weight = self.data.edge_weight.view(-1)
else:
edge_weight = torch.ones(self.data.edge_index.size(1), dtype=int)
A = ssp.csr_matrix(
(edge_weight, (self.data.edge_index[0], self.data.edge_index[1])),
shape=(self.data.num_nodes, self.data.num_nodes)
)
if self.directed:
A_csc = A.tocsc()
else:
A_csc = None
# Extract enclosing subgraphs for pos and neg edges
cached_pos_rws = cached_neg_rws = None
if self.rw_kwargs.get('m') and self.args.optimize_sign and self.sign_type == "PoS":
cached_pos_rws = create_rw_cache(self.sparse_adj, pos_edge, self.device, self.rw_kwargs['m'],
self.rw_kwargs['M'])
cached_neg_rws = create_rw_cache(self.sparse_adj, neg_edge, self.device, self.rw_kwargs['m'],
self.rw_kwargs['M'])
rw_kwargs = {
"rw_m": self.rw_kwargs.get('m'),
"rw_M": self.rw_kwargs.get('M'),
"sparse_adj": self.sparse_adj,
"edge_index": self.data.edge_index,
"device": self.device,
"data": self.data,
"node_label": self.node_label,
"cached_pos_rws": cached_pos_rws,
"cached_neg_rws": cached_neg_rws,
}
sign_kwargs = {}
powers_of_A = []
if self.args.model == 'SIGN':
sign_k = self.args.sign_k
sign_type = self.sign_type
sign_kwargs.update({
"sign_k": sign_k,
"use_feature": self.use_feature,
"sign_type": sign_type,
"optimize_sign": self.args.optimize_sign,
"k_heuristic": self.args.k_heuristic,
"k_node_set_strategy": self.args.k_node_set_strategy,
})
if not self.rw_kwargs.get('m'):
rw_kwargs = None
else:
rw_kwargs.update({"sign": True})
if sign_type == 'SoP' or sign_type == "hybrid":
edge_index = self.data.edge_index
num_nodes = self.data.num_nodes
row, col = edge_index
adj_t = SparseTensor(row=row, col=col,
sparse_sizes=(num_nodes, num_nodes)
)
deg = adj_t.sum(dim=1).to(torch.float)
deg_inv_sqrt = deg.pow(-0.5)
deg_inv_sqrt[deg_inv_sqrt == float('inf')] = 0
adj_t = deg_inv_sqrt.view(-1, 1) * adj_t * deg_inv_sqrt.view(1, -1)
print("Begin taking powers of A")
powers_of_A = [adj_t]
for sign_k in tqdm(range(2, self.args.sign_k + 1), ncols=70):
powers_of_A += [adj_t @ powers_of_A[-1]]
if not sign_kwargs['optimize_sign']:
for index in range(len(powers_of_A)):
powers_of_A[index] = ssp.csr_matrix(powers_of_A[index].to_dense())
if self.rw_kwargs.get('calc_ratio', False):
print(f"Calculating preprocessing stats for {self.split}")
if self.args.model == "SIGN":
raise NotImplementedError("calc_ratio not implemented for SIGN")
calc_ratio_helper(pos_edge, neg_edge, A, self.data.x, -1, self.num_hops, self.node_label,
self.ratio_per_hop, self.max_nodes_per_hop, self.directed, A_csc, rw_kwargs, self.split,
self.args.dataset, self.args.seed)
exit()
if not self.pairwise:
print("Setting up Positive Subgraphs")
pos_list = extract_enclosing_subgraphs(
pos_edge, A, self.data.x, 1, self.num_hops, self.node_label,
self.ratio_per_hop, self.max_nodes_per_hop, self.directed, A_csc, rw_kwargs, sign_kwargs,
powers_of_A=powers_of_A, data=self.data)
print("Setting up Negative Subgraphs")
neg_list = extract_enclosing_subgraphs(
neg_edge, A, self.data.x, 0, self.num_hops, self.node_label,
self.ratio_per_hop, self.max_nodes_per_hop, self.directed, A_csc, rw_kwargs, sign_kwargs,
powers_of_A=powers_of_A, data=self.data)
torch.save(self.collate(pos_list + neg_list), self.processed_paths[0])
del pos_list, neg_list
else:
if self.pos_pairwise:
pos_list = extract_enclosing_subgraphs(
pos_edge, A, self.data.x, 1, self.num_hops, self.node_label,
self.ratio_per_hop, self.max_nodes_per_hop, self.directed, A_csc, rw_kwargs, sign_kwargs,
powers_of_A=powers_of_A, data=self.data)
torch.save(self.collate(pos_list), self.processed_paths[0])
del pos_list
else:
neg_list = extract_enclosing_subgraphs(
neg_edge, A, self.data.x, 0, self.num_hops, self.node_label,
self.ratio_per_hop, self.max_nodes_per_hop, self.directed, A_csc, rw_kwargs, sign_kwargs,
powers_of_A=powers_of_A, data=self.data)
torch.save(self.collate(neg_list), self.processed_paths[0])
del neg_list
class SEALDynamicDataset(Dataset):
def __init__(self, root, data, split_edge, num_hops, percent=100, split='train',
use_coalesce=False, node_label='drnl', ratio_per_hop=1.0,
max_nodes_per_hop=None, directed=False, rw_kwargs=None, device='cpu', pairwise=False,
pos_pairwise=False, neg_ratio=1, use_feature=False, sign_type="", args=None, **kwargs):
self.data = data
self.split_edge = split_edge
self.num_hops = num_hops
self.percent = percent
self.use_coalesce = use_coalesce
self.node_label = node_label
self.ratio_per_hop = ratio_per_hop
self.max_nodes_per_hop = max_nodes_per_hop
self.directed = directed
self.rw_kwargs = rw_kwargs
self.device = device
self.N = self.data.num_nodes
self.E = self.data.edge_index.size()[-1]
self.sparse_adj = SparseTensor(
row=self.data.edge_index[0].to(self.device), col=self.data.edge_index[1].to(self.device),
value=torch.arange(self.E, device=self.device),
sparse_sizes=(self.N, self.N))
self.pairwise = pairwise
self.pos_pairwise = pos_pairwise
self.neg_ratio = neg_ratio
self.use_feature = use_feature
self.sign_type = sign_type
self.args = args
super(SEALDynamicDataset, self).__init__(root)
pos_edge, neg_edge = get_pos_neg_edges(split, self.split_edge,
self.data.edge_index,
self.data.num_nodes,
self.percent, neg_ratio=self.neg_ratio)
if self.pairwise:
if self.pos_pairwise:
self.links = pos_edge.t().tolist()
self.labels = [1] * pos_edge.size(1)
else:
self.links = neg_edge.t().tolist()
self.labels = [0] * neg_edge.size(1)
else:
self.links = torch.cat([pos_edge, neg_edge], 1).t().tolist()
self.labels = [1] * pos_edge.size(1) + [0] * neg_edge.size(1)
if self.use_coalesce: # compress mutli-edge into edge with weight
self.data.edge_index, self.data.edge_weight = coalesce(
self.data.edge_index, self.data.edge_weight,
self.data.num_nodes, self.data.num_nodes)
if 'edge_weight' in self.data:
edge_weight = self.data.edge_weight.view(-1)
else:
edge_weight = torch.ones(self.data.edge_index.size(1), dtype=int)
self.A = ssp.csr_matrix(
(edge_weight, (self.data.edge_index[0], self.data.edge_index[1])),
shape=(self.data.num_nodes, self.data.num_nodes)
)
if self.directed:
self.A_csc = self.A.tocsc()
else:
self.A_csc = None
self.unique_nodes = {}
if self.rw_kwargs.get('M'):
print("Start caching random walk unique nodes")
for link in self.links:
rw_M = self.rw_kwargs.get('M')
starting_nodes = []
[starting_nodes.extend(link) for _ in range(rw_M)]
start = torch.tensor(starting_nodes, dtype=torch.long, device=device)
rw = self.sparse_adj.random_walk(start.flatten(), self.rw_kwargs.get('m'))
self.unique_nodes[tuple(link)] = torch.unique(rw.flatten()).tolist()
print("Finish caching random walk unique nodes")
self.powers_of_A = []
if self.args.model == 'SIGN':
if self.sign_type == 'SoP':
edge_index = self.data.edge_index
num_nodes = self.data.num_nodes
dense_adj = to_dense_adj(edge_index).reshape([num_nodes, num_nodes])
self.powers_of_A = [self.A]
for sign_k in range(2, self.args.sign_k + 1):
dense_adj_power = torch.linalg.matrix_power(dense_adj, sign_k)
self.powers_of_A.append(ssp.csr_matrix(dense_adj_power))
def __len__(self):
return len(self.links)
def len(self):
return self.__len__()
def get(self, idx):
if self.args.model == 'SIGN':
raise NotImplementedError("SoP and PoS (plus) support in dynamic mode is not implemented (yet)")
src, dst = self.links[idx]
y = self.labels[idx]
rw_kwargs = {
"rw_m": self.rw_kwargs.get('m'),
"rw_M": self.rw_kwargs.get('M'),
"sparse_adj": self.sparse_adj,
"edge_index": self.data.edge_index,
"device": self.device,
"data": self.data,
"unique_nodes": self.unique_nodes,
"node_label": self.node_label,
}
sign_kwargs = {}
if self.args.model == 'SIGN':
if not self.rw_kwargs.get('m'):
if not self.powers_of_A:
# PoS flow
# debug code with graphistry
# networkx_G = to_networkx(data) # the full graph
# graphistry.bind(source='src', destination='dst', node='nodeid').plot(networkx_G)
# check against the nodes that is received in tmp before the relabeling occurs
tmp = k_hop_subgraph(src, dst, self.num_hops, self.A, self.ratio_per_hop,
self.max_nodes_per_hop, node_features=self.data.x,
y=y, directed=self.directed, A_csc=self.A_csc)
sign_pyg_kwargs = {
'use_feature': self.use_feature,
}
data = construct_pyg_graph(*tmp, self.node_label, sign_pyg_kwargs)
sign_t = TunedSIGN(self.args.sign_k)
data = sign_t(data, self.args.sign_k)
else:
# SoP flow
# debug code with graphistry
# networkx_G = to_networkx(data) # the full graph
# graphistry.bind(source='src', destination='dst', node='nodeid').plot(networkx_G)
# check against the nodes that is received in tmp before the relabeling occurs
pos_data_list = []
for index, power_of_a in enumerate(self.powers_of_A, start=1):
tmp = k_hop_subgraph(src, dst, self.num_hops, power_of_a, self.ratio_per_hop,
self.max_nodes_per_hop, node_features=self.data.x,
y=y, directed=self.directed, A_csc=self.A_csc)
sign_pyg_kwargs = {
'use_feature': self.use_feature,
}
data = construct_pyg_graph(*tmp, self.node_label, sign_pyg_kwargs)
pos_data_list.append(data)
sign_t = TunedSIGN(self.args.sign_k)
data = sign_t.SoP_data_creation(pos_data_list)
else:
rw_kwargs.update({'sign': True})
data = k_hop_subgraph(src, dst, self.num_hops, self.A, self.ratio_per_hop,
self.max_nodes_per_hop, node_features=self.data.x,
y=y, directed=self.directed, A_csc=self.A_csc, rw_kwargs=rw_kwargs)
sign_t = TunedSIGN(self.args.sign_k)
data = sign_t(data, self.args.sign_k)
else:
if not rw_kwargs['rw_m']:
# SEAL flow
tmp = k_hop_subgraph(src, dst, self.num_hops, self.A, self.ratio_per_hop,
self.max_nodes_per_hop, node_features=self.data.x,
y=y, directed=self.directed, A_csc=self.A_csc)
data = construct_pyg_graph(*tmp, self.node_label, sign_kwargs)
else:
data = k_hop_subgraph(src, dst, self.num_hops, self.A, self.ratio_per_hop,
self.max_nodes_per_hop, node_features=self.data.x,
y=y, directed=self.directed, A_csc=self.A_csc, rw_kwargs=rw_kwargs)
return data
@profileit()
def profile_train(model, train_loader, optimizer, device, emb, train_dataset, args):
# normal training with BCE logit loss with profiling enabled
model.train()
total_loss = 0
pbar = tqdm(train_loader, ncols=70)
for data in pbar:
data = data.to(device)
optimizer.zero_grad()
x = data.x if args.use_feature else None
edge_weight = data.edge_weight if args.use_edge_weight else None
node_id = data.node_id if emb else None
num_nodes = data.num_nodes
if args.model == 'SIGN':
sign_k = args.sign_k
if args.sign_type == 'hybrid':
sign_k = args.sign_k * 2 - 1
if sign_k != -1:
xs = [data.x.to(device)]
xs += [data[f'x{i}'].to(device) for i in range(1, sign_k + 1)]
else:
xs = [data[f'x{args.sign_k}'].to(device)]
operator_batch_data = [data.batch] + [data[f"x{index}_batch"] for index in range(1, args.sign_k + 1)]
logits = model(xs, operator_batch_data)
else:
logits = model(num_nodes, data.z, data.edge_index, data.batch, x, edge_weight, node_id)
loss = BCEWithLogitsLoss()(logits.view(-1), data.y.to(torch.float))
loss.backward()
optimizer.step()
total_loss += loss.item() * data.num_graphs
return total_loss / len(train_dataset)
def train_bce(model, train_loader, optimizer, device, emb, train_dataset, args):
# normal training with BCE logit loss
model.train()
total_loss = 0
pbar = tqdm(train_loader, ncols=70)
for data in pbar:
data = data.to(device)
optimizer.zero_grad()
if args.model == 'SIGN':
sign_k = args.sign_k
if args.sign_type == 'hybrid':
sign_k = args.sign_k * 2 - 1
if sign_k != -1:
xs = [data.x.to(device)]
xs += [data[f'x{i}'].to(device) for i in range(1, sign_k + 1)]
else:
xs = [data[f'x{args.sign_k}'].to(device)]
operator_batch_data = [data.batch] + [data[f"x{index}_batch"] for index in range(1, args.sign_k + 1)]
logits = model(xs, operator_batch_data)
else:
x = data.x if args.use_feature else None
edge_weight = data.edge_weight if args.use_edge_weight else None
node_id = data.node_id if emb else None
num_nodes = data.num_nodes
logits = model(num_nodes, data.z, data.edge_index, data.batch, x, edge_weight, node_id)
loss = BCEWithLogitsLoss()(logits.view(-1), data.y.to(torch.float))
loss.backward()
optimizer.step()
total_loss += loss.item() * data.num_graphs
return total_loss / len(train_dataset)
def train_pairwise(model, train_positive_loader, train_negative_loader, optimizer, device, emb, train_dataset, args):
# pairwise training with AUC loss + many others from PLNLP paper
model.train()
total_loss = 0
pbar = tqdm(train_positive_loader, ncols=70)
train_negative_loader = iter(train_negative_loader)
for indx, data in enumerate(pbar):
pos_data = data.to(device)
optimizer.zero_grad()
pos_x = pos_data.x if args.use_feature else None
pos_edge_weight = pos_data.edge_weight if args.use_edge_weight else None
pos_node_id = pos_data.node_id if emb else None
pos_num_nodes = pos_data.num_nodes
if args.model == 'SIGN':
if args.sign_k != -1:
xs = [data.x.to(device)]
xs += [data[f'x{i}'].to(device) for i in range(1, args.sign_k + 1)]
else:
xs = [data[f'x{args.sign_k}'].to(device)]
operator_batch_data = [data.batch] + [data[f"x{index}_batch"] for index in range(1, args.sign_k + 1)]
pos_logits = model(xs, operator_batch_data)
else:
pos_logits = model(pos_num_nodes, pos_data.z, pos_data.edge_index, data.batch, pos_x, pos_edge_weight,
pos_node_id)
neg_data = next(train_negative_loader).to(device)
neg_x = neg_data.x if args.use_feature else None
neg_edge_weight = neg_data.edge_weight if args.use_edge_weight else None
neg_node_id = neg_data.node_id if emb else None
neg_num_nodes = neg_data.num_nodes
if args.model == 'SIGN':
if args.sign_k != -1:
xs = [data.x.to(device)]
xs += [data[f'x{i}'].to(device) for i in range(1, args.sign_k + 1)]
else:
xs = [data[f'x{args.sign_k}'].to(device)]
operator_batch_data = [data.batch] + [data[f"x{index}_batch"] for index in range(1, args.sign_k + 1)]
neg_logits = model(xs, operator_batch_data)
else:
neg_logits = model(neg_num_nodes, neg_data.z, neg_data.edge_index, neg_data.batch, neg_x, neg_edge_weight,
neg_node_id)
loss_fn = get_loss(args.loss_fn)
loss = loss_fn(pos_logits, neg_logits, args.neg_ratio)
loss.backward()
optimizer.step()
total_loss += loss.item() * data.num_graphs
return total_loss / len(train_dataset)
def get_loss(loss_function):
if loss_function == 'auc_loss':
return auc_loss
elif loss_function == 'hinge_auc_loss':
return hinge_auc_loss
else:
raise NotImplementedError(f'Loss function {loss_function} not implemented')
@torch.no_grad()
def test(evaluator, model, val_loader, device, emb, test_loader, args):
model.eval()
y_pred, y_true = [], []
for data in tqdm(val_loader, ncols=70):
data = data.to(device)
x = data.x if args.use_feature else None
edge_weight = data.edge_weight if args.use_edge_weight else None
node_id = data.node_id if emb else None
num_nodes = data.num_nodes
if args.model == 'SIGN':
sign_k = args.sign_k
if args.sign_type == 'hybrid':
sign_k = args.sign_k * 2 - 1
if sign_k != -1:
xs = [data.x.to(device)]
xs += [data[f'x{i}'].to(device) for i in range(1, sign_k + 1)]
else:
xs = [data[f'x{args.sign_k}'].to(device)]
operator_batch_data = [data.batch] + [data[f"x{index}_batch"] for index in range(1, args.sign_k + 1)]
logits = model(xs, operator_batch_data)
else:
logits = model(num_nodes, data.z, data.edge_index, data.batch, x, edge_weight, node_id)
y_pred.append(logits.view(-1).cpu())
y_true.append(data.y.view(-1).cpu().to(torch.float))
val_pred, val_true = torch.cat(y_pred), torch.cat(y_true)
pos_val_pred = val_pred[val_true == 1]
neg_val_pred = val_pred[val_true == 0]
if args.profile:
out, time_for_inference = _get_test_auc_with_prof(args, device, emb, model, test_loader)
else:
time_for_inference_start = default_timer()
out = _get_test_auc(args, device, emb, model, test_loader)
time_for_inference_end = default_timer()
time_for_inference = time_for_inference_end - time_for_inference_start
neg_test_pred, pos_test_pred, test_pred, test_true = out
if args.eval_metric == 'hits':
results = evaluate_hits(pos_val_pred, neg_val_pred, pos_test_pred, neg_test_pred, evaluator)
elif args.eval_metric == 'mrr':
results = evaluate_mrr(pos_val_pred, neg_val_pred, pos_test_pred, neg_test_pred, evaluator)
elif args.eval_metric == 'rocauc':
results = evaluate_ogb_rocauc(pos_val_pred, neg_val_pred, pos_test_pred, neg_test_pred, evaluator)
elif args.eval_metric == 'auc':
results = evaluate_auc(val_pred, val_true, test_pred, test_true)
return results, time_for_inference
@timeit()
@torch.no_grad()
def _get_test_auc_with_prof(args, device, emb, model, test_loader):
y_pred, y_true = [], []
for data in tqdm(test_loader, ncols=70):
data = data.to(device)
x = data.x if args.use_feature else None
edge_weight = data.edge_weight if args.use_edge_weight else None
node_id = data.node_id if emb else None
num_nodes = data.num_nodes
if args.model == 'SIGN':
sign_k = args.sign_k
if args.sign_type == 'hybrid':
sign_k = args.sign_k * 2 - 1
if sign_k != -1:
xs = [data.x.to(device)]
xs += [data[f'x{i}'].to(device) for i in range(1, sign_k + 1)]
else:
xs = [data[f'x{args.sign_k}'].to(device)]
operator_batch_data = [data.batch] + [data[f"x{index}_batch"] for index in range(1, args.sign_k + 1)]
logits = model(xs, operator_batch_data)
else:
logits = model(num_nodes, data.z, data.edge_index, data.batch, x, edge_weight, node_id)
y_pred.append(logits.view(-1).cpu())
y_true.append(data.y.view(-1).cpu().to(torch.float))
test_pred, test_true = torch.cat(y_pred), torch.cat(y_true)
pos_test_pred = test_pred[test_true == 1]
neg_test_pred = test_pred[test_true == 0]
return neg_test_pred, pos_test_pred, test_pred, test_true
@torch.no_grad()
def _get_test_auc(args, device, emb, model, test_loader):
y_pred, y_true = [], []
for data in tqdm(test_loader, ncols=70):
data = data.to(device)
x = data.x if args.use_feature else None
edge_weight = data.edge_weight if args.use_edge_weight else None
node_id = data.node_id if emb else None
num_nodes = data.num_nodes
if args.model == 'SIGN':
sign_k = args.sign_k
if args.sign_type == 'hybrid':
sign_k = args.sign_k * 2 - 1
if sign_k != -1:
xs = [data.x.to(device)]
xs += [data[f'x{i}'].to(device) for i in range(1, sign_k + 1)]
else:
xs = [data[f'x{args.sign_k}'].to(device)]
operator_batch_data = [data.batch] + [data[f"x{index}_batch"] for index in range(1, args.sign_k + 1)]
logits = model(xs, operator_batch_data)
else:
logits = model(num_nodes, data.z, data.edge_index, data.batch, x, edge_weight, node_id)
y_pred.append(logits.view(-1).cpu())
y_true.append(data.y.view(-1).cpu().to(torch.float))
test_pred, test_true = torch.cat(y_pred), torch.cat(y_true)
pos_test_pred = test_pred[test_true == 1]
neg_test_pred = test_pred[test_true == 0]
return neg_test_pred, pos_test_pred, test_pred, test_true
@torch.no_grad()
def test_multiple_models(models, val_loader, device, emb, test_loader, evaluator, args):
raise NotImplementedError("This is untested")
for m in models:
m.eval()
y_pred, y_true = [[] for _ in range(len(models))], [[] for _ in range(len(models))]
for data in tqdm(val_loader, ncols=70):
data = data.to(device)
x = data.x if args.use_feature else None
edge_weight = data.edge_weight if args.use_edge_weight else None
node_id = data.node_id if emb else None
for i, m in enumerate(models):
logits = m(data.z, data.edge_index, data.batch, x, edge_weight, node_id)
y_pred[i].append(logits.view(-1).cpu())
y_true[i].append(data.y.view(-1).cpu().to(torch.float))
val_pred = [torch.cat(y_pred[i]) for i in range(len(models))]
val_true = [torch.cat(y_true[i]) for i in range(len(models))]
pos_val_pred = [val_pred[i][val_true[i] == 1] for i in range(len(models))]
neg_val_pred = [val_pred[i][val_true[i] == 0] for i in range(len(models))]
y_pred, y_true = [[] for _ in range(len(models))], [[] for _ in range(len(models))]
for data in tqdm(test_loader, ncols=70):
data = data.to(device)
x = data.x if args.use_feature else None
edge_weight = data.edge_weight if args.use_edge_weight else None
node_id = data.node_id if emb else None
for i, m in enumerate(models):
logits = m(data.z, data.edge_index, data.batch, x, edge_weight, node_id)
y_pred[i].append(logits.view(-1).cpu())
y_true[i].append(data.y.view(-1).cpu().to(torch.float))
test_pred = [torch.cat(y_pred[i]) for i in range(len(models))]
test_true = [torch.cat(y_true[i]) for i in range(len(models))]
pos_test_pred = [test_pred[i][test_true[i] == 1] for i in range(len(models))]
neg_test_pred = [test_pred[i][test_true[i] == 0] for i in range(len(models))]
Results = []
for i in range(len(models)):
if args.eval_metric == 'hits':
Results.append(evaluate_hits(pos_val_pred[i], neg_val_pred[i],
pos_test_pred[i], neg_test_pred[i]))
elif args.eval_metric == 'mrr':
Results.append(evaluate_mrr(pos_val_pred[i], neg_val_pred[i],
pos_test_pred[i], neg_test_pred[i], evaluator))
elif args.eval_metric == 'rocauc':
Results.append(evaluate_ogb_rocauc(pos_val_pred[i], neg_val_pred[i],
pos_test_pred[i], neg_test_pred[i], evaluator))
elif args.eval_metric == 'auc':
Results.append(evaluate_auc(val_pred[i], val_true[i],
test_pred[i], test_pred[i]))
return Results
def evaluate_hits(pos_val_pred, neg_val_pred, pos_test_pred, neg_test_pred, evaluator):
results = {}
for K in [20, 50, 100]:
evaluator.K = K
valid_hits = evaluator.eval({
'y_pred_pos': pos_val_pred,
'y_pred_neg': neg_val_pred,
})[f'hits@{K}']
test_hits = evaluator.eval({
'y_pred_pos': pos_test_pred,
'y_pred_neg': neg_test_pred,
})[f'hits@{K}']
results[f'Hits@{K}'] = (valid_hits, test_hits)
return results
def evaluate_mrr(pos_val_pred, neg_val_pred, pos_test_pred, neg_test_pred, evaluator):
neg_val_pred = neg_val_pred.view(pos_val_pred.shape[0], -1)
neg_test_pred = neg_test_pred.view(pos_test_pred.shape[0], -1)
results = {}
valid_mrr = evaluator.eval({
'y_pred_pos': pos_val_pred,
'y_pred_neg': neg_val_pred,
})['mrr_list'].mean().item()
test_mrr = evaluator.eval({
'y_pred_pos': pos_test_pred,
'y_pred_neg': neg_test_pred,
})['mrr_list'].mean().item()
results['MRR'] = (valid_mrr, test_mrr)
return results
def evaluate_ogb_rocauc(pos_val_pred, neg_val_pred, pos_test_pred, neg_test_pred, evaluator):
valid_rocauc = evaluator.eval({
'y_pred_pos': pos_val_pred,
'y_pred_neg': neg_val_pred,
})[f'rocauc']
test_rocauc = evaluator.eval({
'y_pred_pos': pos_test_pred,
'y_pred_neg': neg_test_pred,
})[f'rocauc']
results = {}
results['rocauc'] = (valid_rocauc, test_rocauc)
return results
def evaluate_auc(val_pred, val_true, test_pred, test_true):
# this also evaluates AP, but the function is not renamed as such
valid_auc = roc_auc_score(val_true, val_pred)
test_auc = roc_auc_score(test_true, test_pred)
valid_ap = average_precision_score(val_true, val_pred)
test_ap = average_precision_score(test_true, test_pred)
results = {}
results['AUC'] = (valid_auc, test_auc)
results['AP'] = (valid_ap, test_ap)
return results
def run_sgrl_learning_with_ray(config, hyper_param_class, device):
args = hyper_param_class
print(config)
if config:
print("Using override values for hypertuning")
# override defaults for each hyperparam tuning run
args.hidden_channels = config['hidden_channels']
args.batch_size = config['batch_size']
args.num_hops = config['num_hops']
args.lr = config['lr']
args.dropout = config['dropout']
args.sign_k = config['sign_k']
args.n2v_dim = config['n2v_dim']
args.k_heuristic = config['k_heuristic']
run_sgrl_learning(args, device, hypertuning=True)
def run_sgrl_learning(args, device, hypertuning=False):
if args.save_appendix == '':
args.save_appendix = '_' + time.strftime("%Y%m%d%H%M%S") + f'_seed{args.seed}'
if args.m and args.M:
args.save_appendix += f'_m{args.m}_M{args.M}_dropedge{args.dropedge}_seed{args.seed}'
if args.data_appendix == '':
if args.m and args.M:
args.data_appendix = f'_m{args.m}_M{args.M}_dropedge{args.dropedge}_seed{args.seed}'
else:
args.data_appendix = '_h{}_{}_rph{}_seed{}'.format(
args.num_hops, args.node_label, ''.join(str(args.ratio_per_hop).split('.')), args.seed)
if args.max_nodes_per_hop is not None:
args.data_appendix += '_mnph{}'.format(args.max_nodes_per_hop)
if args.use_valedges_as_input:
args.data_appendix += '_uvai'
args.res_dir = os.path.join('results/{}{}'.format(args.dataset, args.save_appendix))
print('Results will be saved in ' + args.res_dir)
if not os.path.exists(args.res_dir):
os.makedirs(args.res_dir)
if not args.keep_old:
# Backup python files.
copy('sgrl_link_pred.py', args.res_dir)
copy('utils.py', args.res_dir)
log_file = os.path.join(args.res_dir, 'log.txt')
# Save command line input.
cmd_input = 'python ' + ' '.join(sys.argv) + '\n'
with open(os.path.join(args.res_dir, 'cmd_input.txt'), 'a') as f:
f.write(cmd_input)
print('Command line input: ' + cmd_input + ' is saved.')
with open(log_file, 'a') as f:
f.write('\n' + cmd_input)
# SGRL Dataset prep + Training Flow
if args.dataset.startswith('ogbl'):
dataset = PygLinkPropPredDataset(name=args.dataset, transform=NormalizeFeatures())
split_edge = dataset.get_edge_split()
data = dataset[0]
elif args.dataset.startswith('ogbl-vessel'):
dataset = PygLinkPropPredDataset(name=args.dataset)
split_edge = dataset.get_edge_split()
data = dataset[0]
# normalize node features
data.x[:, 0] = torch.nn.functional.normalize(data.x[:, 0], dim=0)
data.x[:, 1] = torch.nn.functional.normalize(data.x[:, 1], dim=0)
data.x[:, 2] = torch.nn.functional.normalize(data.x[:, 2], dim=0)
elif args.dataset.startswith('attributed'):
dataset_name = args.dataset.split('-')[-1]
path = osp.join('dataset', dataset_name)
dataset = AttributedGraphDataset(path, dataset_name, transform=NormalizeFeatures())
split_edge = do_edge_split(dataset, args.fast_split, val_ratio=args.split_val_ratio,
test_ratio=args.split_test_ratio, neg_ratio=args.neg_ratio)
data = dataset[0]
data.edge_index = split_edge['train']['edge'].t()
elif args.dataset in ['Cora', 'Pubmed', 'CiteSeer']:
path = osp.join('dataset', args.dataset)
dataset = Planetoid(path, args.dataset, transform=NormalizeFeatures())
split_edge = do_edge_split(dataset, args.fast_split, val_ratio=args.split_val_ratio,
test_ratio=args.split_test_ratio, neg_ratio=args.neg_ratio)
data = dataset[0]
data.edge_index = split_edge['train']['edge'].t()
import networkx as nx
G = nx.Graph()
G.add_edges_from(data.edge_index.T.detach().numpy())
elif args.dataset in ['USAir', 'NS', 'Power', 'Celegans', 'Router', 'PB', 'Ecoli', 'Yeast']:
# We consume the dataset split index as well
if os.path.exists('data'):
file_name = os.path.join('data', 'link_prediction', args.dataset.lower())
else:
# we consume user path
file_name = os.path.join(str(Path.home()), 'S3GRL', 'data', 'link_prediction', args.dataset.lower())
if not os.path.exists(file_name):
raise FileNotFoundError("Check your file path is correct")
node_id_mapping = read_label(file_name)
edges = read_edges(file_name, node_id_mapping)
import networkx as nx
G = nx.Graph(edges)
edges_coo = torch.tensor(edges, dtype=torch.long).t().contiguous()
data = Data(edge_index=edges_coo.view(2, -1))
data.edge_index = to_undirected(data.edge_index)
data.num_nodes = torch.max(data.edge_index) + 1
split_edge = do_edge_split(data, args.fast_split, val_ratio=args.split_val_ratio,
test_ratio=args.split_test_ratio, neg_ratio=args.neg_ratio, data_passed=True)
data.edge_index = split_edge['train']['edge'].t()
# backward compatibility
class DummyDataset:
def __init__(self, root):
self.root = root
self.num_features = 0
def __repr__(self):
return args.dataset
def __len__(self):
return 1
dataset = DummyDataset(root=f'dataset/{args.dataset}/SEALDataset_{args.dataset}')
print("Finish reading from file")
elif args.dataset in ['chameleon', 'crocodile', 'squirrel']:
path = osp.join('dataset', args.dataset)
dataset = WikipediaNetwork(path, args.dataset, transform=NormalizeFeatures())
split_edge = do_edge_split(dataset, args.fast_split, val_ratio=args.split_val_ratio,
test_ratio=args.split_test_ratio, neg_ratio=args.neg_ratio)
data = dataset[0]
data.edge_index = split_edge['train']['edge'].t()
import networkx as nx
G = nx.Graph()
G.add_edges_from(data.edge_index.T.detach().numpy())
elif args.dataset in ['Cornell', 'Texas', 'Wisconsin']:
path = osp.join('dataset', args.dataset)
dataset = WebKB(path, args.dataset, transform=NormalizeFeatures())
split_edge = do_edge_split(dataset, args.fast_split, val_ratio=args.split_val_ratio,
test_ratio=args.split_test_ratio, neg_ratio=args.neg_ratio)
data = dataset[0]
data.edge_index = split_edge['train']['edge'].t()
import networkx as nx
G = nx.Graph()
G.add_edges_from(data.edge_index.T.detach().numpy())
elif args.dataset in ['CS', 'Physics']:
path = osp.join('dataset', args.dataset)
dataset = Coauthor(path, args.dataset, transform=NormalizeFeatures())
split_edge = do_edge_split(dataset, args.fast_split, val_ratio=args.split_val_ratio,
test_ratio=args.split_test_ratio, neg_ratio=args.neg_ratio)
data = dataset[0]
data.edge_index = split_edge['train']['edge'].t()
import networkx as nx
G = nx.Graph()
G.add_edges_from(data.edge_index.T.detach().numpy())
else:
raise NotImplementedError(f'dataset {args.dataset} is not yet supported.')
max_z = 1000 # set a large max_z so that every z has embeddings to look up
if args.dataset_stats:
if args.dataset in ['USAir', 'NS', 'Power', 'Celegans', 'Router', 'PB', 'Ecoli', 'Yeast']:
print(f'Dataset: {dataset}:')
print('======================')
print(f'Number of graphs: {len(dataset)}')
print(f'Number of features: {dataset.num_features}')
print(f'Number of nodes: {G.number_of_nodes()}')
print(f'Number of edges: {G.number_of_edges()}')
degrees = [x[1] for x in G.degree]
print(f'Average node degree: {sum(degrees) / len(G.nodes):.2f}')
print(f'Average clustering coeffiecient: {nx.average_clustering(G)}')
print(f'Is undirected: {data.is_undirected()}')
exit()
else:
print(f'Dataset: {dataset}:')
print('======================')
print(f'Number of graphs: {len(dataset)}')
print(f'Number of features: {dataset.num_features}')
print(f'Number of nodes: {data.num_nodes}')
print(f'Number of edges: {G.number_of_edges()}')
print(f'Average node degree: {data.num_edges / data.num_nodes:.2f}')
print(f'Average clustering coeffiecient: {nx.average_clustering(G)}')
print(f'Is undirected: {data.is_undirected()}')
exit()
time_for_prep_start = default_timer()
init_features = args.init_features
if init_features:
print(f"Init features using: {init_features}")
if init_features == "degree":
one_hot = OneHotDegree(max_degree=1024)
data = one_hot(data)
elif init_features == "eye":
data.x = torch.eye(data.num_nodes)
elif init_features == "n2v":
extra_identifier = ''
if args.model == "SIGN":
extra_identifier = f"{args.k_heuristic}{args.sign_type}{args.hidden_channels}{args.num_hops}"
data.x = node_2_vec_pretrain(args.dataset, data.edge_index, data.num_nodes, args.n2v_dim, args.seed, device,
args.epochs, hypertuning, extra_identifier)
init_representation = args.init_representation
if init_representation:
print(f"Init representation using: {init_representation} model")
from baselines.vgae import run_vgae
original_hidden_dims = args.hidden_channels
args.embedding_dim = args.hidden_channels
args.hidden_channels = args.hidden_channels // 2
# 64 -> 32 (output)
test_and_val = [split_edge['test']['edge'].T, split_edge['test']['edge_neg'].T, split_edge['valid']['edge'].T,
split_edge['valid']['edge_neg'].T]
edge_index = split_edge['train']['edge'].T
x = data.x
if init_representation in ['GAE', 'VGAE', 'ARGVA']:
_, data.x = run_vgae(edge_index=edge_index, x=x, test_and_val=test_and_val, model=init_representation,
args=args)
args.hidden_channels = original_hidden_dims
elif init_representation == 'GIC':
args.par_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ''))
sys.path.append('%s/Software/GIC/' % args.par_dir)
from GICEmbs import CalGIC
args.data_name = args.dataset
_, data.x = CalGIC(edge_index=edge_index, features=x, dataset=args.dataset, test_and_val=test_and_val,
args=args)
args.hidden_channels = original_hidden_dims
else:
raise NotImplementedError(f"init_representation: {init_representation} not supported.")
if init_representation or init_features: