model_sampling.py 8.05 KB
Newer Older
1
import torch as th
2
import torch.nn as nn
3

4
5
6
7
8
9
10
11
12
13
import dgl.function as fn
from dgl.nn.functional import edge_softmax


class MLP(nn.Module):
    def __init__(self, in_dim, out_dim):
        super().__init__()
        self.W = nn.Linear(in_dim, out_dim)

    def apply_edges(self, edges):
14
15
16
        h_e = edges.data["h"]
        h_u = edges.src["h"]
        h_v = edges.dst["h"]
17
        score = self.W(th.cat([h_e, h_u, h_v], -1))
18
        return {"score": score}
19
20
21

    def forward(self, g, e_feat, u_feat, v_feat):
        with g.local_scope():
22
23
24
            g.edges["forward"].data["h"] = e_feat
            g.nodes["u"].data["h"] = u_feat
            g.nodes["v"].data["h"] = v_feat
25
            g.apply_edges(self.apply_edges, etype="forward")
26
            return g.edges["forward"].data["score"]
27
28
29
30
31


class GASConv(nn.Module):
    """One layer of GAS."""

32
33
34
35
36
37
38
39
40
41
42
    def __init__(
        self,
        e_in_dim,
        u_in_dim,
        v_in_dim,
        e_out_dim,
        u_out_dim,
        v_out_dim,
        activation=None,
        dropout=0,
    ):
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
        super(GASConv, self).__init__()

        self.activation = activation
        self.dropout = nn.Dropout(dropout)

        self.e_linear = nn.Linear(e_in_dim, e_out_dim)
        self.u_linear = nn.Linear(u_in_dim, e_out_dim)
        self.v_linear = nn.Linear(v_in_dim, e_out_dim)

        self.W_ATTN_u = nn.Linear(u_in_dim, v_in_dim + e_in_dim)
        self.W_ATTN_v = nn.Linear(v_in_dim, u_in_dim + e_in_dim)

        # the proportion of h_u and h_Nu are specified as 1/2 in formula 8
        nu_dim = int(u_out_dim / 2)
        nv_dim = int(v_out_dim / 2)

        self.W_u = nn.Linear(v_in_dim + e_in_dim, nu_dim)
        self.W_v = nn.Linear(u_in_dim + e_in_dim, nv_dim)

        self.Vu = nn.Linear(u_in_dim, u_out_dim - nu_dim)
        self.Vv = nn.Linear(v_in_dim, v_out_dim - nv_dim)

    def forward(self, g, f_feat, b_feat, u_feat, v_feat):
66
67
68
69
70
71
        g.srcnodes["u"].data["h"] = u_feat
        g.srcnodes["v"].data["h"] = v_feat
        g.dstnodes["u"].data["h"] = u_feat[: g.number_of_dst_nodes(ntype="u")]
        g.dstnodes["v"].data["h"] = v_feat[: g.number_of_dst_nodes(ntype="v")]
        g.edges["forward"].data["h"] = f_feat
        g.edges["backward"].data["h"] = b_feat
72
73

        # formula 3 and 4 (optimized implementation to save memory)
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
        g.srcnodes["u"].data.update(
            {"he_u": self.u_linear(g.srcnodes["u"].data["h"])}
        )
        g.srcnodes["v"].data.update(
            {"he_v": self.v_linear(g.srcnodes["v"].data["h"])}
        )
        g.dstnodes["u"].data.update(
            {"he_u": self.u_linear(g.dstnodes["u"].data["h"])}
        )
        g.dstnodes["v"].data.update(
            {"he_v": self.v_linear(g.dstnodes["v"].data["h"])}
        )
        g.edges["forward"].data.update({"he_e": self.e_linear(f_feat)})
        g.edges["backward"].data.update({"he_e": self.e_linear(b_feat)})
        g.apply_edges(
            lambda edges: {
                "he": edges.data["he_e"] + edges.dst["he_u"] + edges.src["he_v"]
            },
            etype="backward",
        )
        g.apply_edges(
            lambda edges: {
                "he": edges.data["he_e"] + edges.src["he_u"] + edges.dst["he_v"]
            },
            etype="forward",
        )
        hf = g.edges["forward"].data["he"]
        hb = g.edges["backward"].data["he"]
102
103
104
105
106
        if self.activation is not None:
            hf = self.activation(hf)
            hb = self.activation(hb)

        # formula 6
107
108
109
110
111
112
113
114
115
116
117
118
        g.apply_edges(
            lambda edges: {
                "h_ve": th.cat([edges.src["h"], edges.data["h"]], -1)
            },
            etype="backward",
        )
        g.apply_edges(
            lambda edges: {
                "h_ue": th.cat([edges.src["h"], edges.data["h"]], -1)
            },
            etype="forward",
        )
119
120

        # formula 7, self-attention
