-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgnn.py
1631 lines (1359 loc) · 55.8 KB
/
gnn.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import absolute_import
from __future__ import print_function
from util import layer_norm_1d, lookup_activation_fn
import util
import functools
import copy
import tensorflow as tf
from tensorflow import keras
DOT = functools.partial(tf.linalg.tensordot, axes=1)
GNN_SPARSE = "sparse"
GNN_DENSE = "dense"
GNN_DISABLE = "disable"
ATTENTION_SOFTMAX = "softmax"
ATTENTION_SIGMOID = "sigmoid"
ATTENTION_UNIFORM = "uniform"
MESSENGER_BINARY = "binary"
MESSENGER_UNARY = "unary"
COMBINER_LSTM = "lstm"
COMBINER_GRU = "gru"
COMBINER_ADD = "add"
# READOUT_MEAN = "mean"
# READOUT_MAX = "max"
READOUT_DISABLE = "disable"
READOUT_MEAN_MAX = "mean_max"
class MultiHeadAttConfig(object):
def __init__(self, num_heads, dim_input, dim_key, dim_value,
dim_node_attr=None, dim_edge_attr=None,
dim_global_state=None,
impl=GNN_SPARSE, attention=ATTENTION_SOFTMAX,
messenger=MESSENGER_BINARY,
layer_norm_in=True, layer_norm_out=False,
skip_conn=False, feed_forward=False,
activation="linear",
parallel_iterations=10, swap_memory=False):
self._num_heads = num_heads
self._dim_input = dim_input
self._dim_key = dim_key
self._dim_value = dim_value
self._dim_node_attr = 0 if dim_node_attr is None else dim_node_attr
self._dim_edge_attr = 0 if dim_edge_attr is None else dim_edge_attr
self._dim_global_state = 0 \
if dim_global_state is None else dim_global_state
self._impl = impl
self._attention = attention
self._messenger = messenger
self._layer_norm_in = layer_norm_in
self._layer_norm_out = layer_norm_out
self._skip_conn = skip_conn
self._activation = activation
self._feed_forward = feed_forward
self._feed_forward_act = activation
self._parallel_iterations = parallel_iterations
self._swap_memory = swap_memory
def clone(self):
return copy.deepcopy(self)
@property
def num_heads(self):
return self._num_heads
@num_heads.setter
def num_heads(self, value):
self._num_heads = value
@property
def dim_input(self):
return self._dim_input
@dim_input.setter
def dim_input(self, value):
self._dim_input = value
@property
def dim_key(self):
return self._dim_key
@dim_key.setter
def dim_key(self, value):
self._dim_key = value
@property
def dim_value(self):
return self._dim_value
@dim_value.setter
def dim_value(self, value):
self._dim_value = value
@property
def dim_node_attr(self):
return self._dim_node_attr
@property
def dim_edge_attr(self):
return self._dim_edge_attr
@property
def dim_global_state(self):
return self._dim_global_state
@dim_global_state.setter
def dim_global_state(self, value):
self._dim_global_state = value
@property
def impl(self):
return self._impl
@property
def attention(self):
return self._attention
@attention.setter
def attention(self, value):
self._attention = value
@property
def messenger(self):
return self._messenger
@messenger.setter
def messenger(self, value):
self._messenger = value
@property
def layer_norm_in(self):
return self._layer_norm_in
@layer_norm_in.setter
def layer_norm_in(self, value):
self._layer_norm_in = value
@property
def layer_norm_out(self):
return self._layer_norm_out
@layer_norm_out.setter
def layer_norm_out(self, value):
self._layer_norm_out = value
@property
def skip_conn(self):
return self._skip_conn
@skip_conn.setter
def skip_conn(self, value):
self._skip_conn = value
@property
def activation(self):
return self._activation
@activation.setter
def activation(self, value):
self._activation = value
@property
def feed_forward(self):
return self._feed_forward
@feed_forward.setter
def feed_forward(self, value):
self._feed_forward = value
@property
def feed_forward_act(self):
return self._feed_forward_act
@feed_forward_act.setter
def feed_forward_act(self, value):
self._feed_forward_act = value
@property
def parallel_iterations(self):
return self._parallel_iterations
@property
def swap_memory(self):
return self._swap_memory
class GNNConfig(MultiHeadAttConfig):
def __init__(self, *args,
num_layers=2, recurrent=False,
combiner=COMBINER_LSTM, rnn_num_layers=1,
readout=None, **kwargs):
super(GNNConfig, self).__init__(*args, **kwargs)
assert (combiner != COMBINER_ADD) or (num_layers == 1)
self._num_layers = num_layers
self._combiner = combiner
self._rnn_num_layers = rnn_num_layers
self._recurrent = recurrent
self._readout = READOUT_DISABLE if readout is None else readout
def clone(self):
return copy.deepcopy(self)
@property
def num_layers(self):
return self._num_layers
@num_layers.setter
def num_layers(self, value):
self._num_layers = value
@property
def recurrent(self):
return self._recurrent
@property
def combiner(self):
return self._combiner
@combiner.setter
def combiner(self, value):
self._combiner = value
@property
def readout(self):
return self._readout
@readout.setter
def readout(self, value):
self._readout = value or READOUT_DISABLE
@property
def dim_readout(self):
if self.readout == READOUT_MEAN_MAX:
return self.dim_input
elif self.readout == READOUT_DISABLE:
return 0
raise ValueError("Unknown readout function: " + self.readout)
@property
def rnn_num_layers(self):
return self._rnn_num_layers
@property
def dim_full_state(self):
if self.combiner == COMBINER_LSTM:
return 2 * self.rnn_num_layers * self.dim_input
elif self.combiner == COMBINER_GRU:
return self.rnn_num_layers * self.dim_input
return self.dim_input
@property
def single_layer(self):
return super(GNNConfig, self).clone()
###########################################################
# Attention Methods #
###########################################################
def _sparse_attention_softmax_fast(config, graph, similarities,
reverse_mask=None):
'''
Normalize the similarities with softmax.
Only work in the `graph signal` mode, i.e., the graphs
in a mini-batch are identical.
Args:
similarities: A (..., B, E) Tensor.
reverse_mask: Optional. A ([..., ]B, E) Tensor.
Returns:
normalized_weights: A (..., B, E) Tensor.
'''
full_prefix = tf.shape(similarities)[:-1]
similarities = tf.math.add(similarities, tf.math.multiply(
util.SOFTMAX_MASK_MULTIPLIER, (1.0 - graph.edge_mask)
))
if reverse_mask is not None:
similarities = tf.math.add(similarities, tf.math.multiply(
util.SOFTMAX_MASK_MULTIPLIER, util.float(reverse_mask)
))
# [N1, N2, NB] -> [0, N1, N1+N2, ...]
# (B) -> (B, 1) +-> (B, E)
offsets = tf.math.cumsum(graph.num_nodes, exclusive=True)
offsets = tf.math.add(
tf.expand_dims(offsets, axis=-1),
tf.zeros(tf.shape(graph.edges)[:-1], dtype=tf.int32)
)
# (...) -> (F)
extra_batch_size = tf.math.reduce_prod(full_prefix[:-1])
extra_offsets = tf.math.multiply(
tf.range(extra_batch_size), graph.total_num_nodes
)
# (B, E) + (F, 1, 1) -> (F, B, E)
# + (B, E) -> (F, B, E)
offsets = tf.math.add(offsets, util.append_dims(extra_offsets, 2))
relabeled_receivers = tf.math.add(offsets, graph.edges[..., 1])
# (..., B, E) -> (... * B * E)
flat_similarities = tf.reshape(similarities, [-1])
flat_segment_ids = tf.reshape(relabeled_receivers, [-1])
flat_normalized_scores = tf.exp(util.unsorted_segment_log_softmax(
logits=flat_similarities, segment_ids=flat_segment_ids,
num_segments=tf.math.multiply(extra_batch_size, graph.total_num_nodes)
))
return tf.reshape(flat_normalized_scores, tf.shape(similarities))
def _sparse_attention_softmax_slow(config, graph, similarities,
reverse_mask=None):
'''
Normalize the similarities with softmax.
- This function works properly even if the graphs
in a mini-batch are different.
- It is very slow on GPU, because TF creates `SparseTensor`s
on CPU.
Args:
similarities: A (..., B, E) Tensor.
reverse_mask: Optional. A ([..., ]B, E) Tensor.
Returns:
normalized_weights: A (..., B, E) Tensor.
'''
full_prefix = tf.shape(similarities)[:-1]
batch_size = full_prefix[-1]
max_num_edges = graph.max_num_edges
if reverse_mask is not None:
similarities = tf.math.add(similarities, tf.math.multiply(
util.SOFTMAX_MASK_MULTIPLIER, util.float(reverse_mask)
))
# (..., B, E) -> (...*B, E)
flat_similarities = tf.reshape(
similarities,
tf.stack([tf.math.reduce_prod(full_prefix), max_num_edges])
)
# (B) -> (..., B) -> (...*B)
batch_ids = tf.math.add(
tf.range(batch_size),
tf.zeros(full_prefix, dtype=tf.int32)
)
flat_batch_ids = tf.reshape(
batch_ids, tf.stack([tf.math.reduce_prod(full_prefix)])
)
def sparse_softmax(params):
batch_similarities, batch_id = params
max_num_edges = tf.shape(batch_similarities)[0]
num_nodes = tf.cast(graph.num_nodes[batch_id], tf.int64)
num_edges = graph.num_edges[batch_id]
adj_shape = tf.stack([num_nodes, num_nodes])
sparse_similarities = tf.SparseTensor(
indices=graph.edges_int64[batch_id][:num_edges],
values=batch_similarities[:num_edges],
dense_shape=adj_shape
)
# For directed graph, the adjacency matrix is indexed by [sid,rid].
# However `sparse.softmax` will normalize weights along the last dim,
# so we first transpose the weight matrix to be indexed by [rid,sid]
# before applying `sparse.softmax`, then transpose the normalized
# matrix back to be indexed by [sid,rid].
sparse_weights = tf.sparse.transpose(
tf.sparse.softmax(tf.sparse.transpose(sparse_similarities))
)
return tf.concat([
sparse_weights.values, tf.zeros(max_num_edges - num_edges)
], axis=-1)
# NOTE:
#
# The `while_loop` in `map_fn` makes this implementation
# not twice-differentiable, because TensorFlow will raise
# "TypeError: Second-order gradient for while loops not supported."
#
flat_normalized_weights = tf.map_fn(
sparse_softmax, (flat_similarities, flat_batch_ids),
dtype=tf.float32,
parallel_iterations=config.parallel_iterations,
swap_memory=config.swap_memory
)
normalized_weights = tf.reshape(
flat_normalized_weights, shape=tf.shape(similarities)
)
return normalized_weights
def _sparse_attention_softmax_slow_alt(config, graph, similarities,
reverse_mask=None):
del config
if reverse_mask is not None:
similarities = tf.math.add(similarities, tf.math.multiply(
util.SOFTMAX_MASK_MULTIPLIER, util.float(reverse_mask)
))
sparse_similarities = graph.dense_edge_weights_to_sparse(similarities)
perm = tf.range(sparse_similarities.shape.ndims)
perm = tf.stack([*tf.unstack(perm[:-2]), perm[-1], perm[-2]])
sparse_normalized_weights = tf.sparse.transpose(tf.sparse.softmax(
tf.sparse.transpose(sparse_similarities, perm)
), perm)
return graph.sparse_edge_weights_to_dense(sparse_normalized_weights)
def _sparse_attention_sigmoid(config, graph, similarities, reverse_mask=None):
del config, reverse_mask
tf.math.multiply(graph.edge_mask, tf.math.sigmoid(similarities))
def _sparse_attention_uniform(config, graph, similarities, reverse_mask=None):
del config
ones = tf.math.multiply(tf.ones_like(similarities), graph.edge_mask)
if reverse_mask is not None: # TODO
ones = tf.math.multiply(ones, (1.0 - util.float(reverse_mask)))
return tf.math.xdivy(ones, graph.tail_indegree)
def _dense_attention_softmax(config, graph, similarities, reverse_mask=None):
'''
Args:
similarities: A (..., B, N, N) Tensor indexed by (sid, rid).
reverse_mask: Optional. A (..., B, N, N) Tensor indexed by (sid, rid).
Returns:
normalized_weights: A (..., B, N, N) Tensor indexed by (rid, sid).
'''
del config
mask = graph.gen_adj_mask_like(
similarities, reverse_mask=reverse_mask, transpose=True
)
# (..., B, N[r], N[s])
#
# MASKED SOFTMAX
#
# Slow Implementation for (N, N):
#
# indices = tf.where(mask)
# compats_sparse = tf.SparseTensor(
# indices, tf.gather_nd(similarities, indices),
# tf.shape(similarities, out_type=tf.int64)
# )
# att_weights_sparse = tf.sparse_softmax(compats_sparse)
# att_weights = tf.sparse.to_dense(att_weights_sparse)
#
# Dirty but Fast Implementation:
#
# e.g., see:
# https://github.com/google-research/bert/blob/master/modeling.py
# https://github.com/tensorflow/tensorflow/issues/11756
#
mask_multiplier = util.float(mask)
reverse_mask_adder = tf.math.multiply(
1.0 - mask_multiplier, tf.constant(util.SOFTMAX_MASK_MULTIPLIER)
)
weights = tf.math.add(similarities, reverse_mask_adder)
normalized_weights = tf.math.softmax(weights, axis=-1)
return tf.math.multiply(mask_multiplier, normalized_weights)
def _dense_attention_sigmoid(config, graph, similarities, reverse_mask=None):
del config
mask = graph.gen_adj_mask_like(
similarities, reverse_mask=reverse_mask, transpose=True
)
mask_multiplier = util.float(mask)
normalized_weights = tf.math.sigmoid(similarities)
return tf.math.multiply(normalized_weights, mask_multiplier)
def _dense_attention_uniform(config, graph, similarities, reverse_mask=None):
del config
mask = graph.gen_adj_mask_like(
similarities, reverse_mask=reverse_mask, transpose=True
)
mask_multiplier = util.float(mask)
uniform_similarities = tf.math.multiply(
tf.ones_like(similarities), mask_multiplier
)
recv_indegree = tf.math.reduce_sum(mask_multiplier, axis=-1)
recv_indegree = tf.expand_dims(recv_indegree, axis=-1)
normalized_weights = tf.div_no_nan(uniform_similarities, recv_indegree)
return normalized_weights
_sparse_attention_methods = {
ATTENTION_SOFTMAX: _sparse_attention_softmax_fast,
ATTENTION_SIGMOID: _sparse_attention_sigmoid,
ATTENTION_UNIFORM: _sparse_attention_uniform
}
_dense_attention_methods = {
ATTENTION_SOFTMAX: _dense_attention_softmax,
ATTENTION_SIGMOID: _dense_attention_sigmoid,
ATTENTION_UNIFORM: _dense_attention_uniform
}
def _lookup_attention_method(config):
methods = _sparse_attention_methods if config.impl == GNN_SPARSE \
else _dense_attention_methods
attention = methods[config.attention]
if attention is None:
raise ValueError("unknown attention method: " + config.attention)
return functools.partial(attention, config)
###########################################################
# Messengers #
###########################################################
class BinaryMessenger(object):
def __init__(self, num_heads,
dim_input, dim_global_state, dim_edge_attr, dim_msg,
activation=tf.tanh, name="BinaryMessenger"):
def var(name, dim_i):
return tf.get_variable(
name, shape=[dim_i, num_heads, dim_msg], trainable=True,
initializer=tf.initializers.glorot_normal()
)
with tf.variable_scope(name):
self._send_to_gate = var("send_to_gate", dim_input)
self._recv_to_gate = var("recv_to_gate", dim_input)
self._send_to_effect = var("send_to_effect", dim_input)
self._recv_to_effect = var("recv_to_effect", dim_input)
self._edge_attr_to_gate = var(
"edge_attr_to_gate", dim_edge_attr)
self._edge_attr_to_effect = var(
"edge_attr_to_effect", dim_edge_attr)
self._global_state_to_gate = var(
"global_state_to_gate", dim_global_state)
self._global_state_to_effect = var(
"global_state_to_effect", dim_global_state)
self._dim_edge_attr = dim_edge_attr
self._dim_global_state = dim_global_state
self._activation = activation
def _transform_edge_attrs(self, edge_attrs, expand_axis, times):
assert (edge_attrs is None) == (self._dim_edge_attr <= 0)
if edge_attrs is None:
return 0.0, 0.0
def expand(x):
for _ in range(times):
x = tf.expand_dims(x, axis=expand_axis)
return x
# (B,E,de) * (de,nh,dm) -> (B,E,nh,dm) -> (B,E,...,nh,dm)
# (B,N,N,de) * (de,nh,dm) -> (B,N,N,nh,dm) -> (...,B,M,N,nh,dm)
return (
expand(DOT(edge_attrs, self._edge_attr_to_gate)),
expand(DOT(edge_attrs, self._edge_attr_to_effect))
)
def _transform_global_states(self, global_states, expand_axis, times):
assert (global_states is None) == (self._dim_global_state <= 0)
if global_states is None:
return 0.0, 0.0
def expand(x):
for _ in range(times):
x = tf.expand_dims(x, axis=expand_axis)
return x
return (
expand(DOT(global_states, self._global_state_to_gate)),
expand(DOT(global_states, self._global_state_to_effect))
)
def compute_message_sparse(self, graph, senders, receivers,
global_states=None):
'''
Args:
senders: A (..., B, N, d) Tensor.
receivers: A (..., B, M, d) Tensor.
global_states: Optional. A (..., B, dg) Tensor.
Returns:
messages: A (..., nh, B, E, dm) Tensor.
'''
with tf.control_dependencies([
tf.assert_equal(tf.shape(senders)[:-2], tf.shape(receivers)[:-2]),
tf.assert_equal(tf.shape(senders)[-1], tf.shape(receivers)[-1])
]):
sids, rids = graph.edges[..., 0], graph.edges[..., 1]
unknown_prefix_length = len(senders.shape.as_list()[:-3])
# (...,B,N,d) * (d,nh,dm) -> (...,B,N,nh,dm) -> (B,N,...,nh,dm)
perm = tf.range(senders.shape.ndims + 1)
# (...,-4,-3,-2,-1) -> (-4,-3,...,-2,-1)
perm = tf.stack([
perm[-4], perm[-3], *tf.unstack(perm[:-4]), perm[-2], perm[-1]
])
as_gate_send = tf.transpose(
DOT(senders, self._send_to_gate), perm)
as_gate_recv = tf.transpose(
DOT(receivers, self._recv_to_gate), perm)
as_effect_send = tf.transpose(
DOT(senders, self._send_to_effect), perm)
as_effect_recv = tf.transpose(
DOT(receivers, self._recv_to_effect), perm)
# (B,N,...,nh,dm) -> (B,E,...,nh,dm)
gate_send = tf.batch_gather(as_gate_send, indices=sids)
effect_send = tf.batch_gather(as_effect_send, indices=sids)
gate_recv = tf.batch_gather(as_gate_recv, indices=rids)
effect_recv = tf.batch_gather(as_effect_recv, indices=rids)
# (B,E,de) -> (B,E,...,nh,dm)
gate_edge, effect_edge = self._transform_edge_attrs(
edge_attrs=graph.edge_attrs,
expand_axis=-3, times=unknown_prefix_length
)
# (...,B,dg) -> (B,...,dg)
if global_states is not None:
perm = tf.range(global_states.shape.ndims)
# (...,-2,-1) -> (-2,...,-1)
perm = tf.stack([perm[-2], *tf.unstack(perm[:-2]), perm[-1]])
global_states = tf.transpose(global_states, perm)
# (B,...,dg) -> (B,...,nh,dm) -> (B,1,...,nh,dm)
gate_global, effect_global = self._transform_global_states(
global_states=global_states, expand_axis=1, times=1
)
gates = tf.math.add(gate_send, gate_recv)
gates = tf.math.add(gates, gate_edge)
gates = tf.math.add(gates, gate_global)
effects = tf.math.add(effect_send, effect_recv)
effects = tf.math.add(effects, effect_edge)
effects = tf.math.add(effects, effect_global)
# (B,E,...,nh,dm) -> (...,nh,B,E,dm)
messages = tf.math.multiply(
tf.math.sigmoid(gates), self._activation(effects)
)
perm = tf.range(messages.shape.ndims)
# (0,1,...,-2,-1) -> (...,-2,0,1,-1)
perm = tf.stack([
*tf.unstack(perm[2:-2]), perm[-2], perm[0], perm[1], perm[-1]
])
messages = tf.transpose(messages, perm)
# (...,nh,B,E,dm) * (B,E,1)
return graph.mask_edge_info(messages, ndims=1)
def compute_message_dense(self, graph, senders, receivers,
global_states=None):
'''
Args:
senders: A (..., B, N, d) Tensor.
receivers: A (..., B, M, d) Tensor.
global_states: Optional. A (..., B, dg) Tensor.
Returns:
pairwise_messages: A (..., B, M, N, nh, dm) Tensor.
'''
with tf.control_dependencies([
tf.assert_equal(tf.shape(senders)[:-2], tf.shape(receivers)[:-2]),
tf.assert_equal(tf.shape(senders)[-1], tf.shape(receivers)[-1])
]):
unknown_prefix_length = len(senders.shape.as_list()[:-3])
batch_shape = tf.shape(senders)[:-2]
num_senders = tf.shape(senders)[-2]
num_receivers = tf.shape(receivers)[-2]
# (...,B,N,d) * (d,nh,dm) -> (...,B,N,nh,dm)
gate_send = DOT(senders, self._send_to_gate)
gate_recv = DOT(receivers, self._recv_to_gate)
effect_send = DOT(senders, self._send_to_effect)
effect_recv = DOT(receivers, self._recv_to_effect)
# (...,B,1,N,nh,dm) -> (...,B,M,N,nh,dm)
multiples_send = tf.stack([
*tf.unstack(tf.ones(tf.size(batch_shape), dtype=tf.int32)),
num_receivers, 1, 1, 1
])
gate_send_expanded = tf.tile(
tf.expand_dims(gate_send, axis=-4), multiples_send
)
effect_send_expanded = tf.tile(
tf.expand_dims(effect_send, axis=-4), multiples_send
)
# (...,B,M,1,nh,dm) -> (...,B,M,N,nh,dm)
multiples_recv = tf.stack([
*tf.unstack(tf.ones(tf.size(batch_shape), dtype=tf.int32)),
1, num_senders, 1, 1
])
gate_recv_expanded = tf.tile(
tf.expand_dims(gate_recv, axis=-3), multiples_recv
)
effect_recv_expanded = tf.tile(
tf.expand_dims(effect_recv, axis=-3), multiples_recv
)
# (B,E,de) -> (...,B,M,N,nh,dm)
gate_edge, effect_edge = self._transform_edge_attrs(
edge_attrs=graph.dense_edge_attrs,
expand_axis=0, times=unknown_prefix_length
)
# (...,B,dg) -> (...,B,nh,dm) -> (...,B,1,1,nh,dm)
gate_global, effect_global = self._transform_global_states(
global_states=global_states, expand_axis=-3, times=2
)
gates = tf.math.add(gate_send_expanded, gate_recv_expanded)
gates = tf.math.add(gates, gate_edge)
gates = tf.math.add(gates, gate_global)
effects = tf.math.add(effect_send_expanded, effect_recv_expanded)
effects = tf.math.add(effects, effect_edge)
effects = tf.math.add(effects, effect_global)
pairwise_messages = tf.math.multiply(
tf.math.sigmoid(gates), self._activation(effects)
)
return pairwise_messages
class UnaryMessenger(object):
def __init__(self, num_heads,
dim_input, dim_global_state, dim_edge_attr, dim_msg,
name="UnaryMessenger"):
del dim_global_state, dim_edge_attr
with tf.variable_scope(name):
self._message_transform = tf.get_variable(
"message_transform",
shape=[dim_input, num_heads, dim_msg], trainable=True,
initializer=tf.initializers.glorot_normal()
)
def compute_message_dense(self, graph, senders, receivers,
global_states=None):
'''
Args:
graph: A RuntimeGraph object.
senders: A (..., B, N, d) Tensor.
receivers: A (..., B, M, d) Tensor.
globals: Optional. A (..., B, dg) Tensor.
Returns:
messages: A (..., nh, B, N, dm) Tensor.
'''
del graph, receivers
# (...,B,N,d) * (d,nh,dv) -> (...,B,N,nh,dv)
messages = DOT(senders, self._message_transform)
# global_bias = 0.0
# if global_states is not None:
# # (...,B,dg) -> (...,B,nh,dv) -> (...,B,1,nh,dv)
# global_bias = DOT(global_states, self._global_state_transform)
# global_bias = tf.expand_dims(global_bias, axis=-3)
# messages = tf.math.add(messages, global_bias)
# (...,B,N,nh,dv) -> (...,nh,B,N,dv)
perm = tf.range(messages.shape.ndims)
# (...,-4,-3,-2,-1) -> (...,-2,-4,-3,-1)
perm = tf.stack([
*tf.unstack(perm[:-4]), perm[-2], perm[-4], perm[-3], perm[-1]
])
return tf.transpose(messages, perm)
def compute_message_sparse(self, graph, senders, receivers,
global_states=None):
'''
Args:
graph: A RuntimeGraph object.
senders: A (..., B, N, d) Tensor.
receivers: A (..., B, M, d) Tensor.
globals: Optional. A (..., B, dg) Tensor.
Returns:
messages: A (..., B, E, nh, dm) Tensor.
'''
del receivers
sids = graph.edges[..., 0]
# (...,B,N,d) * (d,nh,dm) -> (...,B,N,nh,dm) -> (B,N,...,nh,dm)
perm = tf.range(senders.shape.ndims + 1)
# (...,-4,-3,-2,-1) -> (-4,-3,...,-2,-1)
perm = tf.stack([
perm[-4], perm[-3], *tf.unstack(perm[:-4]), perm[-2], perm[-1]
])
values = tf.transpose(DOT(senders, self._message_transform), perm)
# global_bias = 0.0
# if global_states is not None:
# # (...,B,dg) -> (...,B,1,dg)
# global_states = tf.expand_dims(global_states, axis=-2)
# # (...,B,1,nh,dm) -> (B,1,...,nh,dm)
# global_bias = tf.transpose(
# DOT(global_states, self._global_state_transform), perm
# )
# values = tf.math.add(values, global_bias)
# (B,N,...,nh,dm) -> (B,E,...,nh,dm) -> (...,nh,B,E,dm)
messages = tf.batch_gather(values, indices=sids)
# (0,1,...,-2,-1) -> (...,-2,0,1,-1)
perm = tf.range(messages.shape.ndims)
perm = tf.stack([
*tf.unstack(perm[2:-2]), perm[-2], perm[0], perm[1], perm[-1]
])
messages = tf.transpose(messages, perm)
# (...,nh,B,E,dm) * (B,E,1)
mask = tf.expand_dims(graph.edge_mask, axis=-1)
return tf.math.multiply(messages, mask)
def _make_message_fn(config):
''' NOTE: call this function within a variable scope. '''
params = dict(
num_heads=config.num_heads,
dim_input=(
config.dim_input +
config.dim_node_attr + config.dim_global_state
),
dim_global_state=config.dim_global_state,
dim_edge_attr=config.dim_edge_attr,
dim_msg=config.dim_value
)
if config.messenger == MESSENGER_BINARY:
messenger = BinaryMessenger(**params)
elif config.messenger == MESSENGER_UNARY:
messenger = UnaryMessenger(**params)
else:
raise ValueError("unknown messenger: " + config.messenger)
if config.impl == GNN_SPARSE:
return messenger.compute_message_sparse
return messenger.compute_message_dense
###########################################################
# Graph Neural Networks #
###########################################################
def GraphNN(config, dim_out=None, name="GraphNN"):
with tf.variable_scope(name + "Wrapper"):
if config.feed_forward:
feed_forward = util.mlp_two_layers(
dim_in=config.dim_input,
dim_hid=config.num_heads * config.dim_value,
dim_out=(dim_out or config.dim_input),
act_out=config.feed_forward_act,
weight_init='small'
)
else:
feed_forward = tf.identity
if config.impl == GNN_SPARSE:
_call = SparseGraphNN(config, name=name)
elif config.impl == GNN_DENSE:
_call = DenseGraphNN(config, name=name)
elif config.impl == GNN_DISABLE:
_call = DummyGraphNN(config, name=name)
else:
raise ValueError("unknown GNN implementation: " + config.impl)
def call(*args, **kwargs):
states = _call(*args, **kwargs)
return feed_forward(states)
return call
def _concat_global_states(states, global_states):
'''
Args:
states: A (..., N, d) Tensor.
global_states: A (..., dg) Tensor.
Returns:
concat_updates: A (..., N, d+dg) Tensor.
'''
if global_states is None:
return states
return util.broadcast_concat(
states, tf.expand_dims(global_states, axis=-2)
)
def _concat_node_attrs(graph, states, has_node_attr):
assert not (has_node_attr and graph.node_attrs is None)
if has_node_attr:
states = util.broadcast_concat(states, graph.node_attrs)
return states
def _make_layer_norm_fn(config):
''' NOTE: call this function within a variable scope. '''
norm_in, norm_out = tf.identity, tf.identity
if config.layer_norm_in:
norm_in = layer_norm_1d(
config.dim_input, trainable=True,
name="InputLayerNorm"
)
if config.layer_norm_out:
norm_out = layer_norm_1d(
config.dim_input, trainable=True,
name="OutputLayerNorm"
)
return norm_in, norm_out
def _make_skip_conn(config):
def _fn(states, updates):
if not config.skip_conn:
return updates
return tf.math.add(states, updates)
return _fn
def DummyGraphNN(config, name="DummyGraphNN"):
del config, name
def call(graph, states, global_states=None):
return tf.zeros_like(states)
return call
def SparseGraphNN(config, name="SparseGraphNN"):
num_heads = config.num_heads
dim_input = config.dim_input
dim_key = config.dim_key
dim_value = config.dim_value
dim_node_attr = config.dim_node_attr
dim_edge_attr = config.dim_edge_attr
dim_output = dim_input
has_node_attr = (dim_node_attr > 0)
has_edge_attr = (dim_edge_attr > 0)
dim_input += (dim_node_attr + config.dim_global_state)
ATTENTION = _lookup_attention_method(config)
ACTIVATION = lookup_activation_fn(config.activation)
SKIP_CONN = _make_skip_conn(config)
with tf.variable_scope(name):
initializer = tf.initializers.glorot_normal
key_transform = tf.get_variable(
"key_transform", shape=[dim_input, num_heads, dim_key],
initializer=initializer(), trainable=True)
query_transform = tf.get_variable(
"query_transform", shape=[dim_input, num_heads, dim_key],
initializer=initializer(), trainable=True)
edge_attr_transform = tf.get_variable(
"edge_attr_transform", shape=[dim_edge_attr, num_heads],
initializer=initializer(), trainable=True)
inverse_transform = tf.get_variable(
"inverse_transform", shape=[num_heads, dim_value, dim_output],
initializer=initializer(), trainable=True)
head_transform = tf.get_variable(
"head_transform", shape=[dim_input, num_heads],
initializer=initializer(), trainable=True)
MESSAGE = _make_message_fn(config)
LAYER_NORM_I, LAYER_NORM_O = _make_layer_norm_fn(config)
def call(graph, states, global_states=None, reverse_mask=None):
'''
Args:
graph: A RuntimeGraph object.
states: A (..., B, N, d) Tensor.
global_states: Optional. A (..., B, d) Tensor.
reverse_mask: Optional. A ([..., ]B, E) boolean Tensor.
Returns:
updates: A (..., B, N, d) Tensor.
'''
original_states = states
states = LAYER_NORM_I(states)
states = graph.mask_nodal_info(states)