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 how to write GNN modules for full graph training.

  2. You know how stochastic GNN training pipeline works.

import dgl
import torch
import numpy as np
from ogb.nodeproppred import DglNodePropPredDataset

dataset = DglNodePropPredDataset('ogbn-arxiv')
device = 'cpu'      # change to 'cuda' for GPU

graph, node_labels = dataset[0]
# Add reverse edges since ogbn-arxiv is unidirectional.
graph = dgl.add_reverse_edges(graph)
graph.ndata['label'] = node_labels[:, 0]
idx_split = dataset.get_idx_split()
train_nids = idx_split['train']
node_features = graph.ndata['feat']

sampler = dgl.dataloading.MultiLayerNeighborSampler([4, 4])
train_dataloader = dgl.dataloading.NodeDataLoader(
    graph, train_nids, sampler,
    batch_size=1024,
    shuffle=True,
    drop_last=False,
    num_workers=0
)

input_nodes, output_nodes, mfgs = next(iter(train_dataloader))

DGL Bipartite Graph Introduction

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. This section introduces how you can manipulate (directional) bipartite graphs.

You can access the source node features and destination node features via srcdata and dstdata attributes:

mfg = mfgs[0]
print(mfg.srcdata)
print(mfg.dstdata)

Out:

{'year': tensor([[2017],
        [2013],
        [2017],
        ...,
        [2014],
        [2019],
        [2012]]), 'feat': tensor([[-0.1243,  0.0564, -0.0636,  ...,  0.0771,  0.0097, -0.2289],
        [-0.2137,  0.1025, -0.1297,  ...,  0.1248, -0.1140, -0.1200],
        [ 0.0819,  0.1031, -0.2067,  ...,  0.2500,  0.1317, -0.2650],
        ...,
        [-0.0524,  0.1758, -0.4150,  ...,  0.2515, -0.2071, -0.1465],
        [-0.0772, -0.0615, -0.2313,  ...,  0.1328,  0.0204, -0.1375],
        [-0.0373, -0.0699, -0.2236,  ...,  0.1208,  0.0038, -0.1270]]), 'label': tensor([16, 24, 16,  ..., 39, 34, 34]), '_ID': tensor([ 70717, 158453,  72063,  ..., 164902,   7574, 127080])}
{'year': tensor([[2017],
        [2013],
        [2017],
        ...,
        [2011],
        [2012],
        [2012]]), 'feat': tensor([[-0.1243,  0.0564, -0.0636,  ...,  0.0771,  0.0097, -0.2289],
        [-0.2137,  0.1025, -0.1297,  ...,  0.1248, -0.1140, -0.1200],
        [ 0.0819,  0.1031, -0.2067,  ...,  0.2500,  0.1317, -0.2650],
        ...,
        [-0.1813, -0.0049, -0.3169,  ...,  0.1786, -0.1149, -0.1511],
        [-0.0659,  0.1194, -0.2886,  ...,  0.1754, -0.0596, -0.0580],
        [-0.0054,  0.1604, -0.4049,  ...,  0.0084, -0.1506, -0.0120]]), 'label': tensor([16, 24, 16,  ..., 34,  4, 34]), '_ID': tensor([ 70717, 158453,  72063,  ...,  67291, 121364,  25245])}

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

print(mfg.num_src_nodes(), mfg.num_dst_nodes())

Out:

12771 4098

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

mfg.srcdata['x'] = torch.zeros(mfg.num_src_nodes(), mfg.num_dst_nodes())
dst_feat = mfg.dstdata['feat']

Also, since the bipartite graphs are constructed by DGL, you can 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 current GNN layer should compute) as follows.

mfg.srcdata[dgl.NID], mfg.dstdata[dgl.NID]

Out:

(tensor([ 70717, 158453,  72063,  ..., 164902,   7574, 127080]), tensor([ 70717, 158453,  72063,  ...,  67291, 121364,  25245]))

Writing GNN Modules for Bipartite Graphs for Stochastic Training

Recall that the MFGs yielded by the NodeDataLoader and EdgeDataLoader have the property that the first few source nodes are always identical to the destination nodes:

image1

print(torch.equal(mfg.srcdata[dgl.NID][:mfg.num_dst_nodes()], mfg.dstdata[dgl.NID]))

Out:

True

Suppose you have obtained the source node representations \(h_u^{(l-1)}\):

mfg.srcdata['h'] = torch.randn(mfg.num_src_nodes(), 10)

