-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmodels.py
More file actions
170 lines (146 loc) · 6.98 KB
/
Copy pathmodels.py
File metadata and controls
170 lines (146 loc) · 6.98 KB
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
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from geoopt.manifolds.stereographic.math import project
from geoopt.manifolds.stereographic import StereographicExact
from geoopt import ManifoldTensor
from geoopt import ManifoldParameter
from backbone import GCN, GAT, GraphSAGE
EPS = 1e-5
class RiemannianFeatures(nn.Module):
def __init__(self, num_nodes, dimensions, init_curvature, num_factors, learnable=True):
super(RiemannianFeatures, self).__init__()
self.manifolds = nn.ModuleList()
self.features = nn.ParameterList()
for i in range(num_factors):
if isinstance(dimensions, list):
d = dimensions[i]
else:
d = dimensions
k = init_curvature * (torch.randn(1) + 1)
manifold = StereographicExact(k=k, learnable=learnable)
features = ManifoldParameter(ManifoldTensor(torch.empty(num_nodes, d), manifold=manifold))
if k != 0:
self.init_weights(features)
self.manifolds.append(manifold)
self.features.append(features)
@staticmethod
def init_weights(w, scale=1e-4):
w.data.uniform_(-scale, scale)
w_norm = w.data.norm(p=2, dim=-1, keepdim=True) + EPS
w.data = w.data / w_norm * w.manifold.radius * 0.9 * torch.rand(1)
@staticmethod
def normalize(x, manifold):
x_norm = x.norm(p=2, dim=-1, keepdim=True) + EPS
if manifold.k != 0:
x = x / x_norm * 0.9 * torch.rand(1).to(x.device) * manifold.radius
else:
x = x / x_norm
return x
def forward(self):
products = []
for manifold, features in zip(self.manifolds, self.features):
products.append(project(features, k=manifold.k))
return products
class Model(nn.Module):
def __init__(self, backbone, n_layers, in_features, hidden_features, embed_features, n_heads, drop_edge, drop_node,
num_factors, dimensions, d_embeds, temperature, device=torch.device('cuda')):
super(Model, self).__init__()
d_embeds = dimensions
if backbone == 'gcn':
self.encoder = GCN(n_layers, in_features, hidden_features, embed_features, drop_edge, drop_node)
self.encoder2 = GCN(n_layers, d_embeds, hidden_features, embed_features, drop_edge, drop_node)
elif backbone == 'gat':
self.encoder = GAT(n_layers, in_features, hidden_features, embed_features, n_heads, drop_edge, drop_node)
self.encoder2 = GAT(n_layers, d_embeds, hidden_features, embed_features, n_heads, drop_edge, drop_node)
elif backbone == 'sage':
self.encoder = GraphSAGE(n_layers, in_features, hidden_features, embed_features, drop_edge, drop_node)
self.encoder2 = GraphSAGE(n_layers, d_embeds, hidden_features, embed_features, drop_edge, drop_node)
else:
raise NotImplementedError
self.temperature = temperature
self.Ws = []
self.bias = []
for i in range(num_factors):
if isinstance(dimensions, list):
d = dimensions[i]
else:
d = dimensions
pre = torch.randn(d_embeds, d).to(device)
w = pre / (torch.norm(pre, dim=-1, keepdim=True) + EPS)
self.Ws.append(w)
self.bias.append(2 * torch.pi * torch.rand(d_embeds).to(device))
self.decoder = FermiDiracDecoder(2, 1)
self.norm = nn.LayerNorm((num_factors+1) * embed_features)
def forward(self, x, edge_index, motif, neg_motif, rm_features: RiemannianFeatures):
products = rm_features()
x = self.encoder(x, edge_index)
laplacian = self.random_mapping(rm_features.manifolds, products)
cl_loss = 0
embeds = []
for embed in laplacian:
embed = self.encoder2(embed, edge_index)
cl_loss = cl_loss + self.cal_cl_loss(x, embed)
embeds.append(embed)
loss = cl_loss / len(laplacian) + self.cal_motif_loss(laplacian, motif, neg_motif)
embeds = torch.concat(embeds, -1)
return self.norm(torch.concat([x, embeds], -1)), loss
def random_mapping(self, manifolds, products):
out = []
for i in range(len(manifolds)):
x = products[i]
w = self.Ws[i]
b = self.bias[i]
k = manifolds[i].k
if k == 0:
distance = x @ w.t()
else:
div = torch.sum((x[:, None] - w[None]) ** 2, dim=-1)
distance = torch.log((1 + k * torch.sum(x * x, -1, keepdim=True)) / (div + EPS) + EPS)
n = x.shape[-1]
z = torch.exp((n - 1) * distance / 2) * torch.cos(distance + b)
out.append(z)
return out
def cal_cl_loss(self, x1, x2):
norm1 = x1.norm(dim=-1)
norm2 = x2.norm(dim=-1)
sim_matrix = torch.einsum('ik,jk->ij', x1, x2) / (torch.einsum('i,j->ij', norm1, norm2) + EPS)
sim_matrix = torch.exp(sim_matrix / self.temperature)
pos_sim = sim_matrix.diag()
loss_1 = pos_sim / (sim_matrix.sum(dim=-2) - pos_sim + EPS)
loss_2 = pos_sim / (sim_matrix.sum(dim=-1) - pos_sim + EPS)
loss_1 = -torch.log(loss_1).mean()
loss_2 = -torch.log(loss_2).mean()
loss = (loss_1 + loss_2) / 2.
return loss
def cal_motif_loss(self, products, pos_motifs, neg_motifs):
embeddings = torch.concat(products, dim=-1)
pos_scores1 = self.decoder(torch.sum((embeddings[pos_motifs[0]] - embeddings[pos_motifs[1]])**2, -1))
pos_scores2 = self.decoder(torch.sum((embeddings[pos_motifs[2]] - embeddings[pos_motifs[1]])**2, -1))
pos_scores3 = self.decoder(torch.sum((embeddings[pos_motifs[2]] - embeddings[pos_motifs[0]])**2, -1))
neg_scores1 = self.decoder(torch.sum((embeddings[neg_motifs[0]] - embeddings[neg_motifs[1]])**2, -1))
neg_scores2 = self.decoder(torch.sum((embeddings[neg_motifs[2]] - embeddings[neg_motifs[1]])**2, -1))
neg_scores3 = self.decoder(torch.sum((embeddings[neg_motifs[2]] - embeddings[neg_motifs[0]])**2, -1))
pos1 = pos_scores1 * pos_scores2 * (1 - pos_scores3)
pos2 = pos_scores1 * pos_scores2 * pos_scores3
pos0 = 1 - pos1 - pos2
pos = torch.stack([pos0, pos1, pos2], dim=1)
p_y = pos_motifs[-1].detach() + 1
neg1 = neg_scores1 * neg_scores2 * (1 - neg_scores3)
neg2 = neg_scores1 * neg_scores2 * neg_scores3
neg0 = 1 - neg1 - neg2
neg = torch.stack([neg0, neg1, neg2], dim=1)
n_y = torch.zeros_like(p_y)
probs = torch.concat([pos, neg], dim=0)
label = torch.concat([p_y, n_y])
loss = F.nll_loss(torch.log(probs + 1e-5), label)
return loss
class FermiDiracDecoder(nn.Module):
def __init__(self, r, t):
super(FermiDiracDecoder, self).__init__()
self.r = r
self.t = t
def forward(self, dist):
probs = torch.sigmoid((self.r - dist) / self.t)
return probs