L4_message_passing.py 12.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
"""
Writing GNN Modules for Stochastic GNN Training
===============================================

All GNN modules DGL provides support stochastic GNN training. This
tutorial teaches you how to write your own graph neural network module
for stochastic GNN training. It assumes that

1. You know :doc:`how to write GNN modules for full graph
10
   training <../blitz/3_message_passing>`.
11
12
13
14
15
2. You know :doc:`how stochastic GNN training pipeline
   works <L1_large_node_classification>`.

"""

16
import os
17
18

os.environ["DGLBACKEND"] = "pytorch"
19
20
import dgl
import numpy as np
21
import torch
22
23
from ogb.nodeproppred import DglNodePropPredDataset

24
25
dataset = DglNodePropPredDataset("ogbn-arxiv")
device = "cpu"  # change to 'cuda' for GPU
26
27

graph, node_labels = dataset[0]
28
29
# Add reverse edges since ogbn-arxiv is unidirectional.
graph = dgl.add_reverse_edges(graph)
30
graph.ndata["label"] = node_labels[:, 0]
31
idx_split = dataset.get_idx_split()
32
33
train_nids = idx_split["train"]
node_features = graph.ndata["feat"]
34
35

sampler = dgl.dataloading.MultiLayerNeighborSampler([4, 4])
36
train_dataloader = dgl.dataloading.DataLoader(
37
38
39
    graph,
    train_nids,
    sampler,
40
41
42
    batch_size=1024,
    shuffle=True,
    drop_last=False,
43
    num_workers=0,
44
45
)

46
input_nodes, output_nodes, mfgs = next(iter(train_dataloader))
47
48
49
50
51
52


######################################################################
# DGL Bipartite Graph Introduction
# --------------------------------
#
53
54
55
# In the previous tutorials, you have seen the concept *message flow graph*
# (MFG), where nodes are divided into two parts.  It is a kind of (directional)
# bipartite graph.
56
57
58
# This section introduces how you can manipulate (directional) bipartite
# graphs.
#
59
# You can access the source node features and destination node features via
60
61
62
# ``srcdata`` and ``dstdata`` attributes:
#

63
64
65
mfg = mfgs[0]
print(mfg.srcdata)
print(mfg.dstdata)
66
67
68
69


######################################################################
# It also has ``num_src_nodes`` and ``num_dst_nodes`` functions to query
70
# how many source nodes and destination nodes exist in the bipartite graph:
71
72
#

73
print(mfg.num_src_nodes(), mfg.num_dst_nodes())
74
75
76
77
78
79
80


######################################################################
# You can assign features to ``srcdata`` and ``dstdata`` just as what you
# will do with ``ndata`` on the graphs you have seen earlier:
#

81
82
mfg.srcdata["x"] = torch.zeros(mfg.num_src_nodes(), mfg.num_dst_nodes())
dst_feat = mfg.dstdata["feat"]
83
84
85
86


######################################################################
# Also, since the bipartite graphs are constructed by DGL, you can
87
88
# retrieve the source node IDs (i.e. those that are required to compute the
# output) and destination node IDs (i.e. those whose representations the
89
90
91
# current GNN layer should compute) as follows.
#

92
mfg.srcdata[dgl.NID], mfg.dstdata[dgl.NID]
93
94
95
96
97
98
99
100
101


######################################################################
# Writing GNN Modules for Bipartite Graphs for Stochastic Training
# ----------------------------------------------------------------
#


######################################################################
102
103
# Recall that the MFGs yielded by the ``DataLoader``
# have the property that the first few source nodes are
104
# always identical to the destination nodes:
105
106
107
108
109
110
#
# |image1|
#
# .. |image1| image:: https://data.dgl.ai/tutorial/img/bipartite.gif
#

111
112
113
114
115
print(
    torch.equal(
        mfg.srcdata[dgl.NID][: mfg.num_dst_nodes()], mfg.dstdata[dgl.NID]
    )
)
116
117
118


######################################################################
119
# Suppose you have obtained the source node representations
120
121
122
# :math:`h_u^{(l-1)}`:
#

123
mfg.srcdata["h"] = torch.randn(mfg.num_src_nodes(), 10)
124
125
126
127
128


######################################################################
# Recall that DGL provides the `update_all` interface for expressing how
# to compute messages and how to aggregate them on the nodes that receive
129
# them. This concept naturally applies to bipartite graphs like MFGs -- message
130
131
132
133
134
135
136
137
138
139
140
141
# computation happens on the edges between source and destination nodes of
# the edges, and message aggregation happens on the destination nodes.
#
# For example, suppose the message function copies the source feature
# (i.e. :math:`M^{(l)}\left(h_v^{(l-1)}, h_u^{(l-1)}, e_{u\to v}^{(l-1)}\right) = h_v^{(l-1)}`),
# and the reduce function averages the received messages.  Performing
# such message passing computation on a bipartite graph is no different than
# on a full graph:
#

