-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph_nets.py
549 lines (489 loc) · 16.5 KB
/
graph_nets.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
"""
Cleaner version of the graph_nets module.
"""
import numpy as np
import torch
import torch.nn.functional as F
from torch.nn import Sequential, Linear, ReLU
from torch.nn import Sigmoid, LayerNorm, Dropout
from torch.nn import BatchNorm1d
try:
from torch_geometric.data import Data
from torch_scatter import scatter_mean
from torch_scatter import scatter_add
except:
from scatter import scatter_mean
from scatter import scatter_add
from utils import Data
# mlp function
def mlp_fn(hidden_layer_sizes, normalize=False):
def mlp(f_in, f_out):
"""
This function returns a Multi-Layer Perceptron with ReLU
non-linearities with num_layers layers and h hidden nodes in each
layer, with f_in input features and f_out output features.
"""
layers = []
f1 = f_in
for i, f2 in enumerate(hidden_layer_sizes):
layers.append(Linear(f1, f2))
if (i == len(hidden_layer_sizes) - 1) and normalize:
layers.append(LayerNorm(f2))
layers.append(ReLU())
f1 = f2
layers.append(Linear(f1, f_out))
# layers.append(ReLU())
# layers.append(LayerNorm(f_out))
return Sequential(*layers)
return mlp
# base aggregation (sum)
class SumAggreg():
def __init__(self):
pass
def __call__(self, x, batch):
return scatter_add(x, batch, dim=0)
# Node and Global models for Deep Sets ++
class DS_NodeModel(torch.nn.Module):
def __init__(self,
f_x,
f_u,
model_fn,
f_x_out=None):
super(DS_NodeModel, self).__init__()
if f_x_out is None:
f_x_out = f_x
self.phi_x = model_fn(f_x + f_u, f_x_out)
def forward(self, x, u, batch):
return self.phi_x(torch.cat([x, u[batch]], 1))
class DS_GlobalModel(torch.nn.Module):
def __init__(self,
f_x,
f_u,
model_fn,
f_u_out=None):
super(DS_GlobalModel, self).__init__()
if f_u_out is None:
f_u_out = f_u
self.phi_u = model_fn(f_x + f_u, f_u_out)
def forward(self, x, u, batch):
x_agg = scatter_add(x, batch, dim=0)
return self.phi_u(torch.cat([x_agg, u], 1))
class DS_GlobalModel_A(torch.nn.Module):
"""
With attention.
"""
def __init__(self,
f_x,
f_u,
h,
model_fn,
f_u_out=None):
super(DS_GlobalModel_A, self).__init__()
if f_u_out is None:
f_u_out = f_u
self.h = h
self.phi_u = model_fn(f_x + f_u, f_u_out)
self.phi_k = Linear(f_x, h)
self.phi_q = Linear(f_u, h)
def forward(self, x, u, batch):
k = self.phi_k(x)
q = self.phi_q(u)[batch]
a = torch.sigmoid(
torch.bmm(k.view(-1, 1, self.h),
q.view(-1, self.h, 1)).squeeze(1))
x_agg = scatter_add(a * x, batch, dim=0)
return self.phi_u(torch.cat([x_agg, u], 1))
# Edge, Node and Global models for GNNs
class EdgeModel(torch.nn.Module):
"""
Concat. Try also Diff ?
"""
def __init__(self,
f_e,
f_x,
f_u,
model_fn,
f_e_out=None):
super(EdgeModel, self).__init__()
if f_e_out is None:
f_e_out = f_e
self.phi_e = model_fn(f_e + 2*f_x + f_u, f_e_out)
def forward(self, src, dest, e, u, batch):
out = torch.cat([src, dest, e, u[batch]], 1)
return self.phi_e(out)
class ResEdgeModel(torch.nn.Module):
"""
Residual edge model.
"""
def __init__(self,
f_e,
f_x,
f_u,
model_fn,
f_e_out=None):
super(ResEdgeModel, self).__init__()
if f_e_out is None:
f_e_out = f_e
self.phi_e = model_fn(f_e + 2*f_x + f_u, f_e_out)
def forward(self, src, dest, e, u, batch):
out = torch.cat([src, dest, e, u[batch]], 1)
return self.phi_e(out) + e
class EdgeModel_NoMem(torch.nn.Module):
"""
Concat. Try also Diff ?
"""
def __init__(self,
f_x,
f_u,
model_fn,
f_e_out=None):
super(EdgeModel_NoMem, self).__init__()
if f_e_out is None:
f_e_out = f_e
self.phi_e = model_fn(2*f_x + f_u, f_e_out)
def forward(self, src, dest, u, batch):
out = torch.cat([src, dest, u[batch]], 1)
return self.phi_e(out)
class NodeModel(torch.nn.Module):
def __init__(self,
f_e,
f_x,
f_u,
model_fn,
f_x_out=None):
if f_x_out is None:
f_x_out = f_x
super(NodeModel, self).__init__()
self.phi_x = model_fn(f_e + f_x + f_u, f_x_out)
def forward(self, x, edge_index, e, u, batch):
if not len(e):
return
src, dest = edge_index
# add nodes with the same dest
e_agg_node = scatter_add(e, dest, dim=0)
out = torch.cat([x, e_agg_node, u[batch]], 1)
return self.phi_x(out)
class NodeModel_A(torch.nn.Module):
def __init__(self,
f_e,
f_x,
f_u,
h,
model_fn,
f_x_out=None):
if f_x_out is None:
f_x_out = f_x
self.h = h
super(NodeModel_A, self).__init__()
self.phi_k = Linear(f_x, h)
self.phi_q = Linear(f_x, h)
self.phi_x = model_fn(f_e + f_x + f_u, f_x_out)
def forward(self, x, edge_index, e, u, batch):
if not len(e):
return
src, dest = edge_index
# attention on edges
k = self.phi_k(x)[src]
q = self.phi_q(x)[dest]
# batch-wise dot product
a = torch.sigmoid(
torch.bmm(k.view(-1, 1, self.h),
q.view(-1, self.h, 1)).squeeze(1))
# add nodes with the same dest
e_agg_node = scatter_add(a * e, dest, dim=0)
out = torch.cat([x, e_agg_node, u[batch]], 1)
return self.phi_x(out)
class ResNodeModel(torch.nn.Module):
"""
Residual Node Model.
"""
def __init__(self,
f_e,
f_x,
f_u,
model_fn,
f_x_out=None):
if f_x_out is None:
f_x_out = f_x
super(ResNodeModel, self).__init__()
self.phi_x = model_fn(f_e + f_x + f_u, f_x_out)
def forward(self, x, edge_index, e, u, batch):
if not len(e):
return
src, dest = edge_index
# add nodes with the same dest
e_agg_node = scatter_add(e, dest, dim=0)
out = torch.cat([x, e_agg_node, u[batch]], 1)
return self.phi_x(out) + x
class GlobalModel(torch.nn.Module):
def __init__(self,
f_e,
f_x,
f_u,
model_fn,
f_u_out=None):
super(GlobalModel, self).__init__()
if f_u_out is None:
f_u_out = f_u
self.phi_u = model_fn(f_e + f_x + f_u, f_u_out)
def forward(self, x, edge_index, e, u, batch):
src, dest = edge_index
# compute the batch index for all edges
e_batch = batch[src]
# aggregate all edges in the graph
e_agg = scatter_add(e, e_batch, dim=0)
# aggregate all nodes in the graph
x_agg = scatter_add(x, batch, dim=0)
out = torch.cat([x_agg, e_agg, u], 1)
return self.phi_u(out)
class GlobalModel_A(torch.nn.Module):
def __init__(self,
f_e,
f_x,
f_u,
h,
model_fn,
f_u_out=None):
super(GlobalModel_A, self).__init__()
if f_u_out is None:
f_u_out = f_u
self.h = h
self.phi_u = model_fn(f_e + f_x + f_u, f_u_out)
self.phi_k_e = Linear(f_e, h)
self.phi_q_e = Linear(f_u, h)
self.phi_k_x = Linear(f_x, h)
self.phi_q_x = Linear(f_u, h)
def forward(self, x, edge_index, e, u, batch):
src, dest = edge_index
# compute the batch index for all edges
e_batch = batch[src]
# TODO : edge attention
k = self.phi_k_e(e)
q = self.phi_q_e(u)[e_batch]
a_e = torch.sigmoid(
torch.bmm(k.view(-1, 1, self.h),
q.view(-1, self.h, 1)).squeeze(1))
# aggregate all edges in the graph
e_agg = scatter_add(a_e * e, e_batch, dim=0)
# TODO : node attention
k = self.phi_k_x(x)
q = self.phi_q_x(u)[batch]
x_a = torch.sigmoid(
torch.bmm(k.view(-1, 1, self.h),
q.view(-1, self.h, 1)).squeeze(1))
# aggregate all nodes in the graph
x_agg = scatter_add(x_a * x, batch, dim=0)
out = torch.cat([x_agg, e_agg, u], 1)
return self.phi_u(out)
class ResGlobalModel(torch.nn.Module):
"""
Residual Global Model.
"""
def __init__(self,
f_e,
f_x,
f_u,
model_fn,
f_u_out=None):
super(ResGlobalModel, self).__init__()
if f_u_out is None:
f_u_out = f_u
self.phi_u = model_fn(f_e + f_x + f_u, f_u_out)
def forward(self, x, edge_index, e, u, batch):
src, dest = edge_index
# compute the batch index for all edges
e_batch = batch[src]
# aggregate all edges in the graph
e_agg = scatter_add(e, e_batch, dim=0)
# aggregate all nodes in the graph
x_agg = scatter_add(x, batch, dim=0)
out = torch.cat([x_agg, e_agg, u], 1)
return self.phi_u(out) + u
class GlobalModel_NodeOnly(torch.nn.Module):
def __init__(self,
f_x,
f_u,
model_fn,
f_u_out=None):
super(GlobalModel_NodeOnly, self).__init__()
if f_u_out is None:
f_u_out = f_u
self.phi_u = model_fn(f_x + f_u, f_u_out)
def forward(self, x, edge_index, e, u, batch):
src, dest = edge_index
# aggregate all nodes in the graph
x_agg = scatter_add(x, batch, dim=0)
out = torch.cat([x_agg, u], 1)
return self.phi_u(out)
class GlobalModel_NodeOnly_A(torch.nn.Module):
def __init__(self,
f_x,
f_u,
h,
model_fn,
f_u_out=None):
super(GlobalModel_NodeOnly_A, self).__init__()
if f_u_out is None:
f_u_out = f_u
self.h = h
self.phi_u = model_fn(f_x + f_u, f_u_out)
self.phi_k = Linear(f_x, h)
self.phi_q = Linear(f_u, h)
def forward(self, x, edge_index, e, u, batch):
src, dest = edge_index
# node attention
k = self.phi_k(x)
q = self.phi_q(u)[batch]
a = torch.sigmoid(
torch.bmm(k.view(-1, 1, self.h),
q.view(-1, self.h, 1)).squeeze(1))
# aggregate all nodes in the graph
x_agg = scatter_add(a * x, batch, dim=0)
out = torch.cat([x_agg, u], 1)
return self.phi_u(out)
class ResGlobalModel_NodeOnly(torch.nn.Module):
def __init__(self,
f_x,
f_u,
model_fn,
f_u_out=None):
super(ResGlobalModel_NodeOnly, self).__init__()
if f_u_out is None:
f_u_out = f_u
self.phi_u = model_fn(f_x + f_u, f_u_out)
def forward(self, x, edge_index, e, u, batch):
src, dest = edge_index
# aggregate all nodes in the graph
x_agg = scatter_add(x, batch, dim=0)
out = torch.cat([x_agg, u], 1)
return self.phi_u(out) + u
# GNN Layers
class DeepSet(torch.nn.Module):
"""
Deep Set.
"""
def __init__(self,
mlp_fn,
f_in,
h,
f_out):
super(DeepSet, self).__init__()
self.phi_x = mlp_fn(f_in, h)
self.phi_u = mlp_fn(h, f_out)
def forward(self, x, batch):
x = self.phi_x(x)
u = self.phi_u(scatter_add(x, batch, dim=0))
return u
class DeepSetPlus(torch.nn.Module):
"""
Deep Set++
"""
def __init__(self,
node_model,
global_model):
super(DeepSetPlus, self).__init__()
self.node_model = node_model
self.global_model = global_model
def forward(self, x, u, batch):
x = self.node_model(x, u, batch)
u = self.global_model(x, u, batch)
return x, u
class N_GNN(torch.nn.Module):
"""
GNN layer, with no edge features.
Messages are computed for the edges according to an edge model, but they
are not kept into memory.
"""
def __init__(self, edge_model, node_model, global_model):
super(N_GNN, self).__init__()
self.edge_model = edge_model
self.node_model = node_model
self.global_model = global_model
self.reset_parameters()
def reset_parameters(self):
for item in [self.node_model, self.edge_model, self.global_model]:
if hasattr(item, 'reset_parameters'):
item.reset_parameters()
def forward(self, x, edge_index, u, batch):
src, dest = edge_index
e = self.edge_model(x[src], x[dest], u, batch[src])
x = self.node_model(x, edge_index, e, u, batch)
u = self.global_model(x, edge_index, e, u, batch)
return x, u
class GNN(torch.nn.Module):
"""
GN block.
Based on rusty1s' Metalayer :
https://github.com/rusty1s/pytorch_geometric
"""
def __init__(self, edge_model, node_model, global_model):
super(GNN, self).__init__()
self.edge_model = edge_model
self.node_model = node_model
self.global_model = global_model
self.reset_parameters()
def reset_parameters(self):
for item in [self.node_model, self.edge_model, self.global_model]:
if hasattr(item, 'reset_parameters'):
item.reset_parameters()
def forward(self, x, edge_index, e, u, batch):
src, dest = edge_index
e = self.edge_model(x[src], x[dest], e, u, batch[src])
x = self.node_model(x, edge_index, e, u, batch)
u = self.global_model(x, edge_index, e, u, batch)
return x, e, u
def __repr__(self):
return ('{}(\n'
' edge_model={},\n'
' node_model={},\n'
' global_model={}\n'
')').format(self.__class__.__name__, self.edge_model,
self.node_model, self.global_model)
class SelfAttention(torch.nn.Module):
"""
"""
def __init__(self, f_in, h_dim):
super(SelfAttention, self).__init__()
self.h = h_dim
self.phi_q = Linear(f_in, h_dim)
self.phi_k = Linear(f_in, h_dim)
self.phi_v = Linear(f_in, h_dim)
# self.phi_x = Linear(h_dim, f_in) # to map back on x's n_dims
# no normalization ?
def forward(self, x, edge_index, batch):
# e_i makes sure all that what happens in a batch stays in a batch
# we need self loops for this model
src, dest = edge_index
q = self.phi_q(x)[dest]
k = self.phi_k(x)[src]
v = self.phi_v(x)[src]
prod = torch.bmm(k.view(-1, 1, self.h), q.view(-1, self.h, 1))
prod = prod.squeeze(1)
prod /= np.sqrt(self.h)
# softmax
exp = torch.exp(prod)
a = exp / (scatter_add(exp, batch[src], dim=0)[batch[src]] + 10e-7)
# a = torch.sigmoid(prod) # softmax here !!!
v = v * a # attention weighting
x = scatter_add(v, dest, dim=0)
return x
class MultiHeadAttention(torch.nn.Module):
"""
Multi-head attention layer.
Not an optimal implem, the heads don't run in parallel, fix this one day.
"""
def __init__(self, f_in, n_heads, h_dim):
super(MultiHeadAttention, self).__init__()
self.modlist = torch.nn.ModuleList() # to hold the heads
for _ in range(n_heads):
self.modlist.append(SelfAttention(f_in, h_dim))
self.phi_x = Linear(n_heads * h_dim, f_in)
# maybe add a normalization layer, and a residual connexion
def forward(self, x, edge_index, batch):
tlist = []
for mod in self.modlist:
tlist.append(mod(x, edge_index, batch))
for t in tlist:
print(t.shape)
x = torch.cat(tlist, 1) # residual connexion
return self.phi_x(x)