Unverified Commit 0a8c533a authored by Rhett Ying's avatar Rhett Ying Committed by GitHub
Browse files

[doc] add lp notebook for stochastic training (#6612)

parent 170fa8b7
...@@ -8,3 +8,4 @@ This tutorial introduces how to train GNNs with stochastic training. ...@@ -8,3 +8,4 @@ This tutorial introduces how to train GNNs with stochastic training.
:titlesonly: :titlesonly:
node_classification.nblink node_classification.nblink
link_prediction.nblink
{
"path": "../../../../notebooks/stochastic_training/link_prediction.ipynb"
}
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"private_outputs": true,
"provenance": [],
"authorship_tag": "ABX9TyOjqI7Q6kAUIF+Fhf3q8KUM",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"source": [
"# Link Prediction\n",
"\n",
"[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/dmlc/dgl/blob/master/notebooks/stochastic_training/link_prediction.ipynb) [![GitHub](https://img.shields.io/badge/-View%20on%20GitHub-181717?logo=github&logoColor=ffffff)](https://github.com/dmlc/dgl/blob/master/notebooks/stochastic_training/link_prediction.ipynb)\n",
"\n",
"This tutorial will show how to train a multi-layer GraphSAGE for link\n",
"prediction on [CoraGraphDataset](https://data.dgl.ai/dataset/cora_v2.zip).\n",
"The dataset contains 2708 nodes and 10556 edges.\n",
"\n",
"By the end of this tutorial, you will be able to\n",
"\n",
"- Train a GNN model for link prediction on target device with DGL's\n",
" neighbor sampling components.\n"
],
"metadata": {
"id": "Ow8CQmZIV8Yn"
}
},
{
"cell_type": "markdown",
"source": [
"## Install DGL package"
],
"metadata": {
"id": "onVijYWpWlMj"
}
},
{
"cell_type": "code",
"source": [
"# Install required packages.\n",
"import os\n",
"import torch\n",
"import numpy as np\n",
"os.environ['TORCH'] = torch.__version__\n",
"os.environ['DGLBACKEND'] = \"pytorch\"\n",
"\n",
"# Install the CPU version.\n",
"device = torch.device(\"cpu\")\n",
"!pip install --pre dgl -f https://data.dgl.ai/wheels-test/repo.html\n",
"\n",
"try:\n",
" import dgl\n",
" import dgl.graphbolt as gb\n",
" installed = True\n",
"except ImportError as error:\n",
" installed = False\n",
" print(error)\n",
"print(\"DGL installed!\" if installed else \"DGL not found!\")"
],
"metadata": {
"id": "QcpjTazg6hEo"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"## Loading Dataset\n",
"`cora` is already prepared as `BuiltinDataset` in **GraphBolt**.\n"
],
"metadata": {
"id": "OOKZxxT7W1Rz"
}
},
{
"cell_type": "code",
"source": [
"dataset = gb.BuiltinDataset(\"cora\").load()"
],
"metadata": {
"id": "RnJkkSKhWiUG"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"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."
],
"metadata": {
"id": "WxnTMEQXXKsM"
}
},
{
"cell_type": "code",
"source": [
"graph = dataset.graph\n",
"feature = dataset.feature\n",
"train_set = dataset.tasks[1].train_set\n",
"test_set = dataset.tasks[1].test_set\n",
"task_name = dataset.tasks[1].metadata[\"name\"]\n",
"print(f\"Task: {task_name}.\")"
],
"metadata": {
"id": "YCm8CGkOX9lK"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"## Defining Neighbor Sampler and Data Loader in DGL\n",
"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.\n",
"\n",
"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.\n",
"\n",
"Except for the negative sampler, the rest of the code is identical to the node classification tutorial.\n",
"\n"
],
"metadata": {
"id": "2y-P5omQYP00"
}
},
{
"cell_type": "code",
"source": [
"datapipe = gb.ItemSampler(train_set, batch_size=256, shuffle=True)\n",
"datapipe = datapipe.sample_uniform_negative(graph, 5)\n",
"datapipe = datapipe.sample_neighbor(graph, [5, 5, 5])\n",
"datapipe = datapipe.fetch_feature(feature, node_feature_keys=[\"feat\"])\n",
"datapipe = datapipe.to_dgl()\n",
"datapipe = datapipe.copy_to(device)\n",
"train_dataloader = gb.MultiProcessDataLoader(datapipe, num_workers=0)"
],
"metadata": {
"id": "LZgXGfBvYijJ"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"You can peek one minibatch from train_dataloader and see what it will give you.\n",
"\n"
],
"metadata": {
"id": "5sU_aulqYkwK"
}
},
{
"cell_type": "code",
"source": [
"data = next(iter(train_dataloader))\n",
"print(f\"DGLMiniBatch: {data}\")"
],
"metadata": {
"id": "euEdzmerYmZi"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"## Defining Model for Node Representation\n",
"Let’s consider training a 2-layer GraphSAGE with neighbor sampling. The model can be written as follows:\n"
],
"metadata": {
"id": "WYQqfrDWYtU0"
}
},
{
"cell_type": "code",
"source": [
"import dgl.nn as dglnn\n",
"import torch.nn as nn\n",
"import torch.nn.functional as F\n",
"\n",
"\n",
"class SAGE(nn.Module):\n",
" def __init__(self, in_size, hidden_size):\n",
" super().__init__()\n",
" self.layers = nn.ModuleList()\n",
" self.layers.append(dglnn.SAGEConv(in_size, hidden_size, \"mean\"))\n",
" self.layers.append(dglnn.SAGEConv(hidden_size, hidden_size, \"mean\"))\n",
" self.hidden_size = hidden_size\n",
" self.predictor = nn.Sequential(\n",
" nn.Linear(hidden_size, hidden_size),\n",
" nn.ReLU(),\n",
" nn.Linear(hidden_size, 1),\n",
" )\n",
"\n",
" def forward(self, blocks, x):\n",
" hidden_x = x\n",
" for layer_idx, (layer, block) in enumerate(zip(self.layers, blocks)):\n",
" hidden_x = layer(block, hidden_x)\n",
" is_last_layer = layer_idx == len(self.layers) - 1\n",
" if not is_last_layer:\n",
" hidden_x = F.relu(hidden_x)\n",
" return hidden_x"
],
"metadata": {
"id": "0qQbBwO7Y3-Q"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"## Defining Traing Loop\n",
"The following initializes the model and defines the optimizer.\n",
"\n"
],
"metadata": {
"id": "y23JppwHY5MC"
}
},
{
"cell_type": "code",
"source": [
"in_size = feature.size(\"node\", None, \"feat\")[0]\n",
"model = SAGE(in_size, 128).to(device)\n",
"optimizer = torch.optim.Adam(model.parameters(), lr=0.001)"
],
"metadata": {
"id": "omSIB_ePZACg"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Define utility function to vonvert the minibatch to a training pair and a label tensor.\n",
"\n"
],
"metadata": {
"id": "J9K1GUs4ZDYw"
}
},
{
"cell_type": "code",
"source": [
"def to_binary_link_dgl_computing_pack(data: gb.DGLMiniBatch):\n",
" \"\"\"Convert the minibatch to a training pair and a label tensor.\"\"\"\n",
" pos_src, pos_dst = data.positive_node_pairs\n",
" neg_src, neg_dst = data.negative_node_pairs\n",
" node_pairs = (\n",
" torch.cat((pos_src, neg_src), dim=0),\n",
" torch.cat((pos_dst, neg_dst), dim=0),\n",
" )\n",
" pos_label = torch.ones_like(pos_src)\n",
" neg_label = torch.zeros_like(neg_src)\n",
" labels = torch.cat([pos_label, neg_label], dim=0)\n",
" return (node_pairs, labels.float())"
],
"metadata": {
"id": "wvIJBPb7ZNUv"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"The following is the training loop for link prediction and evaluation.\n",
"\n"
],
"metadata": {
"id": "QyWtzNZcZRgp"
}
},
{
"cell_type": "code",
"source": [
"import tqdm\n",
"for epoch in range(3):\n",
" model.train()\n",
" total_loss = 0\n",
" for step, data in tqdm.tqdm(enumerate(train_dataloader)):\n",
" # Unpack MiniBatch.\n",
" compacted_pairs, labels = to_binary_link_dgl_computing_pack(data)\n",
" node_feature = data.node_features[\"feat\"]\n",
" # Convert sampled subgraphs to DGL blocks.\n",
" blocks = data.blocks\n",
"\n",
" # Get the embeddings of the input nodes.\n",
" y = model(blocks, node_feature)\n",
" logits = model.predictor(\n",
" y[compacted_pairs[0]] * y[compacted_pairs[1]]\n",
" ).squeeze()\n",
"\n",
" # Compute loss.\n",
" loss = F.binary_cross_entropy_with_logits(logits, labels)\n",
" optimizer.zero_grad()\n",
" loss.backward()\n",
" optimizer.step()\n",
"\n",
" total_loss += loss.item()\n",
"\n",
" print(f\"Epoch {epoch:03d} | Loss {total_loss / (step + 1):.3f}\")"
],
"metadata": {
"id": "SccLVrjSZSkd"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"## Evaluating Performance with Link Prediction\n"
],
"metadata": {
"id": "pxow2XSkZXoO"
}
},
{
"cell_type": "code",
"source": [
"model.eval()\n",
"\n",
"datapipe = gb.ItemSampler(test_set, batch_size=256, shuffle=False)\n",
"# Since we need to use all neghborhoods for evaluation, we set the fanout\n",
"# to -1.\n",
"datapipe = datapipe.sample_neighbor(graph, [-1, -1])\n",
"datapipe = datapipe.fetch_feature(feature, node_feature_keys=[\"feat\"])\n",
"datapipe = datapipe.to_dgl()\n",
"datapipe = datapipe.copy_to(device)\n",
"eval_dataloader = gb.MultiProcessDataLoader(datapipe, num_workers=0)\n",
"\n",
"logits = []\n",
"labels = []\n",
"for step, data in enumerate(eval_dataloader):\n",
" # Unpack MiniBatch.\n",
" compacted_pairs, label = to_binary_link_dgl_computing_pack(data)\n",
"\n",
" # The features of sampled nodes.\n",
" x = data.node_features[\"feat\"]\n",
"\n",
" # Forward.\n",
" y = model(data.blocks, x)\n",
" logit = (\n",
" model.predictor(y[compacted_pairs[0]] * y[compacted_pairs[1]])\n",
" .squeeze()\n",
" .detach()\n",
" )\n",
"\n",
" logits.append(logit)\n",
" labels.append(label)\n",
"\n",
"logits = torch.cat(logits, dim=0)\n",
"labels = torch.cat(labels, dim=0)\n",
"\n",
"\n",
"# Compute the AUROC score.\n",
"from sklearn.metrics import roc_auc_score\n",
"\n",
"auc = roc_auc_score(labels, logits)\n",
"print(\"Link Prediction AUC:\", auc)"
],
"metadata": {
"id": "IMulfsnIZZVh"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"## Conclusion\n",
"In this tutorial, you have learned how to train a multi-layer GraphSAGE for link prediction with neighbor sampling."
],
"metadata": {
"id": "KoCoIvqAZeCS"
}
}
]
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment