-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy pathmessage_passing.py
167 lines (136 loc) · 5.17 KB
/
message_passing.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
import tensorlayerx as tlx
from gammagl.mpops import *
from gammagl.utils import Inspector
class MessagePassing(tlx.nn.Module):
r"""Base class for creating message passing layers of the form
.. math::
\mathbf{x}_i^{\prime} = \gamma_{\mathbf{\Theta}} \left( \mathbf{x}_i,
\square_{j \in \mathcal{N}(i)} \, \phi_{\mathbf{\Theta}}
\left(\mathbf{x}_i, \mathbf{x}_j,\mathbf{e}_{j,i}\right) \right),
where :math:`\square` denotes a differentiable, permutation invariant
function, *e.g.*, sum, mean or max, and :math:`\gamma_{\mathbf{\Theta}}`
and :math:`\phi_{\mathbf{\Theta}}` denote differentiable functions such as
MLPs.
"""
special_args = {
'edge_index', 'x', 'edge_weight'
}
def __init__(self):
super().__init__()
self.inspector = Inspector(self)
self.inspector.inspect(self.message)
self.inspector.inspect(self.message_aggregate)
self.__user_args__ = self.inspector.keys(
['message','message_aggregate']).difference(self.special_args)
def message(self, x, edge_index, edge_weight=None):
"""
Function that construct message from source nodes to destination nodes.
Parameters
----------
x: tensor
input node feature.
edge_index: tensor
edges from src to dst.
edge_weight: tensor, optional
weight of each edge.
Returns
-------
tensor
output message
Returns:
the message matrix, and the shape is [num_edges, message_dim]
"""
msg = tlx.gather(x, edge_index[0, :])
if edge_weight is not None:
edge_weight = tlx.expand_dims(edge_weight, -1)
return msg * edge_weight
else:
return msg
def aggregate(self, msg, edge_index, num_nodes=None, aggr='sum'):
"""
Function that aggregates message from edges to destination nodes.
Parameters
----------
msg: tensor
message construct by message function.
edge_index: tensor
edges from src to dst.
num_nodes: int, optional
number of nodes of the graph.
aggr: str, optional
aggregation type, default = 'sum', optional=['sum', 'mean', 'max'].
Returns
-------
tensor
aggregation outcome.
"""
dst_index = edge_index[1, :]
if aggr == 'sum':
return unsorted_segment_sum(msg, dst_index, num_nodes)
elif aggr == 'mean':
return unsorted_segment_mean(msg, dst_index, num_nodes)
elif aggr == 'max':
return unsorted_segment_max(msg, dst_index, num_nodes)
else:
raise NotImplementedError('Not support for this opearator')
def message_aggregate(self, x, edge_index, edge_weight=None, aggr='sum'):
"""
try to fuse message and aggregate to reduce expensed edge information.
"""
# use_ext is defined in mpops
if use_ext is not None and use_ext:
if edge_weight is None:
edge_weight = torch.ones(edge_index.shape[1],
device=x.device,
dtype=x.dtype)
out = gspmm(edge_index, edge_weight, x, aggr)
else:
msg = self.message(x, edge_index, edge_weight)
out = self.aggregate(msg, edge_index)
return out
def update(self, x):
"""
Function defines how to update node embeddings.
Parameters
----------
x: tensor
aggregated message
"""
return x
def propagate(self, x, edge_index, aggr='sum', **kwargs):
"""
Function that perform message passing.
Parameters
----------
x: tensor
input node feature.
edge_index: tensor
edges from src to dst.
aggr: str, optional
aggregation type, default='sum', optional=['sum', 'mean', 'max'].
fuse_kernel: bool, optional
use fused kernel function to speed up, default = False.
kwargs: optional
other parameters dict.
"""
if 'num_nodes' not in kwargs.keys() or kwargs['num_nodes'] is None:
kwargs['num_nodes'] = x.shape[0]
if tlx.BACKEND == "torch" and 'message_aggregate' in self.__class__.__dict__:
coll_dict = self.__collect__(x, edge_index, aggr, kwargs)
msg_agg_kwargs = self.inspector.distribute('message_aggregate', coll_dict)
x = self.message_aggregate(**msg_agg_kwargs)
else:
coll_dict = self.__collect__(x, edge_index, aggr, kwargs)
msg_kwargs = self.inspector.distribute('message', coll_dict)
msg = self.message(**msg_kwargs)
x = self.aggregate(msg, edge_index, num_nodes=kwargs['num_nodes'], aggr=aggr)
x = self.update(x)
return x
def __collect__(self, x, edge_index, aggr, kwargs):
out = {}
for k, v in kwargs.items():
out[k] = v
out['x'] = x
out['edge_index'] = edge_index
out['aggr'] = aggr
return out