Guide · Open source
How to use pytorch_geometric: a beginner's guide to PyG
Updated · written with AI from the project's own documentation and checked against our catalogue data
PyTorch Geometric (PyG) is a Python library built on PyTorch for writing and training graph neural networks (GNNs), models that learn from data shaped like networks such as citation graphs. It is aimed at Python developers who already know PyTorch and want ready-made graph methods. After this guide you will know what PyG is for, how it is installed, how a small GCN is trained on the Cora dataset, and where to go next.
Quick start
- 1Install prerequisites. Make sure Python and PyTorch are installed, then get the library from the project's README or documentation.
- 2Clone the repository. Run git clone https://github.com/pyg-team/pytorch_geometric to get the source code.
- 3Load a benchmark dataset. Use Planetoid with name='Cora' to download and load the citation graph.
- 4Define a GCN model. Build a two-layer model from GCNConv layers, taking node features and edge_index.
- 5Train with a standard loop. Run an Adam optimizer over 200 epochs using cross-entropy loss on the training mask.
- 6Extend with custom layers. Subclass MessagePassing when you need a layer that is not built in.
What PyG is and who it is for
PyG (PyTorch Geometric) is a library built upon PyTorch to easily write and train Graph Neural Networks for a wide range of applications related to structured data. It bundles methods for deep learning on graphs and other irregular structures, drawn from a variety of published papers.
It suits researchers who want implementations of published GNN methods, Python developers comfortable with PyTorch, and students learning graph machine learning with benchmarks such as Cora. It is less suited to standard tabular or image models, to people without Python or PyTorch experience, and to anyone who needs a finished no-code product, since it is a code library.
- Ready-made implementations of many published GNN architectures
- Mini-batch loaders for many small graphs or single giant graphs
- Multi-GPU support, torch.compile support and DataPipe support
- Common benchmark datasets and transforms for graphs, 3D meshes and point clouds
Install pytorch_geometric with a package manager
The prerequisites are Python and PyTorch. The project is distributed as a Python package, and the README's install instruction is to clone the repository from GitHub. Check the official documentation at pytorch-geometric.readthedocs.io for the current install options for your platform.
The README's direct command for getting the source is shown below.
- Install Python and PyTorch first
- Clone the repository to get the source code
- Confirm the package imports before you start a project
git clone https://github.com/pyg-team/pytorch_geometricTrain your first GNN on the Cora dataset
The quick tour trains a GNN that classifies papers in a citation graph. It loads the Cora dataset with Planetoid and builds a simple 2-layer GCN using the pre-defined GCNConv layer. The model's forward method takes node features x and the graph connectivity edge_index.
Training follows the standard PyTorch loop: a forward pass, a cross-entropy loss on the training mask, backpropagation, and an optimizer step. The README notes that evaluating final performance is covered in a separate example script.
- Load the data with Planetoid(root='.', name='Cora')
- Define the GCN model with two GCNConv layers
- Train with Adam at learning rate 0.01 for 200 epochs, as in the quick tour
import torch
from torch import Tensor
from torch_geometric.nn import GCNConv
from torch_geometric.datasets import Planetoid
dataset = Planetoid(root='.', name='Cora')
class GCN(torch.nn.Module):
def __init__(self, in_channels, hidden_channels, out_channels):
super().__init__()
self.conv1 = GCNConv(in_channels, hidden_channels)
self.conv2 = GCNConv(hidden_channels, out_channels)
def forward(self, x: Tensor, edge_index: Tensor) -> Tensor:
x = self.conv1(x, edge_index).relu()
x = self.conv2(x, edge_index)
return x
model = GCN(dataset.num_features, 16, dataset.num_classes)Run the training loop
Once the model is defined, the training loop uses the first graph in the dataset, a standard Adam optimizer, and cross-entropy loss restricted to the training nodes. This is the same pattern you would use for any PyTorch model.
- data = dataset[0] selects the graph
- Loss is computed on data.train_mask only
- Call optimizer.zero_grad(), loss.backward() and optimizer.step() each iteration
import torch.nn.functional as F
data = dataset[0]
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
for epoch in range(200):
pred = model(data.x, data.edge_index)
loss = F.cross_entropy(pred[data.train_mask], data.y[data.train_mask])
# Backpropagation
optimizer.zero_grad()
loss.backward()
optimizer.step()Write a custom GNN layer with MessagePassing
PyG makes it possible to implement your own GNN layers. The README gives an example of the edge convolutional layer from Wang et al. The layer subclasses MessagePassing with max aggregation, builds an MLP, and defines message and forward methods. The accompanying tutorial is linked from the project's documentation.
This is the path for researchers who want to change an existing architecture or try a new one, using the library's message passing API and its operators and utility functions.
- Subclass MessagePassing and pass aggr="max" to the constructor
- Put the per-edge logic in message()
- Call self.propagate() from forward()
import torch
from torch import Tensor
from torch.nn import Sequential, Linear, ReLU
from torch_geometric.nn import MessagePassing
class EdgeConv(MessagePassing):
def __init__(self, in_channels, out_channels):
super().__init__(aggr="max")
self.mlp = Sequential(
Linear(2 * in_channels, out_channels),
ReLU(),
Linear(out_channels, out_channels),
)
def forward(self, x: Tensor, edge_index: Tensor) -> Tensor:
return self.propagate(edge_index, x=x)
def message(self, x_j: Tensor, x_i: Tensor) -> Tensor:
edge_features = torch.cat([x_i, x_j - x_i], dim=-1)
return self.mlp(edge_features)Understand the architecture before scaling up
The README describes PyG as having four components: an engine built on PyTorch with torch.compile and TorchScript support, a storage layer for data processing and loading (including sampling for large graphs), a set of operators for building GNN blocks, and a set of models and examples on standard benchmarks.
The engine also uses efficient CPU/CUDA libraries for sparse data, such as pyg-lib. For graphs too large for one batch, the storage layer's sampling and mini-batch loaders are the parts to read about in the documentation.
- Engine: PyTorch, torch.compile, TorchScript, pyg-lib
- Storage: data processing, transforms, loaders, sampling
- Operators: reusable GNN building blocks
- Models: implemented GNN architectures and examples
What people use it for
- Classifying papers in a citation graph such as Cora
- Training a GNN on molecules or other network-shaped data
- Experimenting with published GNN architectures for a research project
- Training GNNs on large graphs using mini-batch loaders and sampling
- Building a custom graph layer by extending MessagePassing
Frequently asked questions
Is pytorch_geometric free to use?
PyG is released under the MIT licence, according to the project's repository details. The MIT licence allows use, modification and distribution, so check the licence text for full terms before using it in a product.
What do I need to use pytorch_geometric?
You need Python and PyTorch. The quick tour assumes familiarity with PyTorch training loops, so basic PyTorch experience is strongly recommended.
How do I install pytorch_geometric?
The README's install instruction is to clone the repository with git clone https://github.com/pyg-team/pytorch_geometric. For package-based installation steps, use the documentation at pytorch-geometric.readthedocs.io.
Is pytorch_geometric good for beginners?
It is suited to Python developers already comfortable with PyTorch and to students learning graph machine learning. Someone with no PyTorch background will find the quick tour hard to follow without learning PyTorch first.
What are the alternatives to pytorch_geometric?
Comparable projects named in the analysis include DGL (Deep Graph Library), Spektral, StellarGraph and CogDL. Choose based on your framework preference and the models you need.
Can pytorch_geometric handle large graphs?
The README says the library includes mini-batch loaders for many small and single giant graphs, and sampling solutions for training GNNs on large-scale graphs. It also mentions multi-GPU support.
New agent skills, repos and AI tools — every week
The best new skills and open-source projects, the fastest-growing repos, and one free prompt. Five minutes to read. Unsubscribe anytime.
Our verdict
PyG is a strong choice for Python developers who know PyTorch and want ready-made graph neural network methods, benchmark datasets and mini-batch loaders for large graphs. It is not the right tool if you only need tabular or image models, have no PyTorch background, or want a finished no-code product, in which case look at a higher-level tool instead.
Install options & downloads