Package: torch-geometric
Documentation|Paper|Colab Notebooks and Video Tutorials|External Resources|OGB ExamplesPyG(PyTorch Geometric)is a library built uponPyTorchto easily write and train Graph Neural Networks (GNNs) for a wide range of applications related to structured data.It consists of various methods for deep learning on graphs and other irregular structures, also known asgeometric deep learning, from a variety of published papers.
In addition, it consists of easy-to-use mini-batch loaders for operating on many small and single giant graphs,multi GPU-support,torch.compilesupport,DataPipesupport, a large number of common benchmark datasets (based on simple interfaces to create your own), theGraphGymexperiment manager, and helpful transforms, both for learning on arbitrary graphs as well as on 3D meshes or point clouds.Click here to join our Slack community!Library HighlightsQuick Tour for New UsersArchitecture OverviewImplemented GNN ModelsInstallationLibrary HighlightsWhether you are a machine learning researcher or first-time user of machine learning toolkits, here are some reasons to try out PyG for machine learning on graph-structured data.Easy-to-use and unified API:
All it takes is 10-20 lines of code to get started with training a GNN model (see the next section for aquick tour).
PyG isPyTorch-on-the-rocks: It utilizes a tensor-centric API and keeps design principles close to vanilla PyTorch.
If you are already familiar with PyTorch, utilizing PyG is straightforward.Comprehensive and well-maintained GNN models:
Most of the state-of-the-art Graph Neural Network architectures have been implemented by library developers or authors of research papers and are ready to be applied.Great flexibility:
Existing PyG models can easily be extended for conducting your own research with GNNs.
Making modifications to existing models or creating new architectures is simple, thanks to its easy-to-use message passing API, and a variety of operators and utility functions.Large-scale real-world GNN models:
We focus on the need of GNN applications in challenging real-world scenarios, and support learning on diverse types of graphs, including but not limited to: scalable GNNs for graphs with millions of nodes; dynamic GNNs for node predictions over time; heterogeneous GNNs with multiple node types and edge types.GraphGym integration: GraphGym lets users easily reproduce GNN experiments, is able to launch and analyze thousands of different GNN configurations, and is customizable by registering new modules to a GNN learning pipeline.Quick Tour for New UsersIn this quick tour, we highlight the ease of creating and training a GNN model with only a few lines of code.Train your own GNN modelIn the first glimpse of PyG, we implement the training of a GNN for classifying papers in a citation graph.
For this, we load theCoradataset, and create a simple 2-layer GCN model using the pre-definedGCNConv:importtorchfromtorchimportTensorfromtorch_geometric.nnimportGCNConvfromtorch_geometric.datasetsimportPlanetoiddataset=Planetoid(root='.',name='Cora')classGCN(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)defforward(self,x:Tensor,edge_index:Tensor)->Tensor:# x: Node feature matrix of shape [num_nodes, in_channels]# edge_index: Graph connectivity matrix of shape [2, num_edges]x=self.conv1(x,edge_index).relu()x=self.conv2(x,edge_index)returnxmodel=GCN(dataset.num_features,16,dataset.num_classes)We can now optimize the model in a training loop, similar to thestandard PyTorch training procedure.importtorch.nn.functionalasFdata=dataset[0]optimizer=torch.optim.Adam(model.parameters(),lr=0.01)forepochinrange(200):pred=model(data.x,data.edge_index)loss=F.cross_entropy(pred[data.train_mask],data.y[data.train_mask])# Backpropagationoptimizer.zero_grad()loss.backward()optimizer.step()More information about evaluating final model performance can be found in the correspondingexample.Create your own GNN layerIn addition to the easy application of existing GNNs, PyG makes it simple to implement custom Graph Neural Networks (seeherefor the accompanying tutorial).
For example, this is all it takes to implement theedge convolutional layerfrom Wanget al.:$$x_i^{\prime} ~ = ~ \max_{j \in \mathcal{N}(i)} ~ \textrm{MLP}_{\theta} \left( [ ~ x_i, ~ x_j - x_i ~ ] \right)$$importtorchfromtorchimportTensorfromtorch.nnimportSequential,Linear,ReLUfromtorch_geometric.nnimportMessagePassingclassEdgeConv(MessagePassing):def__init__(self,in_channels,out_channels):super().__init__(aggr="max")# "Max" aggregation.self.mlp=Sequential(Linear(2*in_channels,out_channels),ReLU(),Linear(out_channels,out_channels),)defforward(self,x:Tensor,edge_index:Tensor)->Tensor:# x: Node feature matrix of shape [num_nodes, in_channels]# edge_index: Graph connectivity matrix of shape [2, num_edges]returnself.propagate(edge_index,x=x)# shape [num_nodes, out_channels]defmessage(self,x_j:Tensor,x_i:Tensor)->Tensor:# x_j: Source node features of shape [num_edges, in_channels]# x_i: Target node features of shape [num_edges, in_channels]edge_features=torch.cat([x_i,x_j-x_i],dim=-1)returnself.mlp(edge_features)# shape [num_edges, out_channels]Manage experiments with GraphGymGraphGym allows you to manage and launch GNN experiments, using a highly modularized pipeline (seeherefor the accompanying tutorial).git clone https://github.com/pyg-team/pytorch_geometric.git
cd pytorch_geometric/graphgym
bash run_single.sh  # run a single GNN experiment (node/edge/graph-level)
bash run_batch.sh   # run a batch of GNN experiments, using differnt GNN designs/datasets/tasksUsers are highly encouraged to check out thedocumentation, which contains additional tutorials on the essential functionalities of PyG, including data handling, creation of datasets and a full list of implemented methods, transforms, and datasets.
For a quick start, check out ourexamplesinexamples/.Architecture OverviewPyG provides a multi-layer framework that enables users to build Graph Neural Network solutions on both low and high levels.
It comprises of the following components:The PyGengineutilizes the powerful PyTorch deep learning framework with fulltorch.compileandTorchScriptsupport, as well as additions of efficient CPU/CUDA libraries for operating on sparse data,e.g.,pyg-lib.The PyGstoragehandles data processing, transformation and loading pipelines. It is capable of handling and processing large-scale graph datasets, and provides effective solutions for heterogeneous graphs. It further provides a variety of sampling solutions, which enable training of GNNs on large-scale graphs.The PyGoperatorsbundle essential functionalities for implementing Graph Neural Networks. PyG supports important GNN building blocks that can be combined and applied to various parts of a GNN model, ensuring rich flexibility of GNN design.Finally, PyG provides an abundant set of GNNmodels, and examples that showcase GNN models on standard graph benchmarks. Thanks to its flexibility, users can easily build and modify custom GNN models to fit their specific needs.Implemented GNN ModelsWe list currently supported PyG models, layers and operators according to category:GNN layers:All Graph Neural Network layers are implemented via thenn.MessagePassinginterface.
A GNN layer specifies how to perform message passing,i.e.by designing different message, aggregation and update functions as definedhere.
These GNN layers can be stacked together to create Graph Neural Network models.GCNConvfrom Kipf and Welling:Semi-Supervised Classification with Graph Convolutional Networks(ICLR 2017) [Example]ChebConvfrom Defferrardet al.:Convolutional Neural Networks on Graphs with Fast Localized Spectral Filtering(NIPS 2016) [Example]GATConvfrom Veličkovićet al.:Graph Attention Networks(ICLR 2018) [Example]Expand to see all implemented GNN layers...GCN2Convfrom Chenet al.:Simple and Deep Graph Convolutional Networks(ICML 2020) [Example1,Example2]SplineConvfrom Feyet al.:SplineCNN: Fast Geometric Deep Learning with Continuous B-Spline Kernels(CVPR 2018) [Example1,Example2]NNConvfrom Gilmeret al.:Neural Message Passing for Quantum Chemistry(ICML 2017) [Example1,Example2]CGConvfrom Xie and Grossman:Crystal Graph Convolutional Neural Networks for an Accurate and Interpretable Prediction of Material Properties(Physical Review Letters 120, 2018)ECConvfrom Simonovsky and Komodakis:Edge-Conditioned Convolution on Graphs(CVPR 2017)EGConvfrom Tailoret al.:Adaptive Filters and Aggregator Fusion for Efficient Graph Convolutions(GNNSys 2021) [Example]GATv2Convfrom Brodyet al.:How Attentive are Graph Attention Networks?(ICLR 2022)TransformerConvfrom Shiet al.:Masked Label Prediction: Unified Message Passing Model for Semi-Supervised Classification(CoRR 2020) [Example]SAGEConvfrom Hamiltonet al.:Inductive Representation Learning on Large Graphs(NIPS 2017) [Example1,Example2,Example3,Example4]GraphConvfrom,e.g., Morriset al.:Weisfeiler and Leman Go Neural: Higher-order Graph Neural Networks(AAAI 2019)GatedGraphConvfrom Liet al.:Gated Graph Sequence Neural Networks(ICLR 2016)ResGatedGraphConvfrom Bresson and Laurent:Residual Gated Graph ConvNets(CoRR 2017)GINConvfrom Xuet al.:How Powerful are Graph Neural Networks?(ICLR 2019) [Example]GINEConvfrom Huet al.:Strategies for Pre-training Graph Neural Networks(ICLR 2020)ARMAConvfrom Bianchiet al.:Graph Neural Networks with Convolutional ARMA Filters(CoRR 2019) [Example]SGConvfrom Wuet al.:Simplifying Graph Convolutional Networks(CoRR 2019) [Example]APPNPfrom Klicperaet al.:Predict then Propagate: Graph Neural Networks meet Personalized PageRank(ICLR 2019) [Example]MFConvfrom Duvenaudet al.:Convolutional Networks on Graphs for Learning Molecular Fingerprints(NIPS 2015)AGNNConvfrom Thekumparampilet al.:Attention-based Graph Neural Network for Semi-Supervised Learning(CoRR 2017) [Example]TAGConvfrom Duet al.:Topology Adaptive Graph Convolutional Networks(CoRR 2017) [Example]PNAConvfrom Corsoet al.:Principal Neighbourhood Aggregation for Graph Nets(CoRR 2020) [Example]FAConvfrom Boet al.:Beyond Low-Frequency Information in Graph Convolutional Networks(AAAI 2021)PDNConvfrom Rozemberczkiet al.:Pathfinder Discovery Networks for Neural Message Passing(WWW 2021)RGCNConvfrom Schlichtkrullet al.:Modeling Relational Data with Graph Convolutional Networks(ESWC 2018) [Example1,Example2]RGATConvfrom Busbridgeet al.:Relational Graph Attention Networks(CoRR 2019) [Example]FiLMConvfrom Brockschmidt:GNN-FiLM: Graph Neural Networks with Feature-wise Linear Modulation(ICML 2020) [Example]SignedConvfrom Derret al.:Signed Graph Convolutional Network(ICDM 2018) [Example]DNAConvfrom Fey:Just Jump: Dynamic Neighborhood Aggregation in Graph Neural Networks(ICLR-W 2019) [Example]PANConvfrom Maet al.:Path Integral Based Convolution and Pooling for Graph Neural Networks(NeurIPS 2020)PointNetConv(includingIterative Farthest Point Sampling, dynamic graph generation based onnearest neighborormaximum distance, andk-NN interpolationfor upsampling) from Qiet al.:PointNet: Deep Learning on Point Sets for 3D Classification and Segmentation(CVPR 2017) andPointNet++: Deep Hierarchical Feature Learning on Point Sets in a Metric Space(NIPS 2017) [Example1,Example2]EdgeConvfrom Wanget al.:Dynamic Graph CNN for Learning on Point Clouds(CoRR, 2018) [Example1,Example2]XConvfrom Liet al.:PointCNN: Convolution On X-Transformed Points(NeurIPS 2018) [Example]PPFConvfrom Denget al.:PPFNet: Global Context Aware Local Features for Robust 3D Point Matching(CVPR 2018)GMMConvfrom Montiet al.:Geometric Deep Learning on Graphs and Manifolds using Mixture Model CNNs(CVPR 2017)FeaStConvfrom Vermaet al.:FeaStNet: Feature-Steered Graph Convolutions for 3D Shape Analysis(CVPR 2018)PointTransformerConvfrom Zhaoet al.:Point Transformer(2020)HypergraphConvfrom Baiet al.:Hypergraph Convolution and Hypergraph Attention(CoRR 2019)GravNetConvfrom Qasimet al.:Learning Representations of Irregular Particle-detector Geometry with Distance-weighted Graph Networks(European Physics Journal C, 2019)SuperGATfrom Kim and Oh:How To Find Your Friendly Neighborhood: Graph Attention Design With Self-Supervision(ICLR 2021) [Example]HGTConvfrom Huet al.:Heterogeneous Graph Transformer(WWW 2020) [Example]HEATConvfrom Moet al.:Heterogeneous Edge-Enhanced Graph Attention Network For Multi-Agent Trajectory Prediction(CoRR 2021)SSGConvfrom Zhuet al.:Simple Spectral Graph Convolution(ICLR 2021)FusedGATConvfrom Zhanget al.:Understanding GNN Computational Graph: A Coordinated Computation, IO, and Memory Perspective(MLSys 2022)GPSConvfrom Rampášeket al.:Recipe for a General, Powerful, Scalable Graph Transformer(NeurIPS 2022) [Example]Pooling layers:Graph pooling layers combine the vectorial representations of a set of nodes in a graph (or a subgraph) into a single vector representation that summarizes its properties of nodes.
It is commonly applied to graph-level tasks, which require combining node features into a single graph representation.Top-K Poolingfrom Gao and Ji:Graph U-Nets(ICML 2019), Cangeaet al.:Towards Sparse Hierarchical Graph Classifiers(NeurIPS-W 2018) and Knyazevet al.:Understanding Attention and Generalization in Graph Neural Networks(ICLR-W 2019) [Example]DiffPoolfrom Yinget al.:Hierarchical Graph Representation Learning with Differentiable Pooling(NeurIPS 2018) [Example]Expand to see all implemented pooling layers...Attentional Aggregationfrom Liet al.:Graph Matching Networks for Learning the Similarity of Graph Structured Objects(ICML 2019) [Example]Set2Setfrom Vinyalset al.:Order Matters: Sequence to Sequence for Sets(ICLR 2016) [Example]Sort Aggregationfrom Zhanget al.:An End-to-End Deep Learning Architecture for Graph Classification(AAAI 2018) [Example]MinCut Poolingfrom Bianchiet al.:Spectral Clustering with Graph Neural Networks for Graph Pooling(ICML 2020) [Example]DMoN Poolingfrom Tsitsulinet al.:Graph Clustering with Graph Neural Networks(CoRR 2020) [Example]Graclus Poolingfrom Dhillonet al.:Weighted Graph Cuts without Eigenvectors: A Multilevel Approach(PAMI 2007) [Example]Voxel Grid Poolingfrom,e.g., Simonovsky and Komodakis:Dynamic Edge-Conditioned Filters in Convolutional Neural Networks on Graphs(CVPR 2017) [Example]SAG Poolingfrom Leeet al.:Self-Attention Graph Pooling(ICML 2019) and Knyazevet al.:Understanding Attention and Generalization in Graph Neural Networks(ICLR-W 2019) [Example]Edge Poolingfrom Diehlet al.:Towards Graph Pooling by Edge Contraction(ICML-W 2019) and Diehl:Edge Contraction Pooling for Graph Neural Networks(CoRR 2019) [Example]ASAPoolingfrom Ranjanet al.:ASAP: Adaptive Structure Aware Pooling for Learning Hierarchical Graph Representations(AAAI 2020) [Example]PANPoolingfrom Maet al.:Path Integral Based Convolution and Pooling for Graph Neural Networks(NeurIPS 2020)MemPoolingfrom Khasahmadiet al.:Memory-Based Graph Networks(ICLR 2020) [Example]Graph Multiset Transformerfrom Baeket al.:Accurate Learning of Graph Representations with Graph Multiset Pooling(ICLR 2021) [Example]Equilibrium Aggregationfrom Bartunovet al.:(UAI 2022) [Example]GNN models:Our supported GNN models incorporate multiple message passing layers, and users can directly use these pre-defined models to make predictions on graphs.
Unlike simple stacking of GNN layers, these models could involve pre-processing, additional learnable parameters, skip connections, graph coarsening, etc.SchNetfrom Schüttet al.:SchNet: A Continuous-filter Convolutional Neural Network for Modeling Quantum Interactions(NIPS 2017) [Example]DimeNetandDimeNetPlusPlusfrom Klicperaet al.:Directional Message Passing for Molecular Graphs(ICLR 2020) andFast and Uncertainty-Aware Directional Message Passing for Non-Equilibrium Molecules(NeurIPS-W 2020) [Example]Node2Vecfrom Grover and Leskovec:node2vec: Scalable Feature Learning for Networks(KDD 2016) [Example]Deep Graph Infomaxfrom Veličkovićet al.:Deep Graph Infomax(ICLR 2019) [Example1,Example2]Deep Multiplex Graph Infomaxfrom Parket al.:Unsupervised Attributed Multiplex Network Embedding(AAAI 2020) [Example]Masked Label Predictionfrom Shiet al.:Masked Label Prediction: Unified Message Passing Model for Semi-Supervised Classification(CoRR 2020) [Example]PMLPfrom Yanget al.:Graph Neural Networks are Inherently Good Generalizers: Insights by Bridging GNNs and MLPs(ICLR 2023)Expand to see all implemented GNN models...Jumping Knowledgefrom Xuet al.:Representation Learning on Graphs with Jumping Knowledge Networks(ICML 2018) [Example]AMetaLayerfor building any kind of graph network similar to theTensorFlow Graph Nets libraryfrom Battagliaet al.:Relational Inductive Biases, Deep Learning, and Graph Networks(CoRR 2018)MetaPath2Vecfrom Donget al.:metapath2vec: Scalable Representation Learning for Heterogeneous Networks(KDD 2017) [Example]All variants ofGraph AutoencodersandVariational Autoencodersfrom:Variational Graph Auto-Encodersfrom Kipf and Welling (NIPS-W 2016) [Example]Adversarially Regularized Graph Autoencoder for Graph Embeddingfrom Panet al.(IJCAI 2018) [Example]Simple and Effective Graph Autoencoders with One-Hop Linear Modelsfrom Salhaet al.(ECML 2020) [Example]SEALfrom Zhang and Chen:Link Prediction Based on Graph Neural Networks(NeurIPS 2018) [Example]RENetfrom Jinet al.:Recurrent Event Network for Reasoning over Temporal Knowledge Graphs(ICLR-W 2019) [Example]GraphUNetfrom Gao and Ji:Graph U-Nets(ICML 2019) [Example]AttentiveFPfrom Xionget al.:Pushing the Boundaries of Molecular Representation for Drug Discovery with the Graph Attention Mechanism(J. Med. Chem. 2020) [Example]DeepGCNand theGENConvfrom Liet al.:DeepGCNs: Can GCNs Go as Deep as CNNs?(ICCV 2019) andDeeperGCN: All You Need to Train Deeper GCNs(CoRR 2020) [Example]RECTfrom Wanget al.:Network Embedding with Completely-imbalanced Labels(TKDE 2020) [Example]GNNExplainerfrom Yinget al.:GNNExplainer: Generating Explanations for Graph Neural Networks(NeurIPS 2019) [Example1,Example2,Example3]Graph-less Neural Networksfrom Zhanget al.:Graph-less Neural Networks: Teaching Old MLPs New Tricks via Distillation(CoRR 2021) [Example]LINKXfrom Limet al.:Large Scale Learning on Non-Homophilous Graphs:
New Benchmarks and Strong Simple Methods(NeurIPS 2021) [Example]RevGNNfrom Liet al.:Training Graph Neural with 1000 Layers(ICML 2021) [Example]TransEfrom Bordeset al.:Translating Embeddings for Modeling Multi-Relational Data(NIPS 2013) [Example]ComplExfrom Trouillonet al.:Complex Embeddings for Simple Link Prediction(ICML 2016) [Example]DistMultfrom Yanget al.:Embedding Entities and Relations for Learning and Inference in Knowledge Bases(ICLR 2015) [Example]RotatEfrom Sunet al.:RotatE: Knowledge Graph Embedding by Relational Rotation in Complex Space(ICLR 2019) [Example]GNN operators and utilities:PyG comes with a rich set of neural network operators that are commonly used in many GNN models.
They follow an extensible design: It is easy to apply these operators and graph utilities to existing GNN layers and models to further enhance model performance.DropEdgefrom Ronget al.:DropEdge: Towards Deep Graph Convolutional Networks on Node Classification(ICLR 2020)DropNode,MaskFeatureandAddRandomEdgefrom Youet al.:Graph Contrastive Learning with Augmentations(NeurIPS 2020)DropPathfrom Liet al.:MaskGAE: Masked Graph Modeling Meets Graph Autoencoders(arXiv 2022)ShuffleNodefrom Veličkovićet al.:Deep Graph Infomax(ICLR 2019)GraphNormfrom Caiet al.:GraphNorm: A Principled Approach to Accelerating Graph Neural Network Training(ICML 2021)GDCfrom Klicperaet al.:Diffusion Improves Graph Learning(NeurIPS 2019) [Example]Expand to see all implemented GNN operators and utilities...GraphSizeNormfrom Dwivediet al.:Benchmarking Graph Neural Networks(CoRR 2020)PairNormfrom Zhao and Akoglu:PairNorm: Tackling Oversmoothing in GNNs(ICLR 2020)MeanSubtractionNormfrom Yanget al.:Revisiting "Over-smoothing" in Deep GCNs(CoRR 2020)DiffGroupNormfrom Zhouet al.:Towards Deeper Graph Neural Networks with Differentiable Group Normalization(NeurIPS 2020)Tree Decompositionfrom Jinet al.:Junction Tree Variational Autoencoder for Molecular Graph Generation(ICML 2018)TGNfrom Rossiet al.:Temporal Graph Networks for Deep Learning on Dynamic Graphs(GRL+ 2020) [Example]Weisfeiler Lehman Operatorfrom Weisfeiler and Lehman:A Reduction of a Graph to a Canonical Form and an Algebra Arising During this Reduction(Nauchno-Technicheskaya Informatsia 1968) [Example]Continuous Weisfeiler Lehman Operatorfrom Togninalliet al.:Wasserstein Weisfeiler-Lehman Graph Kernels(NeurIPS 2019)Label Propagationfrom Zhu and Ghahramani:Learning from Labeled and Unlabeled Data with Label Propagation(CMU-CALD 2002) [Example]Local Degree Profilefrom Cai and Wang:A Simple yet Effective Baseline for Non-attribute Graph Classification(CoRR 2018)CorrectAndSmoothfrom Huanget al.:Combining Label Propagation And Simple Models Out-performs Graph Neural Networks(CoRR 2020) [Example]GiniandBROregularization from Hendersonet al.:Improving Molecular Graph Neural Network Explainability with Orthonormalization and Induced Sparsity(ICML 2021)RootedEgoNetsandRootedRWSubgraphfrom Zhaoet al.:From Stars to Subgraphs: Uplifting Any GNN with Local Structure Awareness(ICLR 2022)FeaturePropagationfrom Rossiet al.:On the Unreasonable Effectiveness of Feature Propagation in Learning on Graphs with Missing Node Features(CoRR 2021)Scalable GNNs:PyG supports the implementation of Graph Neural Networks that can scale to large-scale graphs.
Such application is challenging since the entire graph, its associated features and the GNN parameters cannot fit into GPU memory.
Many state-of-the-art scalability approaches tackle this challenge by sampling neighborhoods for mini-batch training, graph clustering and partitioning, or by using simplified GNN models.
These approaches have been implemented in PyG, and can benefit from the above GNN layers, operators and models.NeighborLoaderfrom Hamiltonet al.:Inductive Representation Learning on Large Graphs(NIPS 2017) [Example1,Example2,Example3,Example4]ClusterGCNfrom Chianget al.:Cluster-GCN: An Efficient Algorithm for Training Deep and Large Graph Convolutional Networks(KDD 2019) [Example1,Example2]GraphSAINTfrom Zenget al.:GraphSAINT: Graph Sampling Based Inductive Learning Method(ICLR 2020) [Example]Expand to see all implemented scalable GNNs...ShaDowfrom Zenget al.:Decoupling the Depth and Scope of Graph Neural Networks(NeurIPS 2021) [Example]SIGNfrom Rossiet al.:SIGN: Scalable Inception Graph Neural Networks(CoRR 2020) [Example]HGTLoaderfrom Huet al.:Heterogeneous Graph Transformer(WWW 2020) [Example]InstallationPyG is available for Python 3.8 to Python 3.12.AnacondaYou can now install PyG viaAnacondafor all major OS/PyTorch/CUDA combinations 🤗
If you have not yet installed PyTorch, install it viacondaas described in theofficial PyTorch documentation.
Given that you have PyTorch installed (>=1.8.0), simply runconda install pyg -c pygPyPiFromPyG 2.3onwards, you can install and use PyGwithout any external libraryrequired except for PyTorch.
For this, simply runpip install torch_geometricAdditional LibrariesIf you want to utilize the full set of features from PyG, there exists several additional libraries you may want to install:pyg-lib: Heterogeneous GNN operators and graph sampling routinestorch-scatter: Accelerated and efficient sparse reductionstorch-sparse:SparseTensorsupporttorch-cluster: Graph clustering routinestorch-spline-conv:SplineConvsupportThese packages come with their own CPU and GPU kernel implementations based on thePyTorch C++/CUDA/hip(ROCm) extension interface.
For a basic usage of PyG, these dependencies arefully optional.
We recommend to start with a minimal installation, and install additional dependencies once you start to actually need them.For ease of installation of these extensions, we providepipwheels for all major OS/PyTorch/CUDA combinations, seehere.PyTorch 2.2To install the binaries for PyTorch 2.2.0, simply runpip install pyg_lib torch_scatter torch_sparse torch_cluster torch_spline_conv -f https://data.pyg.org/whl/torch-2.2.0+${CUDA}.htmlwhere${CUDA}should be replaced by eithercpu,cu118, orcu121depending on your PyTorch installation.cpucu118cu121Linux✅✅✅Windows✅✅✅macOS✅PyTorch 2.1To install the binaries for PyTorch 2.1.0, simply runpip install pyg_lib torch_scatter torch_sparse torch_cluster torch_spline_conv -f https://data.pyg.org/whl/torch-2.1.0+${CUDA}.htmlwhere${CUDA}should be replaced by eithercpu,cu118, orcu121depending on your PyTorch installation.cpucu118cu121Linux✅✅✅Windows✅✅✅macOS✅Note:Binaries of older versions are also provided for PyTorch 1.4.0, PyTorch 1.5.0, PyTorch 1.6.0, PyTorch 1.7.0/1.7.1, PyTorch 1.8.0/1.8.1, PyTorch 1.9.0, PyTorch 1.10.0/1.10.1/1.10.2, PyTorch 1.11.0, PyTorch 1.12.0/1.12.1, PyTorch 1.13.0/1.13.1, and PyTorch 2.0.0 (following the same procedure).For older versions, you might need to explicitly specify the latest supported version numberor install viapip install --no-indexin order to prevent a manual installation from source.
You can look up the latest supported version numberhere.NVIDIA PyG ContainerNVIDIA provides a PyG docker container for effortlessly training and deploying GPU accelerated GNNs with PyG, seehere.Nightly and MasterIn case you want to experiment with the latest PyG features which are not fully released yet, either install thenightly versionof PyG viapip install pyg-nightlyor install PyGfrom masterviapip install git+https://github.com/pyg-team/pytorch_geometric.gitROCm WheelsThe externalpyg-rocm-buildrepositoryprovides wheels and detailed instructions on how to install PyG for ROCm.
If you have any questions about it, please open an issuehere.CitePlease citeour paper(and the respective papers of the methods used) if you use this code in your own work:@inproceedings{Fey/Lenssen/2019,
  title={Fast Graph Representation Learning with {PyTorch Geometric}},
  author={Fey, Matthias and Lenssen, Jan E.},
  booktitle={ICLR Workshop on Representation Learning on Graphs and Manifolds},
  year={2019},
}Feel free toemail usif you wish your work to be listed in theexternal resources.
If you notice anything unexpected, please open anissueand let us know.
If you have any questions or are missing a specific feature, feel freeto discuss them with us.
We are motivated to constantly make PyG even better.