DGL
2.5

Get Started

  • Install and Setup
  • A Blitz Introduction to DGL

Advanced Materials

  • ๐Ÿ†• Stochastic Training of GNNs with GraphBolt
    • Neighbor Sampling Overview
    • Node Classification
    • Link Prediction
    • Multi-GPU Node Classification
    • Composing OnDiskDataset from raw data
  • User Guide
  • ็”จๆˆทๆŒ‡ๅ—ใ€ๅŒ…ๅซ่ฟ‡ๆ—ถไฟกๆฏใ€‘
  • ์‚ฌ์šฉ์ž ๊ฐ€์ด๋“œ[์‹œ๋Œ€์— ๋’ค์ณ์ง„]
  • ๐Ÿ†• Tutorial: Graph Transformer
  • Tutorials: dgl.sparse
  • Training on CPUs
  • Training on Multiple GPUs
  • Distributed training
  • Paper Study with DGL

API Reference

  • dgl
  • dgl.data
  • dgl.dataloading
  • dgl.DGLGraph
  • dgl.distributed
  • dgl.function
  • dgl.geometry
  • ๐Ÿ†• dgl.graphbolt
  • dgl.nn (PyTorch)
  • dgl.nn.functional
  • dgl.ops
  • dgl.optim
  • dgl.sampling
  • dgl.sparse
  • dgl.multiprocessing
  • dgl.transforms
  • User-defined Functions

Notes

  • Contribute to DGL
  • DGL Foreign Function Interface (FFI)
  • Performance Benchmarks

Misc

  • Frequently Asked Questions (FAQ)
  • Environment Variables
  • Resources
DGL
  • ๐Ÿ†• Stochastic Training of GNNs with GraphBolt
  • Link Prediction
  • View page source

Link Prediction๏ƒ

Open In Colab GitHub

This tutorial will show how to train a multi-layer GraphSAGE for link prediction on CoraGraphDataset. The dataset contains 2708 nodes and 10556 edges.

By the end of this tutorial, you will be able to

  • Train a GNN model for link prediction on target device with DGLโ€™s neighbor sampling components.

Install DGL package๏ƒ

[1]:
# Install required packages.
import os
import torch
os.environ['TORCH'] = torch.__version__
os.environ['DGLBACKEND'] = "pytorch"

# Install the CPU version in default. If you want to install CUDA version,
# please refer to https://www.dgl.ai/pages/start.html and change runtime type
# accordingly.
device = torch.device("cpu")
!pip install --pre dgl -f https://data.dgl.ai/wheels-test/repo.html

try:
    import dgl
    import dgl.graphbolt as gb
    installed = True
except ImportError as error:
    installed = False
    print(error)