import dgl.function as fn

142
143
mfg.update_all(message_func=fn.copy_u("h", "m"), reduce_func=fn.mean("m", "h"))
m_v = mfg.dstdata["h"]
144
145
146
147
148
149
m_v


######################################################################
# Putting them together, you can implement a GraphSAGE convolution for
# training with neighbor sampling as follows (the differences to the :doc:`full graph
150
# counterpart <../blitz/3_message_passing>` are highlighted with arrows ``<---``)
151
152
153
154
155
156
#

import torch.nn as nn
import torch.nn.functional as F
import tqdm

157

158
159
160
161
162
163
164
165
166
167
class SAGEConv(nn.Module):
    """Graph convolution module used by the GraphSAGE model.

    Parameters
    ----------
    in_feat : int
        Input feature size.
    out_feat : int
        Output feature size.
    """
168

169
170
171
172
173
174
175
176
177
178
179
    def __init__(self, in_feat, out_feat):
        super(SAGEConv, self).__init__()
        # A linear submodule for projecting the input and neighbor feature to the output.
        self.linear = nn.Linear(in_feat * 2, out_feat)

    def forward(self, g, h):
        """Forward computation

        Parameters
        ----------
        g : Graph
180
            The input MFG.
181
        h : (Tensor, Tensor)
182
            The feature of source nodes and destination nodes as a pair of Tensors.
183
184
185
        """
        with g.local_scope():
            h_src, h_dst = h
186
187
            g.srcdata["h"] = h_src  # <---
            g.dstdata["h"] = h_dst  # <---
188
            # update_all is a message passing API.
189
190
191
            g.update_all(fn.copy_u("h", "m"), fn.mean("m", "h_N"))
            h_N = g.dstdata["h_N"]
            h_total = torch.cat([h_dst, h_N], dim=1)  # <---
192
193
            return self.linear(h_total)

194

195
196
197
198
199
200
class Model(nn.Module):
    def __init__(self, in_feats, h_feats, num_classes):
        super(Model, self).__init__()
        self.conv1 = SAGEConv(in_feats, h_feats)
        self.conv2 = SAGEConv(h_feats, num_classes)

201
    def forward(self, mfgs, x):
202
        h_dst = x[: mfgs[0].num_dst_nodes()]
203
        h = self.conv1(mfgs[0], (x, h_dst))
204
        h = F.relu(h)
205
        h_dst = h[: mfgs[1].num_dst_nodes()]
206
        h = self.conv2(mfgs[1], (h, h_dst))
207
208
        return h

209

210
sampler = dgl.dataloading.MultiLayerNeighborSampler([4, 4])
211
train_dataloader = dgl.dataloading.DataLoader(
212
213
214
    graph,
    train_nids,
    sampler,
215
    device=device,
216
217
218
    batch_size=1024,
    shuffle=True,
    drop_last=False,
219
    num_workers=0,
220
)
221
model = Model(graph.ndata["feat"].shape[1], 128, dataset.num_classes).to(device)
222
223

with tqdm.tqdm(train_dataloader) as tq:
224
    for step, (input_nodes, output_nodes, mfgs) in enumerate(tq):
225
226
        inputs = mfgs[0].srcdata["feat"]
        labels = mfgs[-1].dstdata["label"]
227
        predictions = model(mfgs, inputs)
228
229
230
231


######################################################################
# Both ``update_all`` and the functions in ``nn.functional`` namespace
232
# support MFGs, so you can migrate the code working for small
233
234
235
236
237
238
239
240
241
# graphs to large graph training with minimal changes introduced above.
#


######################################################################
# Writing GNN Modules for Both Full-graph Training and Stochastic Training
# ------------------------------------------------------------------------
#
# Here is a step-by-step tutorial for writing a GNN module for both
242
# :doc:`full-graph training <../blitz/1_introduction>` *and* :doc:`stochastic
243
# training <L1_large_node_classification>`.
244
245
246
247
#
# Say you start with a GNN module that works for full-graph training only:
#

248

249
250
251
252
253
254
255
256
257
258
class SAGEConv(nn.Module):
    """Graph convolution module used by the GraphSAGE model.

    Parameters
    ----------
    in_feat : int
        Input feature size.
    out_feat : int
        Output feature size.
    """
259

260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
    def __init__(self, in_feat, out_feat):
        super().__init__()
        # A linear submodule for projecting the input and neighbor feature to the output.
        self.linear = nn.Linear(in_feat * 2, out_feat)

    def forward(self, g, h):
        """Forward computation

        Parameters
        ----------
        g : Graph
            The input graph.
        h : Tensor
            The input node feature.
        """
        with g.local_scope():