121
122
123
124
125
126
127
128
129
130
131
132
        g.srcnodes["u"].data["h_att_u"] = self.W_ATTN_u(
            g.srcnodes["u"].data["h"]
        )
        g.srcnodes["v"].data["h_att_v"] = self.W_ATTN_v(
            g.srcnodes["v"].data["h"]
        )
        g.dstnodes["u"].data["h_att_u"] = self.W_ATTN_u(
            g.dstnodes["u"].data["h"]
        )
        g.dstnodes["v"].data["h_att_v"] = self.W_ATTN_v(
            g.dstnodes["v"].data["h"]
        )
133
134

        # Step 1: dot product
135
136
        g.apply_edges(fn.e_dot_v("h_ve", "h_att_u", "edotv"), etype="backward")
        g.apply_edges(fn.e_dot_v("h_ue", "h_att_v", "edotv"), etype="forward")
137
138

        # Step 2. softmax
139
140
141
142
143
144
        g.edges["backward"].data["sfm"] = edge_softmax(
            g["backward"], g.edges["backward"].data["edotv"]
        )
        g.edges["forward"].data["sfm"] = edge_softmax(
            g["forward"], g.edges["forward"].data["edotv"]
        )
145
146

        # Step 3. Broadcast softmax value to each edge, and then attention is done
147
148
149
150
151
152
153
154
        g.apply_edges(
            lambda edges: {"attn": edges.data["h_ve"] * edges.data["sfm"]},
            etype="backward",
        )
        g.apply_edges(
            lambda edges: {"attn": edges.data["h_ue"] * edges.data["sfm"]},
            etype="forward",
        )
155
156

        # Step 4. Aggregate attention to dst,user nodes, so formula 7 is done
157
158
159
160
161
162
        g.update_all(
            fn.copy_e("attn", "m"), fn.sum("m", "agg_u"), etype="backward"
        )
        g.update_all(
            fn.copy_e("attn", "m"), fn.sum("m", "agg_v"), etype="forward"
        )
163
164

        # formula 5
165
166
        h_nu = self.W_u(g.dstnodes["u"].data["agg_u"])
        h_nv = self.W_v(g.dstnodes["v"].data["agg_v"])
167
168
169
170
171
172
173
174
175
176
177
        if self.activation is not None:
            h_nu = self.activation(h_nu)
            h_nv = self.activation(h_nv)

        # Dropout
        hf = self.dropout(hf)
        hb = self.dropout(hb)
        h_nu = self.dropout(h_nu)
        h_nv = self.dropout(h_nv)

        # formula 8
178
179
        hu = th.cat([self.Vu(g.dstnodes["u"].data["h"]), h_nu], -1)
        hv = th.cat([self.Vv(g.dstnodes["v"].data["h"]), h_nv], -1)
180
181
182
183
184

        return hf, hb, hu, hv


class GAS(nn.Module):
185
186
187
188
189
190
191
192
193
194
195
196
197
    def __init__(
        self,
        e_in_dim,
        u_in_dim,
        v_in_dim,
        e_hid_dim,
        u_hid_dim,
        v_hid_dim,
        out_dim,
        num_layers=2,
        dropout=0.0,
        activation=None,
    ):
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
        super(GAS, self).__init__()
        self.e_in_dim = e_in_dim
        self.u_in_dim = u_in_dim
        self.v_in_dim = v_in_dim
        self.e_hid_dim = e_hid_dim
        self.u_hid_dim = u_hid_dim
        self.v_hid_dim = v_hid_dim
        self.out_dim = out_dim
        self.num_layer = num_layers
        self.dropout = dropout
        self.activation = activation
        self.predictor = MLP(e_hid_dim + u_hid_dim + v_hid_dim, out_dim)
        self.layers = nn.ModuleList()

        # Input layer
213
214
215
216
217
218
219
220
221
222
223
224
        self.layers.append(
            GASConv(
                self.e_in_dim,
                self.u_in_dim,
                self.v_in_dim,
                self.e_hid_dim,
                self.u_hid_dim,
                self.v_hid_dim,
                activation=self.activation,
                dropout=self.dropout,
            )
        )
225
226
227

        # Hidden layers with n - 1 CompGraphConv layers
        for i in range(self.num_layer - 1):
228
229
230
231
232
233
234
235
236
237
238
239
            self.layers.append(
                GASConv(
                    self.e_hid_dim,
                    self.u_hid_dim,
                    self.v_hid_dim,
                    self.e_hid_dim,
                    self.u_hid_dim,
                    self.v_hid_dim,
                    activation=self.activation,
                    dropout=self.dropout,
                )
            )
240
241
242
243

    def forward(self, subgraph, blocks, f_feat, b_feat, u_feat, v_feat):
        # Forward of n layers of GAS
        for layer, block in zip(self.layers, blocks):
244
245
246
247
248
249
250
            f_feat, b_feat, u_feat, v_feat = layer(
                block,
                f_feat[: block.num_edges(etype="forward")],
                b_feat[: block.num_edges(etype="backward")],
                u_feat,
                v_feat,
            )
251
252

        # return the result of final prediction layer
253
254
255
256
257
258
        return self.predictor(
            subgraph,
            f_feat[: subgraph.num_edges(etype="forward")],
            u_feat,
            v_feat,
        )