print("DGL installed!" if installed else "DGL not found!")
Looking in links: https://data.dgl.ai/wheels-test/repo.html
Requirement already satisfied: dgl in /opt/conda/envs/dgl-dev-cpu/lib/python3.10/site-packages (2.2a240410)
Requirement already satisfied: numpy>=1.14.0 in /opt/conda/envs/dgl-dev-cpu/lib/python3.10/site-packages (from dgl) (1.26.4)
Requirement already satisfied: scipy>=1.1.0 in /opt/conda/envs/dgl-dev-cpu/lib/python3.10/site-packages (from dgl) (1.14.0)
Requirement already satisfied: networkx>=2.1 in /opt/conda/envs/dgl-dev-cpu/lib/python3.10/site-packages (from dgl) (3.3)
Requirement already satisfied: requests>=2.19.0 in /opt/conda/envs/dgl-dev-cpu/lib/python3.10/site-packages (from dgl) (2.32.3)
Requirement already satisfied: tqdm in /opt/conda/envs/dgl-dev-cpu/lib/python3.10/site-packages (from dgl) (4.66.5)
Requirement already satisfied: psutil>=5.8.0 in /opt/conda/envs/dgl-dev-cpu/lib/python3.10/site-packages (from dgl) (6.0.0)
Requirement already satisfied: torchdata>=0.5.0 in /opt/conda/envs/dgl-dev-cpu/lib/python3.10/site-packages (from dgl) (0.7.1)
Requirement already satisfied: pandas in /opt/conda/envs/dgl-dev-cpu/lib/python3.10/site-packages (from dgl) (2.2.2)
Requirement already satisfied: charset-normalizer<4,>=2 in /opt/conda/envs/dgl-dev-cpu/lib/python3.10/site-packages (from requests>=2.19.0->dgl) (3.3.2)
Requirement already satisfied: idna<4,>=2.5 in /opt/conda/envs/dgl-dev-cpu/lib/python3.10/site-packages (from requests>=2.19.0->dgl) (3.8)
Requirement already satisfied: urllib3<3,>=1.21.1 in /opt/conda/envs/dgl-dev-cpu/lib/python3.10/site-packages (from requests>=2.19.0->dgl) (2.2.2)
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/envs/dgl-dev-cpu/lib/python3.10/site-packages (from requests>=2.19.0->dgl) (2024.7.4)
Requirement already satisfied: torch>=2 in /opt/conda/envs/dgl-dev-cpu/lib/python3.10/site-packages (from torchdata>=0.5.0->dgl) (2.4.0+cpu)
Requirement already satisfied: python-dateutil>=2.8.2 in /opt/conda/envs/dgl-dev-cpu/lib/python3.10/site-packages (from pandas->dgl) (2.9.0.post0)
Requirement already satisfied: pytz>=2020.1 in /opt/conda/envs/dgl-dev-cpu/lib/python3.10/site-packages (from pandas->dgl) (2024.1)
Requirement already satisfied: tzdata>=2022.7 in /opt/conda/envs/dgl-dev-cpu/lib/python3.10/site-packages (from pandas->dgl) (2024.1)
Requirement already satisfied: six>=1.5 in /opt/conda/envs/dgl-dev-cpu/lib/python3.10/site-packages (from python-dateutil>=2.8.2->pandas->dgl) (1.16.0)
Requirement already satisfied: filelock in /opt/conda/envs/dgl-dev-cpu/lib/python3.10/site-packages (from torch>=2->torchdata>=0.5.0->dgl) (3.15.4)
Requirement already satisfied: typing-extensions>=4.8.0 in /opt/conda/envs/dgl-dev-cpu/lib/python3.10/site-packages (from torch>=2->torchdata>=0.5.0->dgl) (4.12.2)
Requirement already satisfied: sympy in /opt/conda/envs/dgl-dev-cpu/lib/python3.10/site-packages (from torch>=2->torchdata>=0.5.0->dgl) (1.13.2)
Requirement already satisfied: jinja2 in /opt/conda/envs/dgl-dev-cpu/lib/python3.10/site-packages (from torch>=2->torchdata>=0.5.0->dgl) (3.1.4)
Requirement already satisfied: fsspec in /opt/conda/envs/dgl-dev-cpu/lib/python3.10/site-packages (from torch>=2->torchdata>=0.5.0->dgl) (2024.6.1)
Requirement already satisfied: MarkupSafe>=2.0 in /opt/conda/envs/dgl-dev-cpu/lib/python3.10/site-packages (from jinja2->torch>=2->torchdata>=0.5.0->dgl) (2.1.5)
Requirement already satisfied: mpmath<1.4,>=1.1.0 in /opt/conda/envs/dgl-dev-cpu/lib/python3.10/site-packages (from sympy->torch>=2->torchdata>=0.5.0->dgl) (1.3.0)
DGL installed!

Loading Dataset๏ƒ

cora is already prepared as BuiltinDataset in GraphBolt.

[2]:
dataset = gb.BuiltinDataset("cora-seeds").load()
Downloading datasets/cora-seeds.zip from https://data.dgl.ai/dataset/graphbolt/cora-seeds.zip...
Extracting file to datasets
Start to preprocess the on-disk dataset.
Finish preprocessing the on-disk dataset.
/home/ubuntu/regression_test/dgl/python/dgl/graphbolt/impl/ondisk_dataset.py:855: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.
  return torch.load(graph_topology.path)

Dataset consists of graph, feature and tasks. You can get the training-validation-test set from the tasks. Seed nodes and corresponding labels are already stored in each training-validation-test set. This dataset contains 2 tasks, one for node classification and the other for link prediction. We will use the link prediction task.

[3]:
graph = dataset.graph.to(device)
feature = dataset.feature.to(device)
train_set = dataset.tasks[1].train_set
test_set = dataset.tasks[1].test_set
task_name = dataset.tasks[1].metadata["name"]
print(f"Task: {task_name}.")
Task: link_prediction.