276
            g.ndata["h"] = h
277
            # update_all is a message passing API.
278
279
280
281
282
            g.update_all(
                message_func=fn.copy_u("h", "m"),
                reduce_func=fn.mean("m", "h_N"),
            )
            h_N = g.ndata["h_N"]
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
            h_total = torch.cat([h, h_N], dim=1)
            return self.linear(h_total)


######################################################################
# **First step**: Check whether the input feature is a single tensor or a
# pair of tensors:
#
# .. code:: python
#
#    if isinstance(h, tuple):
#        h_src, h_dst = h
#    else:
#        h_src = h_dst = h
#
# **Second step**: Replace node features ``h`` with ``h_src`` or
# ``h_dst``, and assign the node features to ``srcdata`` or ``dstdata``,
# instead of ``ndata``.
#
# Whether to assign to ``srcdata`` or ``dstdata`` depends on whether the
# said feature acts as the features on source nodes or destination nodes
# of the edges in the message functions (in ``update_all`` or
# ``apply_edges``).
#
# *Example 1*: For the following ``update_all`` statement:
#
# .. code:: python
#
#    g.ndata['h'] = h
#    g.update_all(message_func=fn.copy_u('h', 'm'), reduce_func=fn.mean('m', 'h_N'))
#
# The node feature ``h`` acts as source node feature because ``'h'``
# appeared as source node feature. So you will need to replace ``h`` with
# source feature ``h_src`` and assign to ``srcdata`` for the version that
# works with both cases:
#
# .. code:: python
#
#    g.srcdata['h'] = h_src
#    g.update_all(message_func=fn.copy_u('h', 'm'), reduce_func=fn.mean('m', 'h_N'))
#
# *Example 2*: For the following ``apply_edges`` statement:
#
# .. code:: python
#
#    g.ndata['h'] = h
#    g.apply_edges(fn.u_dot_v('h', 'h', 'score'))
#
# The node feature ``h`` acts as both source node feature and destination
# node feature. So you will assign ``h_src`` to ``srcdata`` and ``h_dst``
# to ``dstdata``:
#
# .. code:: python
#
#    g.srcdata['h'] = h_src
#    g.dstdata['h'] = h_dst
#    # The first 'h' corresponds to source feature (u) while the second 'h' corresponds to destination feature (v).
#    g.apply_edges(fn.u_dot_v('h', 'h', 'score'))
#
# .. note::
#
#    For homogeneous graphs (i.e. graphs with only one node type
#    and one edge type), ``srcdata`` and ``dstdata`` are aliases of
#    ``ndata``. So you can safely replace ``ndata`` with ``srcdata`` and
#    ``dstdata`` even for full-graph training.
#
# **Third step**: Replace the ``ndata`` for outputs with ``dstdata``.
#
# For example, the following code
#
# .. code:: python
#
#    # Assume that update_all() function has been called with output node features in `h_N`.
#    h_N = g.ndata['h_N']
#    h_total = torch.cat([h, h_N], dim=1)
#
# will change to
#
# .. code:: python
#
#    h_N = g.dstdata['h_N']
#    h_total = torch.cat([h_dst, h_N], dim=1)
#


######################################################################
# Putting together, you will change the ``SAGEConvForBoth`` module above
# to something like the following:
#

373

374
375
376
377
378
379
380
381
382
383
class SAGEConvForBoth(nn.Module):
    """Graph convolution module used by the GraphSAGE model.

    Parameters
    ----------
    in_feat : int
        Input feature size.
    out_feat : int
        Output feature size.
    """
384

385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
    def __init__(self, in_feat, out_feat):
        super().__init__()
        # A linear submodule for projecting the input and neighbor feature to the output.
        self.linear = nn.Linear(in_feat * 2, out_feat)

    def forward(self, g, h):
        """Forward computation

        Parameters
        ----------
        g : Graph
            The input graph.
        h : Tensor or tuple[Tensor, Tensor]
            The input node feature.
        """
        with g.local_scope():
            if isinstance(h, tuple):
                h_src, h_dst = h
            else:
                h_src = h_dst = h

406
            g.srcdata["h"] = h_src
407
            # update_all is a message passing API.
408
409
410
411
412
            g.update_all(
                message_func=fn.copy_u("h", "m"),
                reduce_func=fn.mean("m", "h_N"),
            )
            h_N = g.ndata["h_N"]
413
414
415
            h_total = torch.cat([h_dst, h_N], dim=1)
            return self.linear(h_total)

416

417
# Thumbnail credits: Representation Learning on Networks, Jure Leskovec, WWW 2018
418
# sphinx_gallery_thumbnail_path = '_static/blitz_3_message_passing.png'