Recall that DGL provides the update_all interface for expressing how to compute messages and how to aggregate them on the nodes that receive them. This concept naturally applies to bipartite graphs like MFGs – message 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. \(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

mfg.update_all(message_func=fn.copy_u('h', 'm'), reduce_func=fn.mean('m', 'h'))
m_v = mfg.dstdata['h']
m_v

Out:

tensor([[-0.1069, -0.1813,  0.8276,  ...,  0.3448,  0.8792, -0.1596],
        [-0.1256,  0.5387,  0.9050,  ...,  0.0917, -0.9336, -0.1189],
        [ 0.9537,  0.1331,  1.2356,  ..., -0.5304,  0.2408, -0.2508],
        ...,
        [-0.2423,  0.3248, -0.2086,  ...,  0.2425, -0.2101, -0.4076],
        [ 0.0241,  0.0950,  0.1874,  ...,  0.6348, -0.5709,  0.3367],
        [-0.1066, -1.1433, -0.6080,  ..., -0.1888, -0.3495,  0.0321]])

Putting them together, you can implement a GraphSAGE convolution for training with neighbor sampling as follows (the differences to the full graph counterpart are highlighted with arrows <---)

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

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.
    """
    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
            The input MFG.
        h : (Tensor, Tensor)
            The feature of source nodes and destination nodes as a pair of Tensors.
        """
        with g.local_scope():
            h_src, h_dst = h
            g.srcdata['h'] = h_src                        # <---
            g.dstdata['h'] = h_dst                        # <---
            # update_all is a message passing API.
            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)      # <---
            return self.linear(h_total)

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)

    def forward(self, mfgs, x):
        h_dst = x[:mfgs[0].num_dst_nodes()]
        h = self.conv1(mfgs[0], (x, h_dst))
        h = F.relu(h)
        h_dst = h[:mfgs[1].num_dst_nodes()]
        h = self.conv2(mfgs[1], (h, h_dst))
        return h

sampler = dgl.dataloading.MultiLayerNeighborSampler([4, 4])
train_dataloader = dgl.dataloading.NodeDataLoader(
    graph, train_nids, sampler,
    device=device,
    batch_size=1024,
    shuffle=True,
    drop_last=False,
    num_workers=0
)
model = Model(graph.ndata['feat'].shape[1], 128, dataset.num_classes).to(device)

with tqdm.tqdm(train_dataloader) as tq:
    for step, (input_nodes, output_nodes, mfgs) in enumerate(tq):
        inputs = mfgs[0].srcdata['feat']
        labels = mfgs[-1].dstdata['label']
        predictions = model(mfgs, inputs)

Out:

  0%|          | 0/89 [00:00<?, ?it/s]
  6%|5         | 5/89 [00:00<00:01, 44.00it/s]
 11%|#1        | 10/89 [00:00<00:01, 45.23it/s]
 17%|#6        | 15/89 [00:00<00:01, 45.98it/s]
 22%|##2       | 20/89 [00:00<00:01, 46.39it/s]
 28%|##8       | 25/89 [00:00<00:01, 46.94it/s]
 34%|###3      | 30/89 [00:00<00:01, 46.97it/s]
 39%|###9      | 35/89 [00:00<00:01, 47.01it/s]
 45%|####4     | 40/89 [00:00<00:01, 47.46it/s]
 51%|#####     | 45/89 [00:00<00:00, 47.81it/s]
 56%|#####6    | 50/89 [00:01<00:00, 47.73it/s]
 62%|######1   | 55/89 [00:01<00:00, 47.93it/s]
 67%|######7   | 60/89 [00:01<00:00, 48.06it/s]
 73%|#######3  | 65/89 [00:01<00:00, 48.17it/s]
 79%|#######8  | 70/89 [00:01<00:00, 48.29it/s]
 84%|########4 | 75/89 [00:01<00:00, 48.36it/s]
 90%|########9 | 80/89 [00:01<00:00, 48.00it/s]
 96%|#########5| 85/89 [00:01<00:00, 47.73it/s]
100%|##########| 89/89 [00:01<00:00, 47.77it/s]

Both update_all and the functions in nn.functional namespace support MFGs, so you can migrate the code working for small 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 full-graph training and stochastic training.

Say you start with a GNN module that works for full-graph training only:

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.
    """
    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():
            g.ndata['h'] = h
            # update_all is a message passing API.
            g.update_all(message_func=fn.copy_u('h', 'm'), reduce_func=fn.mean('m', 'h_N'))
            h_N = g.ndata['h_N']
            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:

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:

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:

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:

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:

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

# 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

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:

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.
    """
    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

            g.srcdata['h'] = h_src
            # update_all is a message passing API.
            g.update_all(message_func=fn.copy_u('h', 'm'), reduce_func=fn.mean('m', 'h_N'))
            h_N = g.ndata['h_N']
            h_total = torch.cat([h_dst, h_N], dim=1)
            return self.linear(h_total)


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

Total running time of the script: ( 0 minutes 2.041 seconds)

Gallery generated by Sphinx-Gallery