Defining Neighbor Sampler and Data Loader in DGL๏ƒ

Different from the link prediction tutorial for full graph, a common practice to train GNN on large graphs is to iterate over the edges in minibatches, since computing the probability of all edges is usually impossible. For each minibatch of edges, you compute the output representation of their incident nodes using neighbor sampling and GNN, in a similar fashion introduced in the node classification tutorial.

To perform link prediction, you need to specify a negative sampler. DGL provides builtin negative samplers such as dgl.graphbolt.UniformNegativeSampler. Here this tutorial uniformly draws 5 negative examples per positive example.

Except for the negative sampler, the rest of the code is identical to the node classification tutorial.

[4]:
from functools import partial
datapipe = gb.ItemSampler(train_set, batch_size=256, shuffle=True)
datapipe = datapipe.copy_to(device)
datapipe = datapipe.sample_uniform_negative(graph, 5)
datapipe = datapipe.sample_neighbor(graph, [5, 5])
datapipe = datapipe.transform(partial(gb.exclude_seed_edges, include_reverse_edges=True))
datapipe = datapipe.fetch_feature(feature, node_feature_keys=["feat"])
train_dataloader = gb.DataLoader(datapipe)

You can peek one minibatch from train_dataloader and see what it will give you.

[5]:
data = next(iter(train_dataloader))
print(f"MiniBatch: {data}")
MiniBatch: MiniBatch(seeds=tensor([[1557, 2083],
                        [ 382,  191],
                        [1340, 1542],
                        ...,
                        [1028, 2462],
                        [1028,   25],
                        [1028, 2188]], dtype=torch.int32),
          sampled_subgraphs=[SampledSubgraphImpl(sampled_csc=CSCFormatBase(indptr=tensor([   0,    3,    8,  ..., 6968, 6970, 6972], dtype=torch.int32),
                                                                         indices=tensor([ 425,  384, 1280,  ..., 1918, 2425, 1279], dtype=torch.int32),
                                                           ),
                                               original_row_node_ids=tensor([1557, 2083,  382,  ..., 1799,  824, 1321], dtype=torch.int32),
                                               original_edge_ids=tensor([6176, 6177, 6179,  ..., 6285, 5739, 5740], dtype=torch.int32),
                                               original_column_node_ids=tensor([1557, 2083,  382,  ...,  561, 1590, 1442], dtype=torch.int32),
                            ),
                            SampledSubgraphImpl(sampled_csc=CSCFormatBase(indptr=tensor([   0,    3,    8,  ..., 3759, 3760, 3761], dtype=torch.int32),
                                                                         indices=tensor([ 425,  384, 1280,  ..., 2092, 1292, 2237], dtype=torch.int32),
                                                           ),
                                               original_row_node_ids=tensor([1557, 2083,  382,  ...,  561, 1590, 1442], dtype=torch.int32),
                                               original_edge_ids=tensor([ 6176,  6177,  6179,  ...,  6623,  6314, 10000], dtype=torch.int32),
                                               original_column_node_ids=tensor([1557, 2083,  382,  ..., 1672, 1601, 2462], dtype=torch.int32),
                            )],
          node_features={'feat': tensor([[0.0000, 0.0000, 0.0000,  ..., 0.0000, 0.0000, 0.0000],
                                [0.0000, 0.0000, 0.0000,  ..., 0.0000, 0.0000, 0.0000],
                                [0.0000, 0.0000, 0.0000,  ..., 0.0000, 0.0000, 0.0000],
                                ...,
                                [0.0000, 0.0000, 0.0556,  ..., 0.0000, 0.0000, 0.0000],
                                [0.0000, 0.0000, 0.0000,  ..., 0.0000, 0.0000, 0.0000],
                                [0.0000, 0.0000, 0.0000,  ..., 0.0000, 0.0000, 0.0000]])},
          labels=tensor([1., 1., 1.,  ..., 0., 0., 0.]),
          input_nodes=tensor([1557, 2083,  382,  ..., 1799,  824, 1321], dtype=torch.int32),
          indexes=tensor([  0,   1,   2,  ..., 255, 255, 255]),
          edge_features=[{},
                        {}],
          compacted_seeds=tensor([[   0,    1],
                                  [   2,    3],
                                  [   4,    5],
                                  ...,
                                  [ 428, 1279],
                                  [ 428,  391],
                                  [ 428, 1089]], dtype=torch.int32),
          blocks=[Block(num_src_nodes=2528, num_dst_nodes=2238, num_edges=6972),
                 Block(num_src_nodes=2238, num_dst_nodes=1280, num_edges=3761)],
       )

Defining Model for Node Representation๏ƒ

Letโ€™s consider training a 2-layer GraphSAGE with neighbor sampling. The model can be written as follows:

[6]:
import dgl.nn as dglnn
import torch.nn as nn
import torch.nn.functional as F


class SAGE(nn.Module):
    def __init__(self, in_size, hidden_size):
        super().__init__()
        self.layers = nn.ModuleList()
        self.layers.append(dglnn.SAGEConv(in_size, hidden_size, "mean"))
        self.layers.append(dglnn.SAGEConv(hidden_size, hidden_size, "mean"))
        self.hidden_size = hidden_size
        self.predictor = nn.Sequential(
            nn.Linear(hidden_size, hidden_size),
            nn.ReLU(),
            nn.Linear(hidden_size, 1),
        )

    def forward(self, blocks, x):
        hidden_x = x
        for layer_idx, (layer, block) in enumerate(zip(self.layers, blocks)):
            hidden_x = layer(block, hidden_x)
            is_last_layer = layer_idx == len(self.layers) - 1
            if not is_last_layer:
                hidden_x = F.relu(hidden_x)
        return hidden_x

Defining Traing Loop๏ƒ

The following initializes the model and defines the optimizer.

[7]:
in_size = feature.size("node", None, "feat")[0]
model = SAGE(in_size, 128).to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)

The following is the training loop for link prediction and evaluation.

[8]:
from tqdm.auto import tqdm
for epoch in range(3):
    model.train()
    total_loss = 0
    for step, data in tqdm(enumerate(train_dataloader)):
        # Get node pairs with labels for loss calculation.
        compacted_seeds = data.compacted_seeds.T
        labels = data.labels
        node_feature = data.node_features["feat"]
        # Convert sampled subgraphs to DGL blocks.
        blocks = data.blocks

        # Get the embeddings of the input nodes.
        y = model(blocks, node_feature)
        logits = model.predictor(
            y[compacted_seeds[0]] * y[compacted_seeds[1]]
        ).squeeze()

        # Compute loss.
        loss = F.binary_cross_entropy_with_logits(logits, labels)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        total_loss += loss.item()

    print(f"Epoch {epoch:03d} | Loss {total_loss / (step + 1):.3f}")
Epoch 000 | Loss 0.555
Epoch 001 | Loss 0.449
Epoch 002 | Loss 0.445

Evaluating Performance with Link Prediction๏ƒ

[9]:
model.eval()

datapipe = gb.ItemSampler(test_set, batch_size=256, shuffle=False)
datapipe = datapipe.copy_to(device)
# Since we need to use all neghborhoods for evaluation, we set the fanout
# to -1.
datapipe = datapipe.sample_neighbor(graph, [-1, -1])
datapipe = datapipe.fetch_feature(feature, node_feature_keys=["feat"])
eval_dataloader = gb.DataLoader(datapipe, num_workers=0)

logits = []
labels = []
for step, data in tqdm(enumerate(eval_dataloader)):
    # Get node pairs with labels for loss calculation.
    compacted_seeds = data.compacted_seeds.T
    label = data.labels

    # The features of sampled nodes.
    x = data.node_features["feat"]

    # Forward.
    y = model(data.blocks, x)
    logit = (
        model.predictor(y[compacted_seeds[0]] * y[compacted_seeds[1]])
        .squeeze()
        .detach()
    )

    logits.append(logit)
    labels.append(label)

logits = torch.cat(logits, dim=0)
labels = torch.cat(labels, dim=0)


# Compute the AUROC score.
from sklearn.metrics import roc_auc_score

auc = roc_auc_score(labels.cpu(), logits.cpu())
print("Link Prediction AUC:", auc)
Link Prediction AUC: 0.6789393769232497

Conclusion๏ƒ

In this tutorial, you have learned how to train a multi-layer GraphSAGE for link prediction with neighbor sampling.

Previous Next

ยฉ Copyright 2018, DGL Team.

Built with Sphinx using a theme provided by Read the Docs.
Read the Docs v: latest
Versions
Downloads
On Read the Docs
Project Home
Builds